<commit_before>/*!
* ----------------------
* Keen IO Plugin
* Data Visualization
* ----------------------
*/

/*

  TODO:

  [ ] Build a more robust DataTable transformer
  [ ] ^Expose date parser for google charts tooltips (#70)
  [ ] ^Allow custom tooltips (#147)

*/

(function(lib){
  var Keen = lib || {};

  var errors = {
    "google-visualization-errors-0": "No results to visualize"
  };

  var chartTypes = ['AreaChart', 'BarChart', 'ColumnChart', 'LineChart', 'PieChart', 'Table'];
  var chartMap = {};

  var dataTypes = {
    // dataType           // chartTypes (namespace)
    // 'singular':        null,
    'categorical':        ['piechart', 'barchart', 'columnchart', 'table'],
    'cat-interval':       ['columnchart', 'barchart', 'table'],
    'cat-ordinal':        ['barchart', 'columnchart', 'areachart', 'linechart', 'table'],
    'chronological':      ['areachart', 'linechart', 'table'],
    'cat-chronological':  ['linechart', 'columnchart', 'barchart', 'areachart'],
    'nominal':            ['table'],
    'extraction':         ['table']
  };

  // Create chart types
  // -------------------------------
  Keen.utils.each(chartTypes, function (type) {
    var name = type.toLowerCase();
    chartMap[name] = {
      initialize: function(){
        // Nothing to do here
      },
      render: function(){
        var self = this;
        if (self.view._artifacts['googlechart']) {
          this.destroy();
        }
        self.view._artifacts['googlechart'] = self.view._artifacts['googlechart'] || new google.visualization[type](self.el());
        google.visualization.events.addListener(self.view._artifacts['googlechart'], 'error', function(stack){
          _handleErrors.call(self, stack);
        });
        this.update();
      },
      update: function(){
        var options = _getDefaultAttributes.call(this, type);
        Keen.utils.extend(options, this.chartOptions(), this.attributes());
        this.view._artifacts['datatable'] = google.visualization.arrayToDataTable(this.data());
        // if (this.view._artifacts['datatable']) {}
        if (this.view._artifacts['googlechart']) {
          this.view._artifacts['googlechart'].draw(this.view._artifacts['datatable'], options);
        }
      },
      destroy: function(){
        if (this.view._artifacts['googlechart']) {
          google.visualization.events.removeAllListeners(this.view._artifacts['googlechart']);
          this.view._artifacts['googlechart'].clearChart();
          this.view._artifacts['googlechart'] = null;
          this.view._artifacts['datatable'] = null;
        }
      }
    };
  });

  // Register library + types
  // -------------------------------

  Keen.Dataviz.register('google', chartMap, {
    capabilities: dataTypes,
    dependencies: [{
      type: 'script',
      url: 'https://www.google.com/jsapi',
      cb: function(done) {
        if(typeof google === 'undefined'){
          throw new Error("Problem loading Google Charts library. Please contact us!");
        } else {
          google.load('visualization', '1.1', {
              packages: ['corechart', 'table'],
              callback: function(){
                done();
              }
          });
        }
      }
    }]
  });

  function _handleErrors(stack){
    var message = errors[stack['id']] || stack['message'] || "An error occurred";
    this.error(message);
  }

  function _getDefaultAttributes(type){
    var output = {};
    switch (type.toLowerCase()) {

      case "areachart":
        output.lineWidth = 2;
        output.hAxis = {
          baselineColor: 'transparent',
          gridlines: { color: 'transparent' }
        };
        output.vAxis = {
          viewWindow: { min: 0 }
        };
        if (this.dataType() === "chronological") {
          output.legend = {
            position: "none"
          };
          output.chartArea = {
            width: "85%"
          };
        }
        break;

      case "barchart":
        output.hAxis = {
          viewWindow: { min: 0 }
        };
        output.vAxis = {
          baselineColor: 'transparent',
          gridlines: { color: 'transparent' }
        };
        if (this.dataType() === "chronological") {
          output.legend = {
            position: "none"
          };
        }
        break;

      case "columnchart":
        output.hAxis = {
          baselineColor: 'transparent',
          gridlines: { color: 'transparent' }
        };
        output.vAxis = {
          viewWindow: { min: 0 }
        };
        if (this.dataType() === "chronological") {
          output.legend = {
            position: "none"
          };
          output.chartArea = {
            width: "85%"
          };
        }
        break;

      case "linechart":
        output.lineWidth = 2;
        output.hAxis = {
          baselineColor: 'transparent',
          gridlines: { color: 'transparent' }
        };
        output.vAxis = {
          viewWindow: { min: 0 }
        };
        if (this.dataType() === "chronological") {
          output.legend = {
            position: "none"
          };
          output.chartArea = {
            width: "85%"
          };
        }
        break;

      case "piechart":
        output.sliceVisibilityThreshold = 0.01;
        break;

      case "table":
        break;
    }
    return output;
  }

})(Keen);
<commit_msg>add graceful error handler<commit_after>/*!
* ----------------------
* Keen IO Plugin
* Data Visualization
* ----------------------
*/

/*

  TODO:

  [ ] Build a more robust DataTable transformer
  [ ] ^Expose date parser for google charts tooltips (#70)
  [ ] ^Allow custom tooltips (#147)

*/

(function(lib){
  var Keen = lib || {};

  var errors = {
    "google-visualization-errors-0": "No results to visualize"
  };

  var chartTypes = ['AreaChart', 'BarChart', 'ColumnChart', 'LineChart', 'PieChart', 'Table'];
  var chartMap = {};

  var dataTypes = {
    // dataType           // chartTypes (namespace)
    // 'singular':        null,
    'categorical':        ['piechart', 'barchart', 'columnchart', 'table'],
    'cat-interval':       ['columnchart', 'barchart', 'table'],
    'cat-ordinal':        ['barchart', 'columnchart', 'areachart', 'linechart', 'table'],
    'chronological':      ['areachart', 'linechart', 'table'],
    'cat-chronological':  ['linechart', 'columnchart', 'barchart', 'areachart'],
    'nominal':            ['table'],
    'extraction':         ['table']
  };

  // Create chart types
  // -------------------------------
  Keen.utils.each(chartTypes, function (type) {
    var name = type.toLowerCase();
    chartMap[name] = {
      initialize: function(){
        // Nothing to do here
      },
      render: function(){
        if(!google) {
          this.error("The Google Charts library could not be loaded.");
          return;
        }
        var self = this;
        if (self.view._artifacts['googlechart']) {
          this.destroy();
        }
        self.view._artifacts['googlechart'] = self.view._artifacts['googlechart'] || new google.visualization[type](self.el());
        google.visualization.events.addListener(self.view._artifacts['googlechart'], 'error', function(stack){
          _handleErrors.call(self, stack);
        });
        this.update();
      },
      update: function(){
        var options = _getDefaultAttributes.call(this, type);
        Keen.utils.extend(options, this.chartOptions(), this.attributes());
        this.view._artifacts['datatable'] = google.visualization.arrayToDataTable(this.data());
        // if (this.view._artifacts['datatable']) {}
        if (this.view._artifacts['googlechart']) {
          this.view._artifacts['googlechart'].draw(this.view._artifacts['datatable'], options);
        }
      },
      destroy: function(){
        if (this.view._artifacts['googlechart']) {
          google.visualization.events.removeAllListeners(this.view._artifacts['googlechart']);
          this.view._artifacts['googlechart'].clearChart();
          this.view._artifacts['googlechart'] = null;
          this.view._artifacts['datatable'] = null;
        }
      }
    };
  });

  // Register library + types
  // -------------------------------

  Keen.Dataviz.register('google', chartMap, {
    capabilities: dataTypes,
    dependencies: [{
      type: 'script',
      url: 'https://www.google.com/jsapi',
      cb: function(done) {
        if(typeof google === 'undefined'){
          Keen.log("Problem loading Google Charts library. Please contact us!");
        } else {
          google.load('visualization', '1.1', {
              packages: ['corechart', 'table'],
              callback: function(){
                done();
              }
          });
        }
      }
    }]
  });

  function _handleErrors(stack){
    var message = errors[stack['id']] || stack['message'] || "An error occurred";
    this.error(message);
  }

  function _getDefaultAttributes(type){
    var output = {};
    switch (type.toLowerCase()) {

      case "areachart":
        output.lineWidth = 2;
        output.hAxis = {
          baselineColor: 'transparent',
          gridlines: { color: 'transparent' }
        };
        output.vAxis = {
          viewWindow: { min: 0 }
        };
        if (this.dataType() === "chronological") {
          output.legend = {
            position: "none"
          };
          output.chartArea = {
            width: "85%"
          };
        }
        break;

      case "barchart":
        output.hAxis = {
          viewWindow: { min: 0 }
        };
        output.vAxis = {
          baselineColor: 'transparent',
          gridlines: { color: 'transparent' }
        };
        if (this.dataType() === "chronological") {
          output.legend = {
            position: "none"
          };
        }
        break;

      case "columnchart":
        output.hAxis = {
          baselineColor: 'transparent',
          gridlines: { color: 'transparent' }
        };
        output.vAxis = {
          viewWindow: { min: 0 }
        };
        if (this.dataType() === "chronological") {
          output.legend = {
            position: "none"
          };
          output.chartArea = {
            width: "85%"
          };
        }
        break;

      case "linechart":
        output.lineWidth = 2;
        output.hAxis = {
          baselineColor: 'transparent',
          gridlines: { color: 'transparent' }
        };
        output.vAxis = {
          viewWindow: { min: 0 }
        };
        if (this.dataType() === "chronological") {
          output.legend = {
            position: "none"
          };
          output.chartArea = {
            width: "85%"
          };
        }
        break;

      case "piechart":
        output.sliceVisibilityThreshold = 0.01;
        break;

      case "table":
        break;
    }
    return output;
  }

})(Keen);
<|endoftext|>


<commit_before>var nopt = require("../")
  , test = require('tap').test
  , isWin = process.platform === 'win32'

test("passing a string results in a string", function (t) {
  var parsed = nopt({ key: String }, {}, ["--key", "myvalue"], 0)
  t.same(parsed.key, "myvalue")
  t.end()
})

// https://github.com/npm/nopt/issues/31
test("Empty String results in empty string, not true", function (t) {
  var parsed = nopt({ empty: String }, {}, ["--empty"], 0)
  t.same(parsed.empty, "")
  t.end()
})

test("~ path is resolved to $HOME", function (t) {
  var path = require("path")
  if (!process.env.HOME) process.env.HOME = "/tmp"
  var parsed = nopt({key: path}, {}, ["--key=~/val"], 0)
  t.same(parsed.key, path.resolve(process.env.HOME, "val"))
  t.end()
})

// https://github.com/npm/nopt/issues/24
test("Unknown options are not parsed as numbers", function (t) {
    var parsed = nopt({"parse-me": Number}, null, ['--leave-as-is=1.20', '--parse-me=1.20'], 0)
    t.equal(parsed['leave-as-is'], '1.20')
    t.equal(parsed['parse-me'], 1.2)
    t.end()
});

// https://github.com/npm/nopt/issues/48
test("Check types based on name of type", function (t) {
  var parsed = nopt({"parse-me": {name: "Number"}}, null, ['--parse-me=1.20'], 0)
  t.equal(parsed['parse-me'], 1.2)
  t.end()
})

test("Missing types are not parsed", function (t) {
  var parsed = nopt({"parse-me": {}}, null, ['--parse-me=1.20'], 0)
  //should only contain argv
  t.equal(Object.keys(parsed).length, 1)
  t.end()
})

test("Types passed without a name are not parsed", function (t) {
  var parsed = nopt({"parse-me": {}}, {}, ['--parse-me=1.20'], 0)
  //should only contain argv
  t.equal(Object.keys(parsed).length, 1)
  t.end()
})

test("other tests", function (t) {

  var util = require("util")
    , Stream = require("stream")
    , path = require("path")
    , url = require("url")

    , shorthands =
      { s : ["--loglevel", "silent"]
      , d : ["--loglevel", "info"]
      , dd : ["--loglevel", "verbose"]
      , ddd : ["--loglevel", "silly"]
      , noreg : ["--no-registry"]
      , reg : ["--registry"]
      , "no-reg" : ["--no-registry"]
      , silent : ["--loglevel", "silent"]
      , verbose : ["--loglevel", "verbose"]
      , h : ["--usage"]
      , H : ["--usage"]
      , "?" : ["--usage"]
      , help : ["--usage"]
      , v : ["--version"]
      , f : ["--force"]
      , desc : ["--description"]
      , "no-desc" : ["--no-description"]
      , "local" : ["--no-global"]
      , l : ["--long"]
      , p : ["--parseable"]
      , porcelain : ["--parseable"]
      , g : ["--global"]
      }

    , types =
      { aoa: Array
      , nullstream: [null, Stream]
      , date: Date
      , str: String
      , browser : String
      , cache : path
      , color : ["always", Boolean]
      , depth : Number
      , description : Boolean
      , dev : Boolean
      , editor : path
      , force : Boolean
      , global : Boolean
      , globalconfig : path
      , group : [String, Number]
      , gzipbin : String
      , logfd : [Number, Stream]
      , loglevel : ["silent","win","error","warn","info","verbose","silly"]
      , long : Boolean
      , "node-version" : [false, String]
      , npaturl : url
      , npat : Boolean
      , "onload-script" : [false, String]
      , outfd : [Number, Stream]
      , parseable : Boolean
      , pre: Boolean
      , prefix: path
      , proxy : url
      , "rebuild-bundle" : Boolean
      , registry : url
      , searchopts : String
      , searchexclude: [null, String]
      , shell : path
      , t: [Array, String]
      , tag : String
      , tar : String
      , tmp : path
      , "unsafe-perm" : Boolean
      , usage : Boolean
      , user : String
      , username : String
      , userconfig : path
      , version : Boolean
      , viewer: path
      , _exit : Boolean
      , path: path
      }

  ; [["-v", {version:true}, []]
    ,["---v", {version:true}, []]
    ,["ls -s --no-reg connect -d",
      {loglevel:"info",registry:null},["ls","connect"]]
    ,["ls ---s foo",{loglevel:"silent"},["ls","foo"]]
    ,["ls --registry blargle", {}, ["ls"]]
    ,["--no-registry", {registry:null}, []]
    ,["--no-color true", {color:false}, []]
    ,["--no-color false", {color:true}, []]
    ,["--no-color", {color:false}, []]
    ,["--color false", {color:false}, []]
    ,["--color --logfd 7", {logfd:7,color:true}, []]
    ,["--color=true", {color:true}, []]
    ,["--logfd=10", {logfd:10}, []]
    ,["--tmp=/tmp -tar=gtar", {tmp: isWin ? "C:\\tmp" : "/tmp",tar:"gtar"},[]]
    ,["--tmp=tmp -tar=gtar",
      {tmp:path.resolve(process.cwd(), "tmp"),tar:"gtar"},[]]
    ,["--logfd x", {}, []]
    ,["a -true -- -no-false", {true:true},["a","-no-false"]]
    ,["a -no-false", {false:false},["a"]]
    ,["a -no-no-true", {true:true}, ["a"]]
    ,["a -no-no-no-false", {false:false}, ["a"]]
    ,["---NO-no-No-no-no-no-nO-no-no"+
      "-No-no-no-no-no-no-no-no-no"+
      "-no-no-no-no-NO-NO-no-no-no-no-no-no"+
      "-no-body-can-do-the-boogaloo-like-I-do"
     ,{"body-can-do-the-boogaloo-like-I-do":false}, []]
    ,["we are -no-strangers-to-love "+
      "--you-know=the-rules --and=so-do-i "+
      "---im-thinking-of=a-full-commitment "+
      "--no-you-would-get-this-from-any-other-guy "+
      "--no-gonna-give-you-up "+
      "-no-gonna-let-you-down=true "+
      "--no-no-gonna-run-around false "+
      "--desert-you=false "+
      "--make-you-cry false "+
      "--no-tell-a-lie "+
      "--no-no-and-hurt-you false"
     ,{"strangers-to-love":false
      ,"you-know":"the-rules"
      ,"and":"so-do-i"
      ,"you-would-get-this-from-any-other-guy":false
      ,"gonna-give-you-up":false
      ,"gonna-let-you-down":false
      ,"gonna-run-around":false
      ,"desert-you":false
      ,"make-you-cry":false
      ,"tell-a-lie":false
      ,"and-hurt-you":false
      },["we", "are"]]
    ,["-t one -t two -t three"
     ,{t: ["one", "two", "three"]}
     ,[]]
    ,["-t one -t null -t three four five null"
     ,{t: ["one", "null", "three"]}
     ,["four", "five", "null"]]
    ,["-t foo"
     ,{t:["foo"]}
     ,[]]
    ,["--no-t"
     ,{t:["false"]}
     ,[]]
    ,["-no-no-t"
     ,{t:["true"]}
     ,[]]
    ,["-aoa one -aoa null -aoa 100"
     ,{aoa:["one", null, '100']}
     ,[]]
    ,["-str 100"
     ,{str:"100"}
     ,[]]
    ,["--color always"
     ,{color:"always"}
     ,[]]
    ,["--no-nullstream"
     ,{nullstream:null}
     ,[]]
    ,["--nullstream false"
     ,{nullstream:null}
     ,[]]
    ,["--notadate=2011-01-25"
     ,{notadate: "2011-01-25"}
     ,[]]
    ,["--date 2011-01-25"
     ,{date: new Date("2011-01-25")}
     ,[]]
    ,["-cl 1"
     ,{config: true, length: 1}
     ,[]
     ,{config: Boolean, length: Number, clear: Boolean}
     ,{c: "--config", l: "--length"}]
    ,["--acount bla"
     ,{"acount":true}
     ,["bla"]
     ,{account: Boolean, credentials: Boolean, options: String}
     ,{a:"--account", c:"--credentials",o:"--options"}]
    ,["--clear"
     ,{clear:true}
     ,[]
     ,{clear:Boolean,con:Boolean,len:Boolean,exp:Boolean,add:Boolean,rep:Boolean}
     ,{c:"--con",l:"--len",e:"--exp",a:"--add",r:"--rep"}]
    ,["--file -"
     ,{"file":"-"}
     ,[]
     ,{file:String}
     ,{}]
    ,["--file -"
     ,{"file":true}
     ,["-"]
     ,{file:Boolean}
     ,{}]
    ,["--path"
     ,{"path":null}
     ,[]]
    ,["--path ."
     ,{"path":process.cwd()}
     ,[]]
    ].forEach(function (test) {
      var argv = test[0].split(/\s+/)
        , opts = test[1]
        , rem = test[2]
        , actual = nopt(test[3] || types, test[4] || shorthands, argv, 0)
        , parsed = actual.argv
      delete actual.argv
      for (var i in opts) {
        var e = JSON.stringify(opts[i])
          , a = JSON.stringify(actual[i] === undefined ? null : actual[i])
        if (e && typeof e === "object") {
          t.deepEqual(e, a)
        } else {
          t.equal(e, a)
        }
      }
      t.deepEqual(rem, parsed.remain)
    })
  t.end()
})
<commit_msg>test: choose test path based on platform<commit_after>var nopt = require("../")
  , test = require('tap').test
  , isWin = process.platform === 'win32'

test("passing a string results in a string", function (t) {
  var parsed = nopt({ key: String }, {}, ["--key", "myvalue"], 0)
  t.same(parsed.key, "myvalue")
  t.end()
})

// https://github.com/npm/nopt/issues/31
test("Empty String results in empty string, not true", function (t) {
  var parsed = nopt({ empty: String }, {}, ["--empty"], 0)
  t.same(parsed.empty, "")
  t.end()
})

test("~ path is resolved to " + (isWin ? '%USERPROFILE%' : '$HOME'), function (t) {
  var path = require("path")
    , the

  if (isWin) {
    the = {
      key: 'USERPROFILE',
      dir: 'C:\\temp',
      val: '~\\val'
    }
  } else {
    the = {
      key: 'HOME',
      dir: '/tmp',
      val: '~/val'
    }
  }
  if (!process.env[the.key]) process.env[the.key] = v.dir
  var parsed = nopt({key: path}, {}, ["--key=" + the.val], 0)
  t.same(parsed.key, path.resolve(process.env[the.key], "val"))
  t.end()
})

// https://github.com/npm/nopt/issues/24
test("Unknown options are not parsed as numbers", function (t) {
    var parsed = nopt({"parse-me": Number}, null, ['--leave-as-is=1.20', '--parse-me=1.20'], 0)
    t.equal(parsed['leave-as-is'], '1.20')
    t.equal(parsed['parse-me'], 1.2)
    t.end()
});

// https://github.com/npm/nopt/issues/48
test("Check types based on name of type", function (t) {
  var parsed = nopt({"parse-me": {name: "Number"}}, null, ['--parse-me=1.20'], 0)
  t.equal(parsed['parse-me'], 1.2)
  t.end()
})

test("Missing types are not parsed", function (t) {
  var parsed = nopt({"parse-me": {}}, null, ['--parse-me=1.20'], 0)
  //should only contain argv
  t.equal(Object.keys(parsed).length, 1)
  t.end()
})

test("Types passed without a name are not parsed", function (t) {
  var parsed = nopt({"parse-me": {}}, {}, ['--parse-me=1.20'], 0)
  //should only contain argv
  t.equal(Object.keys(parsed).length, 1)
  t.end()
})

test("other tests", function (t) {

  var util = require("util")
    , Stream = require("stream")
    , path = require("path")
    , url = require("url")

    , shorthands =
      { s : ["--loglevel", "silent"]
      , d : ["--loglevel", "info"]
      , dd : ["--loglevel", "verbose"]
      , ddd : ["--loglevel", "silly"]
      , noreg : ["--no-registry"]
      , reg : ["--registry"]
      , "no-reg" : ["--no-registry"]
      , silent : ["--loglevel", "silent"]
      , verbose : ["--loglevel", "verbose"]
      , h : ["--usage"]
      , H : ["--usage"]
      , "?" : ["--usage"]
      , help : ["--usage"]
      , v : ["--version"]
      , f : ["--force"]
      , desc : ["--description"]
      , "no-desc" : ["--no-description"]
      , "local" : ["--no-global"]
      , l : ["--long"]
      , p : ["--parseable"]
      , porcelain : ["--parseable"]
      , g : ["--global"]
      }

    , types =
      { aoa: Array
      , nullstream: [null, Stream]
      , date: Date
      , str: String
      , browser : String
      , cache : path
      , color : ["always", Boolean]
      , depth : Number
      , description : Boolean
      , dev : Boolean
      , editor : path
      , force : Boolean
      , global : Boolean
      , globalconfig : path
      , group : [String, Number]
      , gzipbin : String
      , logfd : [Number, Stream]
      , loglevel : ["silent","win","error","warn","info","verbose","silly"]
      , long : Boolean
      , "node-version" : [false, String]
      , npaturl : url
      , npat : Boolean
      , "onload-script" : [false, String]
      , outfd : [Number, Stream]
      , parseable : Boolean
      , pre: Boolean
      , prefix: path
      , proxy : url
      , "rebuild-bundle" : Boolean
      , registry : url
      , searchopts : String
      , searchexclude: [null, String]
      , shell : path
      , t: [Array, String]
      , tag : String
      , tar : String
      , tmp : path
      , "unsafe-perm" : Boolean
      , usage : Boolean
      , user : String
      , username : String
      , userconfig : path
      , version : Boolean
      , viewer: path
      , _exit : Boolean
      , path: path
      }

  ; [["-v", {version:true}, []]
    ,["---v", {version:true}, []]
    ,["ls -s --no-reg connect -d",
      {loglevel:"info",registry:null},["ls","connect"]]
    ,["ls ---s foo",{loglevel:"silent"},["ls","foo"]]
    ,["ls --registry blargle", {}, ["ls"]]
    ,["--no-registry", {registry:null}, []]
    ,["--no-color true", {color:false}, []]
    ,["--no-color false", {color:true}, []]
    ,["--no-color", {color:false}, []]
    ,["--color false", {color:false}, []]
    ,["--color --logfd 7", {logfd:7,color:true}, []]
    ,["--color=true", {color:true}, []]
    ,["--logfd=10", {logfd:10}, []]
    ,["--tmp=/tmp -tar=gtar", {tmp: isWin ? "C:\\tmp" : "/tmp",tar:"gtar"},[]]
    ,["--tmp=tmp -tar=gtar",
      {tmp:path.resolve(process.cwd(), "tmp"),tar:"gtar"},[]]
    ,["--logfd x", {}, []]
    ,["a -true -- -no-false", {true:true},["a","-no-false"]]
    ,["a -no-false", {false:false},["a"]]
    ,["a -no-no-true", {true:true}, ["a"]]
    ,["a -no-no-no-false", {false:false}, ["a"]]
    ,["---NO-no-No-no-no-no-nO-no-no"+
      "-No-no-no-no-no-no-no-no-no"+
      "-no-no-no-no-NO-NO-no-no-no-no-no-no"+
      "-no-body-can-do-the-boogaloo-like-I-do"
     ,{"body-can-do-the-boogaloo-like-I-do":false}, []]
    ,["we are -no-strangers-to-love "+
      "--you-know=the-rules --and=so-do-i "+
      "---im-thinking-of=a-full-commitment "+
      "--no-you-would-get-this-from-any-other-guy "+
      "--no-gonna-give-you-up "+
      "-no-gonna-let-you-down=true "+
      "--no-no-gonna-run-around false "+
      "--desert-you=false "+
      "--make-you-cry false "+
      "--no-tell-a-lie "+
      "--no-no-and-hurt-you false"
     ,{"strangers-to-love":false
      ,"you-know":"the-rules"
      ,"and":"so-do-i"
      ,"you-would-get-this-from-any-other-guy":false
      ,"gonna-give-you-up":false
      ,"gonna-let-you-down":false
      ,"gonna-run-around":false
      ,"desert-you":false
      ,"make-you-cry":false
      ,"tell-a-lie":false
      ,"and-hurt-you":false
      },["we", "are"]]
    ,["-t one -t two -t three"
     ,{t: ["one", "two", "three"]}
     ,[]]
    ,["-t one -t null -t three four five null"
     ,{t: ["one", "null", "three"]}
     ,["four", "five", "null"]]
    ,["-t foo"
     ,{t:["foo"]}
     ,[]]
    ,["--no-t"
     ,{t:["false"]}
     ,[]]
    ,["-no-no-t"
     ,{t:["true"]}
     ,[]]
    ,["-aoa one -aoa null -aoa 100"
     ,{aoa:["one", null, '100']}
     ,[]]
    ,["-str 100"
     ,{str:"100"}
     ,[]]
    ,["--color always"
     ,{color:"always"}
     ,[]]
    ,["--no-nullstream"
     ,{nullstream:null}
     ,[]]
    ,["--nullstream false"
     ,{nullstream:null}
     ,[]]
    ,["--notadate=2011-01-25"
     ,{notadate: "2011-01-25"}
     ,[]]
    ,["--date 2011-01-25"
     ,{date: new Date("2011-01-25")}
     ,[]]
    ,["-cl 1"
     ,{config: true, length: 1}
     ,[]
     ,{config: Boolean, length: Number, clear: Boolean}
     ,{c: "--config", l: "--length"}]
    ,["--acount bla"
     ,{"acount":true}
     ,["bla"]
     ,{account: Boolean, credentials: Boolean, options: String}
     ,{a:"--account", c:"--credentials",o:"--options"}]
    ,["--clear"
     ,{clear:true}
     ,[]
     ,{clear:Boolean,con:Boolean,len:Boolean,exp:Boolean,add:Boolean,rep:Boolean}
     ,{c:"--con",l:"--len",e:"--exp",a:"--add",r:"--rep"}]
    ,["--file -"
     ,{"file":"-"}
     ,[]
     ,{file:String}
     ,{}]
    ,["--file -"
     ,{"file":true}
     ,["-"]
     ,{file:Boolean}
     ,{}]
    ,["--path"
     ,{"path":null}
     ,[]]
    ,["--path ."
     ,{"path":process.cwd()}
     ,[]]
    ].forEach(function (test) {
      var argv = test[0].split(/\s+/)
        , opts = test[1]
        , rem = test[2]
        , actual = nopt(test[3] || types, test[4] || shorthands, argv, 0)
        , parsed = actual.argv
      delete actual.argv
      for (var i in opts) {
        var e = JSON.stringify(opts[i])
          , a = JSON.stringify(actual[i] === undefined ? null : actual[i])
        if (e && typeof e === "object") {
          t.deepEqual(e, a)
        } else {
          t.equal(e, a)
        }
      }
      t.deepEqual(rem, parsed.remain)
    })
  t.end()
})
<|endoftext|>


<commit_before>/*
 *  all.js
 *
 *  David Janes
 *  IOTDB.org
 *  2017-08-06
 *
 *  Copyright [2013-2018] [David P. Janes]
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

"use strict";

const _ = require("iotdb-helpers");

const assert = require("assert");

const mongo = require("../lib");
const util = require("../lib/util");

/**
 *  Make a mongo looking query from a DynamoDB one
 */
const _make_query = _query => {
    const query = _.d.clone.shallow(_query || {})

    _.keys(query)
        .filter(query_key => _.is.Array(query[query_key]))
        .forEach(query_key => {
            const parts = query[query_key];

            let position = 0;
            while (position < parts.length) {
                let comparitor;
                let q;

                switch (parts[position].toLowerCase()) {
                case "=":
                case "eq":
                    q = {
                        "$eq": parts[position + 1]
                    }

                    position += 2;
                    break;

                case "<": case "lt":
                    q = {
                        "$lt": parts[position + 1]
                    }

                    position += 2;
                    break;

                case "<=": case "le":
                    q = {
                        "$lte": parts[position + 1]
                    }

                    position += 2;
                    break;

                case ">": case "gt":
                    q = {
                        "$gt": parts[position + 1]
                    }

                    position += 2;
                    break;

                case ">=": case "ge":
                    q = {
                        "$gte": parts[position + 1]
                    }

                    position += 2;
                    break;

                case "!=": case "ne":
                    q = {
                        "$ne": parts[position + 1]
                    }

                    position += 2;
                    break;

                case "between":
                    q = {
                        "$gte": parts[position + 1],
                        "$lte": parts[position + 2],
                    }

                    position += 3;
                    break;

                default:
                    throw new error.Invalid("unknown operator: " + parts[position])
                }

                query[query_key] = q;
            }
        })

    return query;
}

/**
 *  Query the database. Note that this implements
 *  `all`, `query_simple` and `scan_simple`
 */
const all = _.promise.make((self, done) => {
    const method = "dynamodb.all";

    assert.ok(self.mongodb, `${method}: expected self.mongodb`)
    assert.ok(self.table_schema, `${method}: expected self.table_schema`)
    assert.ok(_.is.Nullish(self.query) || _.is.JSON(self.query),
        `${method}: expected self.query to be a JSON or Null`);

    let keys = self.table_schema.keys;
    if (self.index_name) {
        keys = self.table_schema.indexes[self.index_name]
    }

    const sort = keys.map(key => [ key.replace(/^[-+]/, ""), key.startsWith("-") ? -1 : 1 ])
    const options = {
        skip: 0
    }

    if (self.pager) {
        options.skip = _.coerce.to.Integer(self.pager, 0)
    }
    if (self.query_limit) {
        options.limit = self.query_limit;
    }

    _.promise.make(self)
        .then(mongo.collection)
        .then(sd => {
            sd.mongo_collection.find(_make_query(self.query), options).sort(sort).toArray((error, mongo_result) => {
                if (error) {
                    return done(error)
                }

                self.jsons = util.scrub_ids(mongo_result);
                self.json = self.jsons.length ? self.jsons[0] : null;

                self.cursor = null;

                if (options.limit) {
                    self.cursor = {
                        first: "0",
                        previous: null,
                        current: `${options.skip}`,
                        next: null,

                        is_first: null,
                        is_last: null,
                        has_next: null,
                        has_previous: null,
                        is_previous_first: null,

                        implements_previous: true,

                        n_results: self.jsons.length,
                        n_start: options.skip,
                    }

                    if (self.jsons.length > 0) {
                        self.cursor.next = `${Math.min(options.limit, self.jsons.length) + options.skip}`;

                        if (self.jsons.length < options.limit) {
                            self.cursor.next = null;
                            self.cursor.is_last = true;
                            self.cursor.has_next = false;
                        } else {
                            self.cursor.has_next = true;
                        }

                        if (options.skip === 0) {
                            self.cursor.is_first = true;
                        }

                        const previous = options.skip - options.limit;
                        self.cursor.previous = `${Math.max(0, previous)}`
                        if (previous === 0) {
                            self.cursor.has_previous = true;
                            self.cursor.is_previous_first = true;
                        } else if (previous < 0) {
                            self.cursor.has_previous = false;
                        } else {
                            self.cursor.has_previous = true;
                        }

                    }
                }

                self.mongo_result = mongo_result;

                done(null, self)
            })
            return null;
        })
        .catch(done)
})

/**
 *  API
 */
exports.all = all;
exports.query_simple = all;
exports.scan_simple = all;
<commit_msg>add dynamodb "count"<commit_after>/*
 *  all.js
 *
 *  David Janes
 *  IOTDB.org
 *  2017-08-06
 *
 *  Copyright [2013-2018] [David P. Janes]
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

"use strict";

const _ = require("iotdb-helpers");

const assert = require("assert");

const mongo = require("../lib");
const util = require("../lib/util");

/**
 *  Make a mongo looking query from a DynamoDB one
 */
const _make_query = _query => {
    const query = _.d.clone.shallow(_query || {})

    _.keys(query)
        .filter(query_key => _.is.Array(query[query_key]))
        .forEach(query_key => {
            const parts = query[query_key];

            let position = 0;
            while (position < parts.length) {
                let comparitor;
                let q;

                switch (parts[position].toLowerCase()) {
                case "=":
                case "eq":
                    q = {
                        "$eq": parts[position + 1]
                    }

                    position += 2;
                    break;

                case "<": case "lt":
                    q = {
                        "$lt": parts[position + 1]
                    }

                    position += 2;
                    break;

                case "<=": case "le":
                    q = {
                        "$lte": parts[position + 1]
                    }

                    position += 2;
                    break;

                case ">": case "gt":
                    q = {
                        "$gt": parts[position + 1]
                    }

                    position += 2;
                    break;

                case ">=": case "ge":
                    q = {
                        "$gte": parts[position + 1]
                    }

                    position += 2;
                    break;

                case "!=": case "ne":
                    q = {
                        "$ne": parts[position + 1]
                    }

                    position += 2;
                    break;

                case "between":
                    q = {
                        "$gte": parts[position + 1],
                        "$lte": parts[position + 2],
                    }

                    position += 3;
                    break;

                default:
                    throw new error.Invalid("unknown operator: " + parts[position])
                }

                query[query_key] = q;
            }
        })

    return query;
}

/**
 *  Query the database. Note that this implements
 *  `all`, `query_simple` and `scan_simple`
 */
const all = _.promise.make((self, done) => {
    const method = "dynamodb.all";

    assert.ok(self.mongodb, `${method}: expected self.mongodb`)
    assert.ok(self.table_schema, `${method}: expected self.table_schema`)
    assert.ok(_.is.Nullish(self.query) || _.is.JSON(self.query),
        `${method}: expected self.query to be a JSON or Null`);

    let keys = self.table_schema.keys;
    if (self.index_name) {
        keys = self.table_schema.indexes[self.index_name]
    }

    const sort = keys.map(key => [ key.replace(/^[-+]/, ""), key.startsWith("-") ? -1 : 1 ])
    const options = {
        skip: 0
    }

    if (self.pager) {
        options.skip = _.coerce.to.Integer(self.pager, 0)
    }
    if (self.query_limit) {
        options.limit = self.query_limit;
    }

    _.promise.make(self)
        .then(mongo.collection)
        .then(sd => {
            sd.mongo_collection.find(_make_query(self.query), options).sort(sort).toArray((error, mongo_result) => {
                if (error) {
                    return done(error)
                }

                self.jsons = util.scrub_ids(mongo_result);
                self.json = self.jsons.length ? self.jsons[0] : null;

                self.cursor = null;

                if (options.limit) {
                    self.cursor = {
                        first: "0",
                        previous: null,
                        current: `${options.skip}`,
                        next: null,

                        is_first: null,
                        is_last: null,
                        has_next: null,
                        has_previous: null,
                        is_previous_first: null,

                        implements_previous: true,

                        n_results: self.jsons.length,
                        n_start: options.skip,
                    }

                    if (self.jsons.length > 0) {
                        self.cursor.next = `${Math.min(options.limit, self.jsons.length) + options.skip}`;

                        if (self.jsons.length < options.limit) {
                            self.cursor.next = null;
                            self.cursor.is_last = true;
                            self.cursor.has_next = false;
                        } else {
                            self.cursor.has_next = true;
                        }

                        if (options.skip === 0) {
                            self.cursor.is_first = true;
                        }

                        const previous = options.skip - options.limit;
                        self.cursor.previous = `${Math.max(0, previous)}`
                        if (previous === 0) {
                            self.cursor.has_previous = true;
                            self.cursor.is_previous_first = true;
                        } else if (previous < 0) {
                            self.cursor.has_previous = false;
                        } else {
                            self.cursor.has_previous = true;
                        }

                    }
                }

                self.mongo_result = mongo_result;

                done(null, self)
            })
            return null;
        })
        .catch(done)
})

const count = _.promise.make((self, done) => {
    const method = "dynamodb.count";

    assert.ok(self.mongodb, `${method}: expected self.mongodb`)
    assert.ok(self.table_schema, `${method}: expected self.table_schema`)
    assert.ok(_.is.Nullish(self.query) || _.is.JSON(self.query),
        `${method}: expected self.query to be a JSON or Null`);

    _.promise.make(self)
        .then(mongo.collection)
        .then(sd => {
            sd.mongo_collection.count(_make_query(self.query), (error, count) => {
                if (error) {
                    return done(error)
                }

                self.count = count;

                done(null, self)
            })
            return null;
        })
        .catch(done)
})

/**
 *  API
 */
exports.count = count;
exports.all = all;
exports.query_simple = all;
exports.scan_simple = all;
<|endoftext|>


<commit_before>var creep_farMining = {

	/** @param {Creep} creep **/
	run: function(creep) {
		if (creep.memory.priority == 'farClaimer' || creep.memory.priority == 'farClaimerNearDeath') {
			if (creep.ticksToLive <= 20) {
				creep.memory.priority == 'farClaimerNearDeath';
			}

			if (creep.room.name != creep.memory.destination) {
				creep.moveTo(new RoomPosition(25, 25, creep.memory.destination));
			} else {
				if (creep.room.controller.reservation && (creep.room.name == creep.memory.destination)) {
					if (creep.room.controller.reservation.ticksToEnd <= 1000) {
						Memory.FarClaimerNeeded[creep.room.name] = true;
					} else {
						Memory.FarClaimerNeeded[creep.room.name] = false;
					}
				} else if (creep.room.name == creep.memory.destination) {
					Memory.FarClaimerNeeded[creep.room.name] = true;
				}

				if (creep.reserveController(creep.room.controller) == ERR_NOT_IN_RANGE) {
					creep.moveTo(creep.room.controller);
				}
			}
		} else if (creep.memory.priority == 'farMiner' || creep.memory.priority == 'farMinerNearDeath') {
			if (creep.ticksToLive <= 60) {
				creep.memory.priority == 'farMinerNearDeath';
			}

			if (creep.room.name != creep.memory.destination) {
				creep.moveTo(new RoomPosition(25, 25, creep.memory.destination));
			} else {
				if (creep.room.controller.reservation && (creep.room.name == creep.memory.destination)) {
					if (creep.room.controller.reservation.ticksToEnd <= 1000) {
						Memory.FarClaimerNeeded[creep.room.name] = true;
					} else {
						Memory.FarClaimerNeeded[creep.room.name] = false;
					}
				} else if (creep.room.name == creep.memory.destination) {
					Memory.FarClaimerNeeded[creep.room.name] = true;
				}

				var mineTarget = "";

				if (creep.memory.mineSource) {
					mineTarget = Game.getObjectById(creep.memory.mineSource);
					if (mineTarget) {
						if (creep.harvest(mineTarget) == ERR_NOT_IN_RANGE) {
							creep.moveTo(mineTarget, {
								reusePath: 5
							});
						}
					}
				} else {
					//Get the source ID while in the room
					var markedSources = [];
					if (Game.flags[creep.memory.targetFlag]) {
						markedSources = Game.flags[creep.memory.targetFlag].pos.lookFor(LOOK_SOURCES);
					}
					if (markedSources.length) {
						creep.memory.mineSource = markedSources[0].id;
					}
					mineTarget = Game.getObjectById(creep.memory.mineSource);
					if (mineTarget) {
						if (creep.harvest(mineTarget) == ERR_NOT_IN_RANGE) {
							creep.moveTo(mineTarget, {
								reusePath: 5
							});
						}
					}
				}

				if (creep.memory.storageUnit) {
					var thisUnit = Game.getObjectById(creep.memory.storageUnit);
					if (thisUnit) {
						if (thisUnit.hits < thisUnit.hitsMax) {
							creep.repair(thisUnit);
						} else {
							if (creep.transfer(thisUnit, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
								creep.moveTo(thisUnit);
							}
						}
					}
				} else {
					var containers = creep.pos.findInRange(FIND_STRUCTURES, 5, {
						filter: (structure) => structure.structureType == STRUCTURE_CONTAINER
					});
					if (containers.length) {
						if (creep.transfer(containers[0], RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
							creep.moveTo(containers[0]);
						}
						creep.memory.storageUnit = containers[0].id;
					} else {
						var sites = creep.pos.findInRange(FIND_CONSTRUCTION_SITES, 5)
						if (sites.length) {
							if (creep.build(sites[0]) == ERR_NOT_IN_RANGE) {
								creep.moveTo(sites[0]);
							}
						} else {
							//Create new container
							if (creep.pos.isNearTo(mineTarget)) {
								creep.room.createConstructionSite(creep.pos, STRUCTURE_CONTAINER)
							}
						}
					}
				}
			}
		} else if (creep.memory.priority == 'farMule' || creep.memory.priority == 'farMuleNearDeath') {
			if (creep.ticksToLive <= 150) {
				creep.memory.priority = 'farMuleNearDeath';
			}

			if (creep.room.name != creep.memory.destination && _.sum(creep.carry) <= 900) {
				var droppedSources = creep.pos.findInRange(FIND_DROPPED_ENERGY, 3);
				if (droppedSources.length) {
					//Pick up dropped energy from dead mules, etc.
					if (creep.pickup(droppedSources[0]) == ERR_NOT_IN_RANGE) {
						creep.moveTo(droppedSources[0]);
					}
				} else {
					creep.moveTo(new RoomPosition(25, 25, creep.memory.destination));
				}
			} else if (creep.room.name != creep.memory.homeRoom && _.sum(creep.carry) > 900) {
				creep.moveTo(new RoomPosition(25, 25, creep.memory.homeRoom));
			} else {
				if (creep.room.controller.reservation && (creep.room.name == creep.memory.destination)) {
					if (creep.room.controller.reservation.ticksToEnd <= 1000) {
						Memory.FarClaimerNeeded[creep.room.name] = true;
					} else {
						Memory.FarClaimerNeeded[creep.room.name] = false;
					}
				} else if (creep.room.name == creep.memory.destination) {
					Memory.FarClaimerNeeded[creep.room.name] = true;
				}

				if (_.sum(creep.carry) <= 900) {
					var droppedSources = creep.pos.findInRange(FIND_DROPPED_ENERGY, 5);
					if (droppedSources.length) {
						//Pick up dropped energy from dead mules, etc.
						if (creep.pickup(droppedSources[0]) == ERR_NOT_IN_RANGE) {
							creep.moveTo(droppedSources[0]);
						}
					} else {
						//in farRoom, pick up container contents
						if (creep.memory.containerTarget) {
							var thisContainer = Game.getObjectById(creep.memory.containerTarget);
							if (thisContainer) {
								if (thisContainer.store[RESOURCE_ENERGY] > 0) {
									if (creep.withdraw(thisContainer, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
										creep.moveTo(thisContainer, {
											reusePath: 20,
											ignoreRoads: true
										});
									}
								} else {
									//Wait by controller
									creep.moveTo(creep.room.controller);
								}

							}
						} else {
							//No container yet, move to be near source
							if (!creep.memory.mineSource) {
								var markedSources = [];
								if (Game.flags[creep.memory.targetFlag]) {
									markedSources = Game.flags[creep.memory.targetFlag].pos.lookFor(LOOK_SOURCES);
								}
								if (markedSources.length) {
									creep.memory.mineSource = markedSources[0].id;
								}
							}

							var thisSource = Game.getObjectById(creep.memory.mineSource);
							if (thisSource) {
								creep.moveTo(thisSource, {
									reusePath: 20,
									ignoreRoads: true
								});
								if (creep.pos.inRangeTo(thisSource, 5)) {
									//Search for container
									var containers = creep.pos.findInRange(FIND_STRUCTURES, 5, {
										filter: (structure) => structure.structureType == STRUCTURE_CONTAINER
									});
									if (containers.length) {
										creep.memory.containerTarget = containers[0].id;
										if (creep.withdraw(containers[0], RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
											creep.moveTo(containers[0], {
												reusePath: 20,
												ignoreRoads: true
											});
										}
									}
								}
							}
						}
					}
				} else {
					//in home room, drop off energy
					var storageUnit = Game.getObjectById(creep.memory.storageSource)
					if (storageUnit) {
						if (creep.transfer(storageUnit, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
							creep.moveTo(storageUnit, {
								reusePath: 20,
								ignoreRoads: true
							});
						}
					}
				}
			}
		} else if (creep.memory.priority == 'farGuard' || creep.memory.priority == 'farGuardNearDeath') {
			if (creep.ticksToLive <= 70) {
				creep.memory.priority == 'farGuardNearDeath';
			}

			if (creep.room.name != creep.memory.destination) {
				creep.moveTo(new RoomPosition(25, 25, creep.memory.destination));
			} else {

				if (creep.room.controller.reservation && (creep.room.name == creep.memory.destination)) {
					if (creep.room.controller.reservation.ticksToEnd <= 1000) {
						Memory.FarClaimerNeeded[creep.room.name] = true;
					} else {
						Memory.FarClaimerNeeded[creep.room.name] = false;
					}
				} else if (creep.room.name == creep.memory.destination) {
					Memory.FarClaimerNeeded[creep.room.name] = true;
				}

				var Foe = creep.pos.findClosestByRange(FIND_HOSTILE_CREEPS);
				if (Foe) {
					creep.say('REEEEEEEEE', true);
					if (creep.pos.getRangeTo(Foe) > 3) {
						creep.moveTo(Foe);
						creep.rangedAttack(Foe);
					} else {
						var foeDirection = creep.pos.getDirectionTo(Foe);
						var evadeDirection = TOP;
						switch (foeDirection) {
							case TOP:
								evadeDirection = BOTTOM;
								break;
							case TOP_RIGHT:
								evadeDirection = BOTTOM_LEFT;
								break;
							case RIGHT:
								evadeDirection = LEFT;
								break;
							case BOTTOM_RIGHT:
								evadeDirection = TOP_LEFT;
								break;
							case BOTTOM:
								evadeDirection = TOP;
								break;
							case BOTTOM_LEFT:
								evadeDirection = TOP_RIGHT;
								break;
							case LEFT:
								evadeDirection = RIGHT;
								break;
							case TOP_LEFT:
								evadeDirection = BOTTOM_RIGHT;
								break;
						}
						creep.move(evadeDirection);
						creep.rangedAttack(Foe);
					}
				} else {
					creep.moveTo(Game.flags[creep.memory.targetFlag].pos);
				}
			}
		}
	}
};

module.exports = creep_farMining;<commit_msg>tiny death time change<commit_after>var creep_farMining = {

	/** @param {Creep} creep **/
	run: function(creep) {
		if (creep.memory.priority == 'farClaimer' || creep.memory.priority == 'farClaimerNearDeath') {
			if (creep.ticksToLive <= 20) {
				creep.memory.priority == 'farClaimerNearDeath';
			}

			if (creep.room.name != creep.memory.destination) {
				creep.moveTo(new RoomPosition(25, 25, creep.memory.destination));
			} else {
				if (creep.room.controller.reservation && (creep.room.name == creep.memory.destination)) {
					if (creep.room.controller.reservation.ticksToEnd <= 1000) {
						Memory.FarClaimerNeeded[creep.room.name] = true;
					} else {
						Memory.FarClaimerNeeded[creep.room.name] = false;
					}
				} else if (creep.room.name == creep.memory.destination) {
					Memory.FarClaimerNeeded[creep.room.name] = true;
				}

				if (creep.reserveController(creep.room.controller) == ERR_NOT_IN_RANGE) {
					creep.moveTo(creep.room.controller);
				}
			}
		} else if (creep.memory.priority == 'farMiner' || creep.memory.priority == 'farMinerNearDeath') {
			if (creep.ticksToLive <= 60) {
				creep.memory.priority == 'farMinerNearDeath';
			}

			if (creep.room.name != creep.memory.destination) {
				creep.moveTo(new RoomPosition(25, 25, creep.memory.destination));
			} else {
				if (creep.room.controller.reservation && (creep.room.name == creep.memory.destination)) {
					if (creep.room.controller.reservation.ticksToEnd <= 1000) {
						Memory.FarClaimerNeeded[creep.room.name] = true;
					} else {
						Memory.FarClaimerNeeded[creep.room.name] = false;
					}
				} else if (creep.room.name == creep.memory.destination) {
					Memory.FarClaimerNeeded[creep.room.name] = true;
				}

				var mineTarget = "";

				if (creep.memory.mineSource) {
					mineTarget = Game.getObjectById(creep.memory.mineSource);
					if (mineTarget) {
						if (creep.harvest(mineTarget) == ERR_NOT_IN_RANGE) {
							creep.moveTo(mineTarget, {
								reusePath: 5
							});
						}
					}
				} else {
					//Get the source ID while in the room
					var markedSources = [];
					if (Game.flags[creep.memory.targetFlag]) {
						markedSources = Game.flags[creep.memory.targetFlag].pos.lookFor(LOOK_SOURCES);
					}
					if (markedSources.length) {
						creep.memory.mineSource = markedSources[0].id;
					}
					mineTarget = Game.getObjectById(creep.memory.mineSource);
					if (mineTarget) {
						if (creep.harvest(mineTarget) == ERR_NOT_IN_RANGE) {
							creep.moveTo(mineTarget, {
								reusePath: 5
							});
						}
					}
				}

				if (creep.memory.storageUnit) {
					var thisUnit = Game.getObjectById(creep.memory.storageUnit);
					if (thisUnit) {
						if (thisUnit.hits < thisUnit.hitsMax) {
							creep.repair(thisUnit);
						} else {
							if (creep.transfer(thisUnit, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
								creep.moveTo(thisUnit);
							}
						}
					}
				} else {
					var containers = creep.pos.findInRange(FIND_STRUCTURES, 5, {
						filter: (structure) => structure.structureType == STRUCTURE_CONTAINER
					});
					if (containers.length) {
						if (creep.transfer(containers[0], RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
							creep.moveTo(containers[0]);
						}
						creep.memory.storageUnit = containers[0].id;
					} else {
						var sites = creep.pos.findInRange(FIND_CONSTRUCTION_SITES, 5)
						if (sites.length) {
							if (creep.build(sites[0]) == ERR_NOT_IN_RANGE) {
								creep.moveTo(sites[0]);
							}
						} else {
							//Create new container
							if (creep.pos.isNearTo(mineTarget)) {
								creep.room.createConstructionSite(creep.pos, STRUCTURE_CONTAINER)
							}
						}
					}
				}
			}
		} else if (creep.memory.priority == 'farMule' || creep.memory.priority == 'farMuleNearDeath') {
			if (creep.ticksToLive <= 170) {
				creep.memory.priority = 'farMuleNearDeath';
			}

			if (creep.room.name != creep.memory.destination && _.sum(creep.carry) <= 900) {
				var droppedSources = creep.pos.findInRange(FIND_DROPPED_ENERGY, 3);
				if (droppedSources.length) {
					//Pick up dropped energy from dead mules, etc.
					if (creep.pickup(droppedSources[0]) == ERR_NOT_IN_RANGE) {
						creep.moveTo(droppedSources[0]);
					}
				} else {
					creep.moveTo(new RoomPosition(25, 25, creep.memory.destination));
				}
			} else if (creep.room.name != creep.memory.homeRoom && _.sum(creep.carry) > 900) {
				creep.moveTo(new RoomPosition(25, 25, creep.memory.homeRoom));
			} else {
				if (creep.room.controller.reservation && (creep.room.name == creep.memory.destination)) {
					if (creep.room.controller.reservation.ticksToEnd <= 1000) {
						Memory.FarClaimerNeeded[creep.room.name] = true;
					} else {
						Memory.FarClaimerNeeded[creep.room.name] = false;
					}
				} else if (creep.room.name == creep.memory.destination) {
					Memory.FarClaimerNeeded[creep.room.name] = true;
				}

				if (_.sum(creep.carry) <= 900) {
					var droppedSources = creep.pos.findInRange(FIND_DROPPED_ENERGY, 5);
					if (droppedSources.length) {
						//Pick up dropped energy from dead mules, etc.
						if (creep.pickup(droppedSources[0]) == ERR_NOT_IN_RANGE) {
							creep.moveTo(droppedSources[0]);
						}
					} else {
						//in farRoom, pick up container contents
						if (creep.memory.containerTarget) {
							var thisContainer = Game.getObjectById(creep.memory.containerTarget);
							if (thisContainer) {
								if (thisContainer.store[RESOURCE_ENERGY] > 0) {
									if (creep.withdraw(thisContainer, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
										creep.moveTo(thisContainer, {
											reusePath: 20,
											ignoreRoads: true
										});
									}
								} else {
									//Wait by controller
									creep.moveTo(creep.room.controller);
								}

							}
						} else {
							//No container yet, move to be near source
							if (!creep.memory.mineSource) {
								var markedSources = [];
								if (Game.flags[creep.memory.targetFlag]) {
									markedSources = Game.flags[creep.memory.targetFlag].pos.lookFor(LOOK_SOURCES);
								}
								if (markedSources.length) {
									creep.memory.mineSource = markedSources[0].id;
								}
							}

							var thisSource = Game.getObjectById(creep.memory.mineSource);
							if (thisSource) {
								creep.moveTo(thisSource, {
									reusePath: 20,
									ignoreRoads: true
								});
								if (creep.pos.inRangeTo(thisSource, 5)) {
									//Search for container
									var containers = creep.pos.findInRange(FIND_STRUCTURES, 5, {
										filter: (structure) => structure.structureType == STRUCTURE_CONTAINER
									});
									if (containers.length) {
										creep.memory.containerTarget = containers[0].id;
										if (creep.withdraw(containers[0], RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
											creep.moveTo(containers[0], {
												reusePath: 20,
												ignoreRoads: true
											});
										}
									}
								}
							}
						}
					}
				} else {
					//in home room, drop off energy
					var storageUnit = Game.getObjectById(creep.memory.storageSource)
					if (storageUnit) {
						if (creep.transfer(storageUnit, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
							creep.moveTo(storageUnit, {
								reusePath: 20,
								ignoreRoads: true
							});
						}
					}
				}
			}
		} else if (creep.memory.priority == 'farGuard' || creep.memory.priority == 'farGuardNearDeath') {
			if (creep.ticksToLive <= 70) {
				creep.memory.priority == 'farGuardNearDeath';
			}

			if (creep.room.name != creep.memory.destination) {
				creep.moveTo(new RoomPosition(25, 25, creep.memory.destination));
			} else {

				if (creep.room.controller.reservation && (creep.room.name == creep.memory.destination)) {
					if (creep.room.controller.reservation.ticksToEnd <= 1000) {
						Memory.FarClaimerNeeded[creep.room.name] = true;
					} else {
						Memory.FarClaimerNeeded[creep.room.name] = false;
					}
				} else if (creep.room.name == creep.memory.destination) {
					Memory.FarClaimerNeeded[creep.room.name] = true;
				}

				var Foe = creep.pos.findClosestByRange(FIND_HOSTILE_CREEPS);
				if (Foe) {
					creep.say('REEEEEEEEE', true);
					if (creep.pos.getRangeTo(Foe) > 3) {
						creep.moveTo(Foe);
						creep.rangedAttack(Foe);
					} else {
						var foeDirection = creep.pos.getDirectionTo(Foe);
						var evadeDirection = TOP;
						switch (foeDirection) {
							case TOP:
								evadeDirection = BOTTOM;
								break;
							case TOP_RIGHT:
								evadeDirection = BOTTOM_LEFT;
								break;
							case RIGHT:
								evadeDirection = LEFT;
								break;
							case BOTTOM_RIGHT:
								evadeDirection = TOP_LEFT;
								break;
							case BOTTOM:
								evadeDirection = TOP;
								break;
							case BOTTOM_LEFT:
								evadeDirection = TOP_RIGHT;
								break;
							case LEFT:
								evadeDirection = RIGHT;
								break;
							case TOP_LEFT:
								evadeDirection = BOTTOM_RIGHT;
								break;
						}
						creep.move(evadeDirection);
						creep.rangedAttack(Foe);
					}
				} else {
					creep.moveTo(Game.flags[creep.memory.targetFlag].pos);
				}
			}
		}
	}
};

module.exports = creep_farMining;<|endoftext|>


<commit_before>(function(g){
    /*
     * LispVal = symbol | number | bool | string | list of LispVal
     *
     * 使用vm.js中的V来构造数据
     */
    var symbolChars = "!?#$%&|+-*/:<=>@^_~";
    var blankChars = " \t\n\r";

    let {stream, C, N, F} = g.parsec;

    let {V} = g.vm;

    /* util */

    function _or([f, ...fr]) {
	if(1 === fr.length) {
	    return F.try(f).or(fr[0])
	} else {
	    return F.try(f).or(_or(fr))
	}
    }

    /* definition */

    var _symbolChar = C.charIn(symbolChars)
    var symbol = F.try(C.letter).or(_symbolChar) // first
        .then(F.try(C.letter).or(F.try(N.digit).or(_symbolChar)).optrep()) // rest
	.map(([first, rest=[]]) => V.s([first, rest.join("")].join("")))

    var bool = C.char("#")
	.thenRight(C.charIn("tf"))
	.map(x => ({"t": V.TRUE, "f": V.FALSE})[x])

    var _special_char = C.char("\\")
	.thenRight(_or(
	    [C.char("n").thenReturns(V.string("\n")),
	     C.char("t").thenReturns(V.string("\t")),
	     C.char("\"").thenReturns(V.string("\"")),
	     C.char("\\").thenReturns(V.string("\\"))]))

    var string = C.char("\"")
	.thenRight(F.try(_special_char)
		   .or(C.notChar("\""))
		   .optrep()
		   .map(xs => V.string(xs.join(""))))
	.thenLeft(C.char("\""))

    var _blankChars = C.charIn(blankChars).optrep()

    /**
     * 入口parser在此处定义，并采用惰性求值的方式，
     * 使得list的定义可以向上递归使用lisp的定义，
     * 构成一个互递归的结构
     */
    var lisp = F.lazy(
	() => _blankChars
	    .thenRight(_or(
		[bool,
		 N.integer.map(i => V.int(i)),
		 // bool and integer shall be parsed
		 // in precedence of symbol
		 symbol,
		 string,
		 list]))
    )

    var _list_tail = _blankChars.then(C.charIn(")]")).thenReturns(V.NULL)
    var _dotted_tail = _blankChars
	.then(C.char("."))
	.thenRight(lisp)
	.thenLeft(_list_tail)

    var list =
	C.charIn("([")
	.thenRight(
	    F.try(lisp.rep()
		  .then(F.try(_list_tail).or(_dotted_tail))
		  .map(([xs, tail]) => {xs.push(tail); return xs}))
	    // or empty list (null)
		.or(_list_tail))

    // g.lispParser = {
    // 	symbol,
    // 	bool,
    // 	string,
    // 	list,
    // 	_blankChars,
    // 	_list_tail,
    // 	_dotted_tail,
    // 	list
    // 	lisp
    // }
    g.lispParser = lisp
})(this)
<commit_msg>parser.js indent fix<commit_after>(function (g) {
    /*
     * LispVal = symbol | number | bool | string | list of LispVal
     *
     * 使用vm.js中的V来构造数据
     */
    var symbolChars = "!?#$%&|+-*/:<=>@^_~";
    var blankChars = " \t\n\r";

    let { stream, C, N, F } = g.parsec;

    let { V } = g.vm;

    /* util */

    function _or([f, ...fr]) {
        if (1 === fr.length) {
            return F.try(f).or(fr[0])
        } else {
            return F.try(f).or(_or(fr))
        }
    }

    /* definition */

    var _symbolChar = C.charIn(symbolChars)
    var symbol = F.try(C.letter).or(_symbolChar) // first
        .then(F.try(C.letter).or(F.try(N.digit).or(_symbolChar)).optrep()) // rest
        .map(([first, rest = []]) => V.s([first, rest.join("")].join("")))

    var bool = C.char("#")
        .thenRight(C.charIn("tf"))
        .map(x => ({ "t": V.TRUE, "f": V.FALSE })[x])

    var _special_char = C.char("\\")
        .thenRight(_or(
            [C.char("n").thenReturns(V.string("\n")),
            C.char("t").thenReturns(V.string("\t")),
            C.char("\"").thenReturns(V.string("\"")),
            C.char("\\").thenReturns(V.string("\\"))]))

    var string = C.char("\"")
        .thenRight(F.try(_special_char)
            .or(C.notChar("\""))
            .optrep()
            .map(xs => V.string(xs.join(""))))
        .thenLeft(C.char("\""))

    var _blankChars = C.charIn(blankChars).optrep()

    /**
     * 入口parser在此处定义，并采用惰性求值的方式，
     * 使得list的定义可以向上递归使用lisp的定义，
     * 构成一个互递归的结构
     */
    var lisp = F.lazy(
        () => _blankChars
            .thenRight(_or(
                [bool,
                    N.integer.map(i => V.int(i)),
                    // bool and integer shall be parsed
                    // in precedence of symbol
                    symbol,
                    string,
                    list]))
    )

    var _list_tail = _blankChars.then(C.charIn(")]")).thenReturns(V.NULL)
    var _dotted_tail = _blankChars
        .then(C.char("."))
        .thenRight(lisp)
        .thenLeft(_list_tail)

    var list =
        C.charIn("([")
            .thenRight(
            F.try(lisp.rep()
                .then(F.try(_list_tail).or(_dotted_tail))
                .map(([xs, tail]) => { xs.push(tail); return xs }))
                // or empty list (null)
                .or(_list_tail))

    // g.lispParser = {
    // 	symbol,
    // 	bool,
    // 	string,
    // 	list,
    // 	_blankChars,
    // 	_list_tail,
    // 	_dotted_tail,
    // 	list
    // 	lisp
    // }
    g.lispParser = lisp
})(this)
<|endoftext|>


<commit_before>import React from 'react';
import { Component, PropTypes } from '../utils/';
import SlickCarousel from 'react-slick';

export default class Carousel extends Component {
  constructor(props){
    super(props);
    this.state={
    }
    this.onWindowResized = this.onWindowResized.bind(this)
  }

  componentDidMount (){
    const { autoplay } = this.props;
    if (autoplay) {
      window.addEventListener('resize',this.onWindowResized);
    }
    const { slick } = this.refs;
    this.innerSlider = slick && slick.innerSlider;
  }

  componentWillUnMount(){
    const { autoplay } = this.props;
    if (autoplay){
      window.removeEventListener('resize',this.onWindowResized);
    }
  }

  // 自动切换
  onWindowResized(){
    const {slick} = this.refs;
    const { autoplay } = this.props;
    if( autoplay && slick && slick.innerSlider && slick.innerSlider.autoPlay ) {
      slick.innerSlider.autoPlay()
    }
  }

  render(){
    let props = { ...this.props }
    props.fade = props.effect === 'fade' ? true : false
    let cls = props.prefixCls;
    if (props.vertical) {
      cls = this.classNames(
        cls,
        `${cls}-vertical`,
        [props.className]: props.className
      )
    }
    return (

        <SlickCarousel
          ref="slick"
          {...props}
        />

    )
  }

}

Carousel.defaultProps = {
  arrows: false, // 左右箭头
  prefixCls: 'w-carousel',
  draggable: false, // 拖拽切换
  fade:false, // 切换效果(渐显)
  dots:true,  // 是否显示下标
};
Carousel.propTypes = {
  effect:PropTypes.oneOf(['scrollx', 'fade']),
  dots: PropTypes.bool,
  vertical: PropTypes.bool,
  autoplay: PropTypes.bool,
  easing: PropTypes.string,
  prefixCls: PropTypes.string,
  beforeChange: PropTypes.func,
  afterChange: PropTypes.func,
  fade: PropTypes.bool,
  focusOnSelect: PropTypes.bool,
  initialSlide: PropTypes.number,
  slide: PropTypes.string,
  draggable:PropTypes.bool,
  arrows:PropTypes.bool,
  nextArrow: PropTypes.any,
  prevArrow: PropTypes.any,
}<commit_msg>fix(Carousel): fix syntax error.<commit_after>import React from 'react';
import { Component, PropTypes } from '../utils/';
import SlickCarousel from 'react-slick';

export default class Carousel extends Component {
  constructor(props) {
    super(props);
    this.state = {
    }
    this.onWindowResized = this.onWindowResized.bind(this)
  }

  componentDidMount() {
    const { autoplay } = this.props;
    if (autoplay) {
      window.addEventListener('resize', this.onWindowResized);
    }
    const { slick } = this.refs;
    this.innerSlider = slick && slick.innerSlider;
  }

  componentWillUnMount() {
    const { autoplay } = this.props;
    if (autoplay) {
      window.removeEventListener('resize', this.onWindowResized);
    }
  }

  // 自动切换
  onWindowResized() {
    const { slick } = this.refs;
    const { autoplay } = this.props;
    if (autoplay && slick && slick.innerSlider && slick.innerSlider.autoPlay) {
      slick.innerSlider.autoPlay()
    }
  }

  render() {
    let props = { ...this.props }
    props.fade = props.effect === 'fade' ? true : false
    let cls = props.prefixCls;
    if (props.vertical) {
      cls = this.classNames(cls, `${cls}-vertical`, {
        [props.className]: props.className
      })
    }
    return (

        <SlickCarousel
          ref="slick"
          {...props}
        />

    )
  }

}

Carousel.defaultProps = {
  arrows: false, // 左右箭头
  prefixCls: 'w-carousel',
  draggable: false, // 拖拽切换
  fade: false, // 切换效果(渐显)
  dots: true,  // 是否显示下标
};
Carousel.propTypes = {
  effect: PropTypes.oneOf(['scrollx', 'fade']),
  dots: PropTypes.bool,
  vertical: PropTypes.bool,
  autoplay: PropTypes.bool,
  easing: PropTypes.string,
  prefixCls: PropTypes.string,
  beforeChange: PropTypes.func,
  afterChange: PropTypes.func,
  fade: PropTypes.bool,
  focusOnSelect: PropTypes.bool,
  initialSlide: PropTypes.number,
  slide: PropTypes.string,
  draggable: PropTypes.bool,
  arrows: PropTypes.bool,
  nextArrow: PropTypes.any,
  prevArrow: PropTypes.any,
}
<|endoftext|>


<commit_before>import api from 'plugins/http/api';

/**
 * Simple interface for interacting with user roles and permissions
 *
 * permissions is an array with the following structure
 *
[
        {
            "name": "Create Subsites",
            "slug": "subsite.create",
            "roles": [
                "site.owner"
            ]
        },
		...
 */
const state = {
	roles: [],
	currentRole: {}
};

const getters = {
	getCurrentRole(state, getters) {
		return state.currentRole;
	},

	getRoles(state, getters) {
		return state.roles;
	},

	/**
	 * can the user perform the requested action
	 * if the user is a global admin then let them do anything
	 *
	 * @param {string} the permission to check i.e. subsite.edit, subsite.create
	 * @returns {bool} true or false
	 */
	canUser: (state, getters) => (permissionSlug) => {

		let permitted = false;

		// if the user has the global role of admin then then they can do anything
		// @TODO - admin should not live in the current role as they might have no particular role with this site
		if (state.currentRole.global_role === 'admin') {
			return true;
		}
		const matchedRole = state.roles.find(function(value) {
			if (value.slug == this.permissionSlug) {
				return true;
			}
		}, {permissionSlug});

		if (matchedRole) {
			permitted = matchedRole.roles.includes(state.currentRole.role);
		}

		return permitted;
	}
};

const actions = {

	/**
	 * gets list of roles from the api can calls mutation to store this in the state
	 *
	 * called from TopBar.vue->mounted
	 */
	loadPermissions({commit, state}) {
		api
			.get('permissions?include=roles')
			.then((response) => {
				let permissions = response.data.data;
				commit('setPermissions', permissions);
			})
	},

	/**
	 * gets list of a user's roles from the api can calls mutation to store this in the state
	 *
	 * called from Editor.vue->created
	 */
	loadSitePermissions({commit, state}, site_id) {
		api
			.get(`sites/${site_id}?include=users`)
			.then(({data}) => {
				const userList = data.data.users;
				if (userList) {
					const currentRole = userList.find((element) => element.name === window.astro.username);
					commit('setCurrentRole', currentRole);
				}
				else {
					commit('setCurrentRole', {});
				}
			});
	}

};

const mutations = {

	/**
	 * Used to initially set the permissions the editor understands
	 *
	 * @param {*} state
	 * @param {object} permissions - the set of permissions as received from the API
	 */
	setPermissions(state, permissions) {
		state.roles = permissions;
	},

	/**
	 * sets the current role for the site
	 * @param {*} state
	 * @param {*} currentRole
	 */
	setCurrentRole(state, currentRole) {
		state.currentRole = currentRole;
	}
};

export default {
	state,
	getters,
	mutations,
	actions
};<commit_msg>Made users role in the current site a simple string<commit_after>import api from 'plugins/http/api';

/**
 * Simple interface for interacting with user roles and permissions
 *
 * permissions is an array with the following structure
 *
[
		{
			"name": "Create Subsites",
			"slug": "subsite.create",
			"roles": [
				"site.owner"
			]
		},
		...
 */
const state = {
	roles: [],
	currentRole: '',
	globalRole: '',
};

const getters = {
	getCurrentRole(state, getters) {
		return state.currentSiteRole;
	},

	getRoles(state, getters) {
		return state.roles;
	},

	/**
	 * can the user perform the requested action
	 * if the user is a global admin then let them do anything
	 *
	 * @param {string} the permission to check i.e. subsite.edit, subsite.create
	 * @returns {bool} true or false
	 */
	canUser: (state, getters) => (permissionSlug) => {

		let permitted = false;

		// if the user has the global role of admin then then they can do anything
		// @TODO - admin should not live in the current role as they might have no particular role with this site
		if (state.currentRole.global_role === 'admin') {
			return true;
		}
		const matchedRole = state.roles.find(function(value) {
			if (value.slug == this.permissionSlug) {
				return true;
			}
		}, {permissionSlug});

		if (matchedRole) {
			permitted = matchedRole.roles.includes(state.currentRole);
		}

		return permitted;
	}
};

const actions = {

	/**
	 * gets list of roles from the api can calls mutation to store this in the state
	 *
	 * called from TopBar.vue->mounted
	 */
	loadPermissions({commit, state}) {
		api
			.get('permissions?include=roles')
			.then((response) => {
				let permissions = response.data.data;
				commit('setPermissions', permissions);
			})
	},

	/**
	 * gets list of a user's roles from the api can calls mutation to store this in the state
	 *
	 * called from Editor.vue->created
	 */
	loadSitePermissions({commit, state}, site_id) {
		api
			.get(`sites/${site_id}?include=users`)
			.then(({data}) => {
				const userList = data.data.users;
				if (userList) {
					const currentUser = userList.find((element) => element.name === window.astro.username);
					commit('setCurrentRole', currentUser.role);
				}
				else {
					commit('setCurrentRole', {});
				}
			});
	}

	/**
	 * gets list of the logged in user's gloabl role
	 *
	 * called from TopBar.vue->mounted
	 *
	 * @param {string} user_name - the name of the user
	 */
	// loadGlobalRole({commit, state}, user_name) {

	// 	api
	// 		.get(`users/${user_name}`)

	// }

};

const mutations = {

	/**
	 * Used to initially set the permissions the editor understands
	 *
	 * @param {*} state
	 * @param {object} permissions - the set of permissions as received from the API
	 */
	setPermissions(state, permissions) {
		state.roles = permissions;
	},

	/**
	 * sets the current role for the site
	 * @param {*} state
	 * @param {*} currentRole
	 */
	setCurrentRole(state, currentRole) {
		state.currentRole = currentRole;
	}
};

export default {
	state,
	getters,
	mutations,
	actions
};<|endoftext|>


<commit_before>/* -*- Mode: js; js-indent-level: 2; indent-tabs-mode: nil; tab-width: 2 -*- */
var BinaryFileReader = (function binaryFileReader() {
  function constructor(url, responseType) {
    this.url = url;
    this.responseType = responseType || "arraybuffer";
  }

  constructor.prototype = {
    readAll: function(progress, complete) {
      var url = this.url;
      var xhr = new XMLHttpRequest({mozSystem:true});
      var async = true;
      xhr.open("GET", this.url, async);
      xhr.responseType = this.responseType;
      if (progress) {
        xhr.onprogress = function(event) {
          progress(xhr.response, event.loaded, event.total);
        };
      }
      xhr.onreadystatechange = function(event) {
        if (xhr.readyState === 4) {
          if (xhr.status !== 200 && xhr.status !== 0) {
            unexpected("Path: " + url + " not found.");
            complete(null, xhr.statusText);
            return;
          }
          complete(xhr.response);
        }
      }
      xhr.setRequestHeader("If-Modified-Since", "Fri, 01 Jan 1960 00:00:00 GMT"); // no-cache
      xhr.send(null);
    },
    readAsync: function(ondata, onerror, onopen, oncomplete, onhttpstatus) {
      var xhr = new XMLHttpRequest();
      var url = this.url;
      xhr.open("GET", url, true);
      // arraybuffer is not provide onprogress, fetching as regular chars
      if ('overrideMimeType' in xhr)
        xhr.overrideMimeType('text/plain; charset=x-user-defined');
      var lastPosition = 0;
      xhr.onprogress = function (e) {
        var position = e.loaded;
        var chunk = xhr.responseText.substring(lastPosition, position);
        var data = new Uint8Array(chunk.length);
        for (var i = 0; i < data.length; i++)
          data[i] = chunk.charCodeAt(i) & 0xFF;
        ondata(data, { loaded: e.loaded, total: e.total });
        lastPosition = position;
      };
      xhr.onreadystatechange = function(event) {
        if(xhr.readyState === 2 && onhttpstatus) {
          onhttpstatus(url, xhr.status, xhr.getAllResponseHeaders());
        }
        if (xhr.readyState === 4) {
          if (xhr.status !== 200 && xhr.status !== 0) {
            onerror(xhr.statusText);
          }
          if (oncomplete)
            oncomplete();
        }
      }
      xhr.setRequestHeader("If-Modified-Since", "Fri, 01 Jan 1960 00:00:00 GMT"); // no-cache
      xhr.send(null);
      if (onopen)
        onopen();
    }
  };
  return constructor;
})();

var asyncLoading = getQueryVariable("async") === "true";
var libraryAbcs
function grabAbc(abcName) {
  var entry = libraryScripts[abcName];
  if (entry) {
    var offset = entry.offset;
    var length = entry.length;
    return new AbcFile(new Uint8Array(libraryAbcs, offset, length), abcName);
  }
  return null
}

function findDefiningAbc(mn) {
  if (!avm2.builtinsLoaded) {
    return null;
  }
  var name;
  for (var i = 0; i < mn.namespaces.length; i++) {
    var name = mn.namespaces[i].originalURI + ":" + mn.name;
    var abcName = playerGlobalNames[name];
    if (abcName) {
      break;
    }
  }
  if (abcName) {
    return grabAbc(abcName);
  }
  return null;
}

// avm2 must be global.
var avm2;
function createAVM2(builtinPath, libraryPath, sysMode, appMode, next) {
  assert (builtinPath);
  new BinaryFileReader(builtinPath).readAll(null, function (buffer) {
    avm2 = new AVM2(sysMode, appMode, findDefiningAbc);
    console.time("Execute builtin.abc");
    avm2.loadedAbcs = {};
    // Avoid loading more Abcs while the builtins are loaded
    avm2.builtinsLoaded = false;
    avm2.systemDomain.executeAbc(new AbcFile(new Uint8Array(buffer), "builtin.abc"));
    avm2.builtinsLoaded = true;
    console.timeEnd("Execute builtin.abc");
    new BinaryFileReader(libraryPath).readAll(null, function (buffer) {
      // If library is shell.abc, then just go ahead and run it now since
      // its not worth doing it lazily given that it is so small.
      if (libraryPath === shellAbcPath) {
        avm2.systemDomain.executeAbc(new AbcFile(new Uint8Array(buffer), libraryPath));
      } else {
        libraryAbcs = buffer;
      }
      next(avm2);
    });
  });
}

var avm2Root = "../../src/avm2/";
var remoteFile = getQueryVariable("rfile");
var builtinPath = avm2Root + "generated/builtin/builtin.abc";
var shellAbcPath = avm2Root + "generated/shell/shell.abc";
var playerGlobalAbcPath = "../../src/flash/playerglobal.abc";

function parseQueryString(qs) {
  if (!qs)
    return {};

  if (qs.charAt(0) == '?')
    qs = qs.slice(1);

  var values = qs.split('&');
  var obj = {};
  for (var i = 0; i < values.length; i++) {
    var kv = values[i].split('=');
    var key = kv[0], value = kv[1];
    obj[key] = decodeURIComponent(value);
  }

  return obj;
}

/**
 * You can also specify a remote file as a query string parameters, ?rfile=... to load it automatically
 * when the page loads.
 */
if (remoteFile) {
  $('#openFileToolbar')[0].setAttribute('hidden', true);
  executeFile(remoteFile, null, parseQueryString(window.location.search));
}

var yt = getQueryVariable('yt');
if (yt) {
  var xhr = new XMLHttpRequest({mozSystem: true});
  xhr.open('GET', 'http://www.youtube.com/watch?v=' + yt, true);
  xhr.onload = function (e) {
    var config = JSON.parse(/ytplayer\.config\s*=\s*([^;]+)/.exec(xhr.responseText)[1]);
    var swf = JSON.parse(/swf\s*=\s*("[^;]+)/.exec(xhr.responseText)[1]);
    swf = /src="([^"]+)/.exec(swf)[1];

    $('#openFileToolbar')[0].setAttribute('hidden', true);
    executeFile(swf, null, config.args);
  };
  xhr.send(null);
}

function showMessage(msg) {
  $('#message').text(msg);
  $('#message')[0].parentElement.removeAttribute('hidden');
}

function executeFile(file, buffer, movieParams) {
  // All execution paths must now load AVM2.
  if (!state.appCompiler) {
    showMessage("Running in the Interpreter");
  }
  var sysMode = state.sysCompiler ? EXECUTION_MODE.COMPILE : EXECUTION_MODE.INTERPRET;
  var appMode = state.appCompiler ? EXECUTION_MODE.COMPILE : EXECUTION_MODE.INTERPRET;
  if (file.endsWith(".abc")) {
    libraryScripts = {};
    createAVM2(builtinPath, shellAbcPath, sysMode, appMode, function (avm2) {
      function runAbc(file, buffer) {
        avm2.applicationDomain.executeAbc(new AbcFile(new Uint8Array(buffer), file));
        terminate();
      }
      if (!buffer) {
        new BinaryFileReader(file).readAll(null, function(buffer) {
          runAbc(file, buffer);
        });
      } else {
        runAbc(file, buffer);
      }
    });
  } else if (file.endsWith(".swf")) {
    libraryScripts = playerGlobalScripts;
    createAVM2(builtinPath, playerGlobalAbcPath, sysMode, appMode, function (avm2) {
      function runSWF(file, buffer) {
        SWF.embed(buffer, document, $("#stage")[0], {
          onComplete: terminate,
          onStageInitialized: stageInitialized,
          onBeforeFrame: frame,
          movieParams: movieParams || {},
        });
      }
      if (!buffer && asyncLoading) {
        var subscription = {
          subscribe: function (callback) {
            this.callback = callback;
          }
        };
        runSWF(file, subscription);
        FileLoadingService.setBaseUrl(file);
        new BinaryFileReader(file).readAsync(
          function onchunk(data, progressInfo) {
            subscription.callback(data, progressInfo);
          },
          function onerror(error) {
            console.error("Unable to open the file " + file + ": " + error);
          });
      } else if (!buffer) {
        FileLoadingService.setBaseUrl(file);
        new BinaryFileReader(file).readAll(null, function(buffer, error) {
          if (!buffer) {
            throw "Unable to open the file " + file + ": " + error;
          }
          runSWF(file, buffer);
        });
      } else {
        runSWF(file, buffer);
      }
    });
  }
}

function stageInitialized(stage) {
  if (TRACE_SYMBOLS_INFO) {
    var traceSymbolsInfo = $('#traceSymbolsInfo')[0];
    traceSymbolsInfo.removeAttribute('hidden');
    traceSymbolsInfo.appendChild(stage._control);
  }
}

function terminate() {}

var initializeFrameControl = true;
var pauseExecution = getQueryVariable("paused") === "true";
function frame(e) {
  if (initializeFrameControl) {
    // skipping frame 0
    initializeFrameControl = false;
    return;
  }
  if (pauseExecution) {
    e.cancel = true;
  }
}

(function setStageSize() {
  var stageSize = getQueryVariable("size");
  if (stageSize && /^\d+x\d+$/.test(stageSize)) {
    var dims = stageSize.split('x');
    $("#stage")[0].style.width = dims[0] + "px";
    $("#stage")[0].style.height = dims[1] + "px";
  }
})();

var FileLoadingService = {
  createSession: function () {
    return {
      open: function (request) {
        var self = this;
        var path = FileLoadingService.resolveUrl(request.url);
        console.log('FileLoadingService: loading ' + path);
        new BinaryFileReader(path).readAsync(
          function (data, progress) {
            self.onprogress(data, {bytesLoaded: progress.loaded, bytesTotal: progress.total});
          },
          function (e) { self.onerror(e); },
          self.onopen,
          self.onclose,
          self.onhttpstatus);
      }
    };
  },
  setBaseUrl: function (url) {
    var a = document.createElement('a');
    a.href = url || '#';
    a.setAttribute('style', 'display: none;');
    document.body.appendChild(a);
    FileLoadingService.baseUrl = a.href;
    document.body.removeChild(a);
  },
  resolveUrl: function (url) {
    if (url.indexOf('://') >= 0) return url;

    var base = FileLoadingService.baseUrl;
    base = base.lastIndexOf('/') >= 0 ? base.substring(0, base.lastIndexOf('/') + 1) : '';
    if (url.indexOf('/') === 0) {
      var m = /^[^:]+:\/\/[^\/]+/.exec(base);
      if (m) base = m[0];
    }
    return base + url;
  }
};
<commit_msg>Using systemXHR for URLStream in the inspector<commit_after>/* -*- Mode: js; js-indent-level: 2; indent-tabs-mode: nil; tab-width: 2 -*- */
var BinaryFileReader = (function binaryFileReader() {
  function constructor(url, responseType) {
    this.url = url;
    this.responseType = responseType || "arraybuffer";
  }

  constructor.prototype = {
    readAll: function(progress, complete) {
      var url = this.url;
      var xhr = new XMLHttpRequest({mozSystem:true});
      var async = true;
      xhr.open("GET", this.url, async);
      xhr.responseType = this.responseType;
      if (progress) {
        xhr.onprogress = function(event) {
          progress(xhr.response, event.loaded, event.total);
        };
      }
      xhr.onreadystatechange = function(event) {
        if (xhr.readyState === 4) {
          if (xhr.status !== 200 && xhr.status !== 0) {
            unexpected("Path: " + url + " not found.");
            complete(null, xhr.statusText);
            return;
          }
          complete(xhr.response);
        }
      }
      xhr.setRequestHeader("If-Modified-Since", "Fri, 01 Jan 1960 00:00:00 GMT"); // no-cache
      xhr.send(null);
    },
    readAsync: function(ondata, onerror, onopen, oncomplete, onhttpstatus) {
      var xhr = new XMLHttpRequest({mozSystem:true});
      var url = this.url;
      xhr.open("GET", url, true);
      // arraybuffer is not provide onprogress, fetching as regular chars
      if ('overrideMimeType' in xhr)
        xhr.overrideMimeType('text/plain; charset=x-user-defined');
      var lastPosition = 0;
      xhr.onprogress = function (e) {
        var position = e.loaded;
        var chunk = xhr.responseText.substring(lastPosition, position);
        var data = new Uint8Array(chunk.length);
        for (var i = 0; i < data.length; i++)
          data[i] = chunk.charCodeAt(i) & 0xFF;
        ondata(data, { loaded: e.loaded, total: e.total });
        lastPosition = position;
      };
      xhr.onreadystatechange = function(event) {
        if(xhr.readyState === 2 && onhttpstatus) {
          onhttpstatus(url, xhr.status, xhr.getAllResponseHeaders());
        }
        if (xhr.readyState === 4) {
          if (xhr.status !== 200 && xhr.status !== 0) {
            onerror(xhr.statusText);
          }
          if (oncomplete)
            oncomplete();
        }
      }
      xhr.setRequestHeader("If-Modified-Since", "Fri, 01 Jan 1960 00:00:00 GMT"); // no-cache
      xhr.send(null);
      if (onopen)
        onopen();
    }
  };
  return constructor;
})();

var asyncLoading = getQueryVariable("async") === "true";
var libraryAbcs
function grabAbc(abcName) {
  var entry = libraryScripts[abcName];
  if (entry) {
    var offset = entry.offset;
    var length = entry.length;
    return new AbcFile(new Uint8Array(libraryAbcs, offset, length), abcName);
  }
  return null
}

function findDefiningAbc(mn) {
  if (!avm2.builtinsLoaded) {
    return null;
  }
  var name;
  for (var i = 0; i < mn.namespaces.length; i++) {
    var name = mn.namespaces[i].originalURI + ":" + mn.name;
    var abcName = playerGlobalNames[name];
    if (abcName) {
      break;
    }
  }
  if (abcName) {
    return grabAbc(abcName);
  }
  return null;
}

// avm2 must be global.
var avm2;
function createAVM2(builtinPath, libraryPath, sysMode, appMode, next) {
  assert (builtinPath);
  new BinaryFileReader(builtinPath).readAll(null, function (buffer) {
    avm2 = new AVM2(sysMode, appMode, findDefiningAbc);
    console.time("Execute builtin.abc");
    avm2.loadedAbcs = {};
    // Avoid loading more Abcs while the builtins are loaded
    avm2.builtinsLoaded = false;
    avm2.systemDomain.executeAbc(new AbcFile(new Uint8Array(buffer), "builtin.abc"));
    avm2.builtinsLoaded = true;
    console.timeEnd("Execute builtin.abc");
    new BinaryFileReader(libraryPath).readAll(null, function (buffer) {
      // If library is shell.abc, then just go ahead and run it now since
      // its not worth doing it lazily given that it is so small.
      if (libraryPath === shellAbcPath) {
        avm2.systemDomain.executeAbc(new AbcFile(new Uint8Array(buffer), libraryPath));
      } else {
        libraryAbcs = buffer;
      }
      next(avm2);
    });
  });
}

var avm2Root = "../../src/avm2/";
var remoteFile = getQueryVariable("rfile");
var builtinPath = avm2Root + "generated/builtin/builtin.abc";
var shellAbcPath = avm2Root + "generated/shell/shell.abc";
var playerGlobalAbcPath = "../../src/flash/playerglobal.abc";

function parseQueryString(qs) {
  if (!qs)
    return {};

  if (qs.charAt(0) == '?')
    qs = qs.slice(1);

  var values = qs.split('&');
  var obj = {};
  for (var i = 0; i < values.length; i++) {
    var kv = values[i].split('=');
    var key = kv[0], value = kv[1];
    obj[key] = decodeURIComponent(value);
  }

  return obj;
}

/**
 * You can also specify a remote file as a query string parameters, ?rfile=... to load it automatically
 * when the page loads.
 */
if (remoteFile) {
  $('#openFileToolbar')[0].setAttribute('hidden', true);
  executeFile(remoteFile, null, parseQueryString(window.location.search));
}

var yt = getQueryVariable('yt');
if (yt) {
  var xhr = new XMLHttpRequest({mozSystem: true});
  xhr.open('GET', 'http://www.youtube.com/watch?v=' + yt, true);
  xhr.onload = function (e) {
    var config = JSON.parse(/ytplayer\.config\s*=\s*([^;]+)/.exec(xhr.responseText)[1]);
    var swf = JSON.parse(/swf\s*=\s*("[^;]+)/.exec(xhr.responseText)[1]);
    swf = /src="([^"]+)/.exec(swf)[1];

    $('#openFileToolbar')[0].setAttribute('hidden', true);
    executeFile(swf, null, config.args);
  };
  xhr.send(null);
}

function showMessage(msg) {
  $('#message').text(msg);
  $('#message')[0].parentElement.removeAttribute('hidden');
}

function executeFile(file, buffer, movieParams) {
  // All execution paths must now load AVM2.
  if (!state.appCompiler) {
    showMessage("Running in the Interpreter");
  }
  var sysMode = state.sysCompiler ? EXECUTION_MODE.COMPILE : EXECUTION_MODE.INTERPRET;
  var appMode = state.appCompiler ? EXECUTION_MODE.COMPILE : EXECUTION_MODE.INTERPRET;
  if (file.endsWith(".abc")) {
    libraryScripts = {};
    createAVM2(builtinPath, shellAbcPath, sysMode, appMode, function (avm2) {
      function runAbc(file, buffer) {
        avm2.applicationDomain.executeAbc(new AbcFile(new Uint8Array(buffer), file));
        terminate();
      }
      if (!buffer) {
        new BinaryFileReader(file).readAll(null, function(buffer) {
          runAbc(file, buffer);
        });
      } else {
        runAbc(file, buffer);
      }
    });
  } else if (file.endsWith(".swf")) {
    libraryScripts = playerGlobalScripts;
    createAVM2(builtinPath, playerGlobalAbcPath, sysMode, appMode, function (avm2) {
      function runSWF(file, buffer) {
        SWF.embed(buffer, document, $("#stage")[0], {
          onComplete: terminate,
          onStageInitialized: stageInitialized,
          onBeforeFrame: frame,
          movieParams: movieParams || {},
        });
      }
      if (!buffer && asyncLoading) {
        var subscription = {
          subscribe: function (callback) {
            this.callback = callback;
          }
        };
        runSWF(file, subscription);
        FileLoadingService.setBaseUrl(file);
        new BinaryFileReader(file).readAsync(
          function onchunk(data, progressInfo) {
            subscription.callback(data, progressInfo);
          },
          function onerror(error) {
            console.error("Unable to open the file " + file + ": " + error);
          });
      } else if (!buffer) {
        FileLoadingService.setBaseUrl(file);
        new BinaryFileReader(file).readAll(null, function(buffer, error) {
          if (!buffer) {
            throw "Unable to open the file " + file + ": " + error;
          }
          runSWF(file, buffer);
        });
      } else {
        runSWF(file, buffer);
      }
    });
  }
}

function stageInitialized(stage) {
  if (TRACE_SYMBOLS_INFO) {
    var traceSymbolsInfo = $('#traceSymbolsInfo')[0];
    traceSymbolsInfo.removeAttribute('hidden');
    traceSymbolsInfo.appendChild(stage._control);
  }
}

function terminate() {}

var initializeFrameControl = true;
var pauseExecution = getQueryVariable("paused") === "true";
function frame(e) {
  if (initializeFrameControl) {
    // skipping frame 0
    initializeFrameControl = false;
    return;
  }
  if (pauseExecution) {
    e.cancel = true;
  }
}

(function setStageSize() {
  var stageSize = getQueryVariable("size");
  if (stageSize && /^\d+x\d+$/.test(stageSize)) {
    var dims = stageSize.split('x');
    $("#stage")[0].style.width = dims[0] + "px";
    $("#stage")[0].style.height = dims[1] + "px";
  }
})();

var FileLoadingService = {
  createSession: function () {
    return {
      open: function (request) {
        var self = this;
        var path = FileLoadingService.resolveUrl(request.url);
        console.log('FileLoadingService: loading ' + path);
        new BinaryFileReader(path).readAsync(
          function (data, progress) {
            self.onprogress(data, {bytesLoaded: progress.loaded, bytesTotal: progress.total});
          },
          function (e) { self.onerror(e); },
          self.onopen,
          self.onclose,
          self.onhttpstatus);
      }
    };
  },
  setBaseUrl: function (url) {
    var a = document.createElement('a');
    a.href = url || '#';
    a.setAttribute('style', 'display: none;');
    document.body.appendChild(a);
    FileLoadingService.baseUrl = a.href;
    document.body.removeChild(a);
  },
  resolveUrl: function (url) {
    if (url.indexOf('://') >= 0) return url;

    var base = FileLoadingService.baseUrl;
    base = base.lastIndexOf('/') >= 0 ? base.substring(0, base.lastIndexOf('/') + 1) : '';
    if (url.indexOf('/') === 0) {
      var m = /^[^:]+:\/\/[^\/]+/.exec(base);
      if (m) base = m[0];
    }
    return base + url;
  }
};
<|endoftext|>


<commit_before>import React from "react";
import { connect } from "react-redux";
import { Form, FormGroup, FormControl, ControlLabel, Button, Checkbox } from "react-bootstrap";
import FontAwesome from "react-fontawesome";
import SelectRole from "./SelectRole";
import SelectTeam from "./SelectTeam";

class AddTeamMember extends React.Component {
  constructor (props) {
    super(props);

    this.onInputChange = this.onInputChange.bind(this);

    this.state = {
      title: "Add Team Member",
      name: "",
      email: "",
      teamLead: false
    };
  }

  render () {
    let teams = [
      "ReactDojo",
      "AngularDojo",
      "BackboneDojo"
    ];

    let roles = [
      "Front-End Developer",
      "Back-End Developer"
    ];

    let teamMemberId = 100;

    return(

{this.state.title}

          <Form>
            <ControlLabel>Name</ControlLabel>
            <FormGroup controlId="name">
              <FormControl
                type="text"
                name="name"
                placeholder="Enter your name"
                value={this.state.name}
                onChange={this.onInputChange}
              />
            </FormGroup>

            <ControlLabel>Email</ControlLabel>
            <FormGroup controlId="email">
              <FormControl
                type="email"
                name="email"
                placeholder="Enter your email"
                value={this.state.email}
                onChange={this.onInputChange}
              />
            </FormGroup>

            <FormGroup controlId="teamLead">
              <Checkbox
                name="teamLead"
                value={this.state.teamLead}
                onChange={this.onInputChange}
                inline>Team Lead
              </Checkbox>
            </FormGroup>

            <SelectTeam teams={this.props.teams} onSelect={() => {}} />
            <SelectRole roles={this.props.roles} onSelect={() => {}} />

            <Button type="submit" bsStyle="primary" onClick={() => dispatch({
              type: "ADD_TEAM_MEMBER",
              teamMember: {
                "_id": `${teamMemberId++}teamMember`,
                "name": this.state.name,
                "email": this.state.email,
                "team": "",
                "teamHistory": ["ReactDojo", "AngularDojo"],
                "role": "Front-End Developer",
                "skills": ["React", "Redux", "Angular"]
              }
            })}>
              Add Team Member
            </Button>
            <Button type="reset" bsStyle="danger">Reset</Button>
          </Form>

    );
  }

  onInputChange (e) {
    const target = e.target;
    const value = target.type === "checkbox" ? target.checked : target.value;
    const name = target.name;

    this.setState({
      [name]: value
    });
  }
};

AddTeamMember = connect((state, ownProps) => {
  return {
    teams: state.teams,
    roles: state.roles
  };
})(AddTeamMember);

export default AddTeamMember;<commit_msg>feat: Fixing some issues with the Team Member Form<commit_after>import React from "react";
import { connect } from "react-redux";
import { Form, FormGroup, FormControl, ControlLabel, Button, Checkbox } from "react-bootstrap";
import FontAwesome from "react-fontawesome";
import SelectRole from "./SelectRole";
import SelectTeam from "./SelectTeam";

class AddTeamMember extends React.Component {
  constructor (props) {
    super(props);

    this.onInputChange = this.onInputChange.bind(this);

    this.state = {
      title: "Add Team Member",
      name: "",
      email: "",
      teamLead: false
    };
  }

  render () {
    let teams = [
      "ReactDojo",
      "AngularDojo",
      "BackboneDojo"
    ];

    let roles = [
      "Front-End Developer",
      "Back-End Developer"
    ];

    let teamMemberId = 100;

    return(

{this.state.title}

          <Form>
            <ControlLabel>Name</ControlLabel>
            <FormGroup controlId="name">
              <FormControl
                type="text"
                name="name"
                placeholder="Enter your name"
                value={this.state.name}
                onChange={this.onInputChange}
              />
            </FormGroup>

            <ControlLabel>Email</ControlLabel>
            <FormGroup controlId="email">
              <FormControl
                type="email"
                name="email"
                placeholder="Enter your email"
                value={this.state.email}
                onChange={this.onInputChange}
              />
            </FormGroup>

            <FormGroup controlId="teamLead">
              <Checkbox
                name="teamLead"
                value={this.state.teamLead}
                onChange={this.onInputChange}
                inline>Team Lead
              </Checkbox>
            </FormGroup>

            <SelectTeam teams={this.props.teams} onSelect={() => {}} />
            <SelectRole roles={this.props.roles} onSelect={() => {}} />

            <Button type="submit" bsStyle="primary" onClick={() => this.props.dispatch({
              type: "ADD_TEAM_MEMBER",
              teamMember: {
                "_id": `${teamMemberId++}teamMember`,
                "name": this.state.name,
                "email": this.state.email,
                "team": "",
                "teamHistory": ["ReactDojo", "AngularDojo"],
                "role": "Front-End Developer",
                "skills": ["React", "Redux", "Angular"]
              }
            })}>
              Add Team Member
            </Button>
            <Button type="reset" bsStyle="danger">Reset</Button>
          </Form>

    );
  }

  onInputChange (e) {
    const target = e.target;
    const value = target.type === "checkbox" ? target.checked : target.value;
    const name = target.name;

    this.setState({
      [name]: value
    });
  }
};

AddTeamMember = connect((state, ownProps) => {
  return {
    teams: state.teams,
    roles: state.roles
  };
})(AddTeamMember);

export default AddTeamMember;<|endoftext|>