<commit_before>var fs = require('fs');
var path = require('path');

// Choose 'tap' rather than 'min' or 'xunit'. The reason is that
// 'min' produces undisplayable text to stdout and stderr under piped/redirect,
// and 'xunit' does not print the stack trace from the test.
var defaultMochaOptions = { ui: 'tdd', reporter: 'tap', timeout: 2000 };

var find_tests = function (testFileList, discoverResultFile, projectFolder) {
    var Mocha = detectMocha(projectFolder);
    if (!Mocha) {
        return;
    }

    function getTestList(suite, testFile) {
        if (suite) {
            if (suite.tests && suite.tests.length !== 0) {
                suite.tests.forEach(function (t, i, testArray) {
                    testList.push({
                        test: t.title,
                        suite: suite.fullTitle(),
                        file: testFile,
                        line: 0,
                        column: 0
                    });
                });
            }

            if (suite.suites) {
                suite.suites.forEach(function (s, i, suiteArray) {
                    getTestList(s, testFile);
                });
            }
        }
    }
    var testList = [];
    testFileList.split(';').forEach(function (testFile) {
        var mocha = initializeMocha(Mocha, projectFolder);
        process.chdir(path.dirname(testFile));

        try {
            mocha.addFile(testFile);
            mocha.loadFiles();
            getTestList(mocha.suite, testFile);
        } catch (e) {
            //we would like continue discover other files, so swallow, log and continue;
            logError("Test discovery error:", e, "in", testFile);
        }
    });

    var fd = fs.openSync(discoverResultFile, 'w');
    fs.writeSync(fd, JSON.stringify(testList));
    fs.closeSync(fd);
};
module.exports.find_tests = find_tests;

var run_tests = function (testName, testFile, workingFolder, projectFolder) {
    var Mocha = detectMocha(projectFolder);
    if (!Mocha) {
        return;
    }

    var mocha = initializeMocha(Mocha, projectFolder);

    if (testName) {
        mocha.grep(testName);
    }
    mocha.addFile(testFile);

    mocha.run(function (code) {
        process.exit(code);
    });
};

function logError() {
    var errorArgs = Array.prototype.slice.call(arguments);
    errorArgs.unshift("NTVS_ERROR:");
    console.error.apply(console, errorArgs);
}

function detectMocha(projectFolder) {
    try {
        var mochaPath = path.join(projectFolder, 'node_modules', 'mocha');
        var Mocha = new require(mochaPath);
        return Mocha;
    } catch (ex) {
        logError("Failed to find Mocha package.  Mocha must be installed in the project locally.  Mocha can be installed locally with the npm manager via solution explorer or with \".npm install mocha\" via the Node.js interactive window.");
        return null;
    }
}

function initializeMocha(Mocha, projectFolder) {
    var mocha = new Mocha();
    applyMochaOptions(mocha, getMochaOptions(projectFolder));
    return mocha;
}

function applyMochaOptions(mocha, options) {
    if (options) {
        for (var opt in options) {
            var mochaOpt = mocha[opt];
            var optValue = options[opt];

            if (typeof mochaOpt === 'function') {
                try {
                    mochaOpt.call(mocha, optValue);
                } catch (e) {
                    console.log("Could not set mocha option '" + opt + "' with value '" + optValue + "' due to error:", e);
                }
            }
        }
    }
}

function getMochaOptions(projectFolder) {
    var mochaOptions = defaultMochaOptions;
    try {
        var optionsPath = path.join(projectFolder, 'test', 'mocha.json');
        var options = require(optionsPath);
        options = options || {};
        for (var opt in options) {
            mochaOptions[opt] = options[opt];
        }
    } catch (ex) {
        console.log("mocha.json options file not found. Using default values:", mochaOptions);
    }

    // set timeout to 10 minutes, because the default of 2 sec is too short for debugging scenarios
    if (typeof (v8debug) === 'object') {
        mochaOptions['timeout'] = 600000;
    }

    return mochaOptions;
}

module.exports.run_tests = run_tests;<commit_msg>#334 Test explorer view is messed up in VS 2015 - nested tests were not appearing in Test Explorer discovery because we   were returning title rather than fullTitle()<commit_after>var fs = require('fs');
var path = require('path');

// Choose 'tap' rather than 'min' or 'xunit'. The reason is that
// 'min' produces undisplayable text to stdout and stderr under piped/redirect,
// and 'xunit' does not print the stack trace from the test.
var defaultMochaOptions = { ui: 'tdd', reporter: 'tap', timeout: 2000 };

var find_tests = function (testFileList, discoverResultFile, projectFolder) {
    var Mocha = detectMocha(projectFolder);
    if (!Mocha) {
        return;
    }

    function getTestList(suite, testFile) {
        if (suite) {
            if (suite.tests && suite.tests.length !== 0) {
                suite.tests.forEach(function (t, i, testArray) {
                    testList.push({
                        test: t.fullTitle(),
                        suite: suite.fullTitle(),
                        file: testFile,
                        line: 0,
                        column: 0
                    });
                });
            }

            if (suite.suites) {
                suite.suites.forEach(function (s, i, suiteArray) {
                    getTestList(s, testFile);
                });
            }
        }
    }
    var testList = [];
    testFileList.split(';').forEach(function (testFile) {
        var mocha = initializeMocha(Mocha, projectFolder);
        process.chdir(path.dirname(testFile));

        try {
            mocha.addFile(testFile);
            mocha.loadFiles();
            getTestList(mocha.suite, testFile);
        } catch (e) {
            //we would like continue discover other files, so swallow, log and continue;
            logError("Test discovery error:", e, "in", testFile);
        }
    });

    var fd = fs.openSync(discoverResultFile, 'w');
    fs.writeSync(fd, JSON.stringify(testList));
    fs.closeSync(fd);
};
module.exports.find_tests = find_tests;

var run_tests = function (testName, testFile, workingFolder, projectFolder) {
    var Mocha = detectMocha(projectFolder);
    if (!Mocha) {
        return;
    }

    var mocha = initializeMocha(Mocha, projectFolder);

    if (testName) {
        mocha.grep(testName);
    }
    mocha.addFile(testFile);

    mocha.run(function (code) {
        process.exit(code);
    });
};

function logError() {
    var errorArgs = Array.prototype.slice.call(arguments);
    errorArgs.unshift("NTVS_ERROR:");
    console.error.apply(console, errorArgs);
}

function detectMocha(projectFolder) {
    try {
        var mochaPath = path.join(projectFolder, 'node_modules', 'mocha');
        var Mocha = new require(mochaPath);
        return Mocha;
    } catch (ex) {
        logError("Failed to find Mocha package.  Mocha must be installed in the project locally.  Mocha can be installed locally with the npm manager via solution explorer or with \".npm install mocha\" via the Node.js interactive window.");
        return null;
    }
}

function initializeMocha(Mocha, projectFolder) {
    var mocha = new Mocha();
    applyMochaOptions(mocha, getMochaOptions(projectFolder));
    return mocha;
}

function applyMochaOptions(mocha, options) {
    if (options) {
        for (var opt in options) {
            var mochaOpt = mocha[opt];
            var optValue = options[opt];

            if (typeof mochaOpt === 'function') {
                try {
                    mochaOpt.call(mocha, optValue);
                } catch (e) {
                    console.log("Could not set mocha option '" + opt + "' with value '" + optValue + "' due to error:", e);
                }
            }
        }
    }
}

function getMochaOptions(projectFolder) {
    var mochaOptions = defaultMochaOptions;
    try {
        var optionsPath = path.join(projectFolder, 'test', 'mocha.json');
        var options = require(optionsPath);
        options = options || {};
        for (var opt in options) {
            mochaOptions[opt] = options[opt];
        }
    } catch (ex) {
        console.log("mocha.json options file not found. Using default values:", mochaOptions);
    }

    // set timeout to 10 minutes, because the default of 2 sec is too short for debugging scenarios
    if (typeof (v8debug) === 'object') {
        mochaOptions['timeout'] = 600000;
    }

    return mochaOptions;
}

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


<commit_before>/******************************************************
Programmeerproject
Florinde Vessies, 10657738
CO2 emissions and urbanization
javascript sunburst

*******************************************************/
// based on the example of Mike Bostock, http://bl.ocks.org/mbostock/4348373
// http://bl.ocks.org/metmajer/5480307
var arcTweenFunction;
var computeTextRotationFunction;

function drawsunburst (dataSunburst, year, countryData) {
    d3.select("#sunburstsvg").remove();
    d3.select("#suntitle").remove();

   var sunwidth = 600,
      sunheight = 600,
      sunradius = (Math.min(sunwidth, sunheight) / 2) - 10;

    var formatNumber = d3.format(",d");

    var x = d3.scale.linear()
        .range([0, 2 * Math.PI]);

    var y = d3.scale.linear()
        .range([0, sunradius]);

    // Interpolate the scales!
  var arcTweenFunction = function arcTween(d) {
    var xd = d3.interpolate(x.domain(), [d.x, d.x + d.dx]),
        yd = d3.interpolate(y.domain(), [d.y, 1]),
        yr = d3.interpolate(y.range(), [d.y ? 20 : 0, sunradius]);
    return function(d, i) {
      return i
          ? function(t) { return sunarc(d); }
          : function(t) { x.domain(xd(t)); y.domain(yd(t)).range(yr(t)); return sunarc(d); };
    };
  }

  // rotates the text appropriately
  var computeTextRotationFunction = function computeTextRotation(d) {
    return (x(d.x + d.dx / 2) - Math.PI / 2) / Math.PI * 180;
  }

  var colorcountry = d3.scale.ordinal()
    .range(['#a6cee3','#1f78b4','#b2df8a','#33a02c','#fb9a99','#e31a1c','#fdbf6f','#ff7f00','#cab2d6','#6a3d9a','#ffff99','#b15928']);
var colorCO2 = d3.scale.ordinal()
    .range(['#fbb4ae','#b3cde3','#ccebc5','#decbe4','#fed9a6']);

// different color schemes based on depth in sunburst
var color = function color(d) {
    switch(d.depth) {
      case 0:
        return '#f0f7fa';
        break;
      case 1:
          return colorcountry(d.name);
          break;
      case 2:
          return colorCO2(d.name);
          break;
      }
    }

  var sunsvg = d3.select("#sunburst").append("svg")
      .attr("id", "sunburstsvg")
      .attr("width", "100%")
      .attr("height", sunheight)
    .append("g")
      .attr("transform", "translate(" + sunwidth / 2 + "," + (sunheight / 2 + 10) + ")");

  var partition = d3.layout.partition()
      .value(function(d) { return d.size; });

  var sunarc = d3.svg.arc()
      .startAngle(function(d) { return Math.max(0, Math.min(2 * Math.PI, x(d.x))); })
      .endAngle(function(d) { return Math.max(0, Math.min(2 * Math.PI, x(d.x + d.dx))); })
      .innerRadius(function(d) { return Math.max(0, y(d.y)); })
      .outerRadius(function(d) { return Math.max(0, y(d.y + d.dy)); });

  var g = sunsvg.selectAll("g")
      .data(partition.nodes(root))
    .enter().append("g");

  var path = g.append("path")
    .attr("d", sunarc)
    .style("fill", function(d) { return color(d); })
    .on("click", click);

  var text = g.append("text")
    .attr("transform", function(d) { return "rotate(" + computeTextRotationFunction(d) + ")"; })
    .attr("x", function(d) { return y(d.y); })
    .attr("dx", "6") // margin
    .attr("dy", ".35em") // vertical-align
    .text(function(d) { return d.name; });

  function click(d) {
    console.log(d);
    // fade out all text elements
    text.transition().attr("opacity", 0);

    path.transition()
      .duration(750)
      .attrTween("d", arcTweenFunction(d))
      .each("end", function(e, i) {
          // check if the animated element's data e lies within the visible angle span given in d
          if (e.x >= d.x && e.x < (d.x + d.dx)) {
            // get a selection of the associated text element
            var arcText = d3.select(this.parentNode).select("text");
            // fade in the text element and recalculate positions
            arcText.transition().duration(750)
              .attr("opacity", 1)
              .attr("transform", function() { return "rotate(" + computeTextRotationFunction(e) + ")" })
              .attr("x", function(d) { return y(d.y); });
          }
      });
  }

d3.select(self.frameElement).style("height", sunheight + "px");

}
<commit_msg>bettercode<commit_after><|endoftext|>


<commit_before>//constructor function
var locationCreator = function(name, description){
  this.name = name;
  this.description = description;
  this.items = [];
  this.enemies = [];
  locationList.push(this);
};
var playerCreator = function(name, description){
  this.name=name;
  this.description=description;
  this.health=150;
  this.items=[];
  this.spells=[];
  this.currentLocation=tinyCave;
  this.attack=0;
  this.blockCharge=0;
};
var itemCreator = function(name, description, type, stat, location){
  this.name = name;
  this.description = description;
  this.type = type;
  switch (this.type){
    case 'weapon':
      this.attack = stat;
      break;
    case 'shield':
      this.blockCharge = stat;
      break;
    default:
      return('error type');
      break;
  }
  location.items.push(this);
};
var spellBookCreator = function(name, description, spellName, spellCharge, spellDamage, location){
  this.name = name;
  this.description = description;
  this.spellName = spellName;
  this.spellCharge = spellCharge;
  this.spellDamage = spellDamage;
  this.type = 'spellbook';
  location.items.push(this);
};
var badGuyCreator = function(name, description, health, attack, type, location){
  this.name = name;
  this.description = description;
  this.health = health;
  this.attack = attack;
  this.type = type;
  location.enemies.push(this);
  enemiesAtLarge.push(this);
};

//creation
var locationList = [];
var enemiesAtLarge = [];
var player = new playerCreator("Red Knight", 'Tall, kinda handsome with wavy blond hair, sort of arrogant and simpleminded. Wears heavy armor painted in red.');

var tinyCave = new locationCreator("Tiny Cave", "Tiny Cave, wet, and full of tiny spiders. Entry point of a larger cave.");
var treasureRoom = new locationCreator("Treasure Room","A big chest sits in the middle of the room");
var secretLibrary = new locationCreator("Secret Library", "A well-lit library...in a cave...");
var bossRoom = new locationCreator("Boss Room", "Welcome! This is the BOSS ROOM! It's big and has a boss in it!");

var bigBadSword = new itemCreator("Big Bad Sword","Heavy. Not well crafted but sharp enough to kill a man.", 'weapon', 15, treasureRoom);
var horribleRedShield = new itemCreator("Horrible Red Shield","Painted in red with a sigil of a boar. Sturdy, but ugly looking round metal shield.", 'shield', 5, treasureRoom);
var uglyRedBook = new spellBookCreator("Ugly Red Book", 'An ugly looking red book, with some gibberish in it.', "Red Fireball", 1, 10, secretLibrary);

var darkPriest = new badGuyCreator("Dark Priest", "Dark Priest of Total Darkness.", 25, 1000, 'boss', bossRoom);
var goblin1 = new badGuyCreator("Goblin", "Green, tiny, annoying", 1, 5, 'minon', secretLibrary);
var goblin2 = new badGuyCreator("Goblin", "Green, tiny, annoying", 1, 5, 'minon', secretLibrary);

//action functions
var encounter = function(location){
  var currentEmemies = location.enemies;
  if (currentEmemies.length>0) {
    for (idx in currentEmemies){
      return('You encounter '+currentEmemies[idx].name+".");
    }
  }
  else {
    return('No enemies here.');
  }
};
var find = function(location){
  var currentItems = location.items;
  if (currentItems.length>0) {
    for (idx in currentItems){
      return('There is a '+currentItems[idx].name+' in this room.');
    }
  }
  else{return('Nothing left in this room.');}
};
var locationMatcher = function(locationPrompt){
  locationPrompt = locationPrompt.toLowerCase();
  switch (locationPrompt){
    case 'tiny cave':
      return(tinyCave);
      break;
    case 'treasure room':
      return(treasureRoom);
      break;
    case 'secret library':
      return(secretLibrary);
      break;
    case 'boss room':
      return(bossRoom);
      break;
    default:
      alert('No such location.');
      break;
  }
};
player.moveTo = function(){
  var locationPrompt = prompt("Enter location.");
  var selection = locationMatcher(locationPrompt);
  this.currentLocation = selection;
  var encountered = encounter(selection);
  var found = find(selection);
  return('You move to '+selection.name+'\n'+encountered+'\n'+found);
};
player.pickUpAll = function(){
  var itemsInLocation = this.currentLocation.items;
  if (itemsInLocation.length>0) {
    for (idx in itemsInLocation){
      this.items.push(itemsInLocation[idx]);
      return('You pick up '+itemsInLocation[idx].name);}
      this.currentLocation.items.splice(idx, 1);
  } else{return('There\'s nothing to pick up.');}
  this.currentLocation.items = [];
};
player.equipAll = function(){
  var itemsGained = this.items;
  for (idx in itemsGained){
    var item = itemsGained[idx];
    switch (item.type){
      case 'weapon':
      this.attack = item.attack;
      break;
      case 'shield':
      this.blockCharge = item.blockCharge;
      break;
      case 'spellbook':
      this.spells.push(item);
      break;
      default:
      return('You have nothing to equip.');
      break;
    }
  }
};
player.attackTarget = function(enemy,selectAttack){
  var enemiesInSight = this.currentLocation.enemies;
  if (enemiesInSight.indexOf(enemy)>=0) {
    if (isNaN(selectAttack)) {weaponSwing(enemy);} else{spellCast(enemy, selectAttack);}
  }
  else{return('No enemies here.');}
  enemyStatus(enemy, this.currentLocation);
  turnSwitch(enemiesInSight);
  levelCheck();
};
var enemyStatus = function(enemyObject,location){
  var eIdx = location.enemies.indexOf(enemyObject);
  if (enemyObject.health <= 0) {
    if (enemyObject.type === 'boss') {return("You slain the boss!");}
    else{return('You defeted '+enemyObject.name);}
    location.enemies.splice(eIdx,1);
    enemiesAtLarge.splice(eIdx,1);
  } else{return('It still lives with '+enemyObject.health+' health left.');}
};
var turnSwitch = function(enemiesInSight){
  if (enemiesInSight.length>0) {
    return('There are enemies still living:\n');
    for (idx in enemiesInSight){
      return(enemiesInSight[idx].name+'\n');
      enemyAttack(enemiesInSight[idx]);
    }
  } else{return('This room is clear.');}
};
var enemyAttack = function(enemyObject){
  var currentDamage = enemyObject.attack;
  var currentBlock = player.blockCharge;
  return(enemyObject.name+" start to attack you!");
  if (currentBlock === 0) {
    player.health -= currentDamage;
    return('You are hit for '+currentDamage+' damage!');}
  else if (currentDamage <= currentBlock) {
    currentBlock -= 1;
    return('You block the attack!');}
  else{
    currentBlock = 0;
    return('You block the attack, but it breaks your shield!');}
  player.blockCharge = currentBlock;
  player.status();
};
player.status = function(){
  if (player.health <= 0) {
    return('You died!');
  }
};
var weaponSwing = function(enemy){
  enemy.health -= player.attack;
  return("You attacked "+enemy.name+" for "+player.attack+" damage.");
};
var spellCast = function(enemy, spellIdx){
  var selectedSpell = player.spells[spellIdx];
  var currentSpellCharge = selectedSpell.spellCharge;
  if (isNaN(selectedSpell)&&currentSpellCharge>0) {
    enemy.health -= selectedSpell.spellDamage;
    currentSpellCharge -= 1;
    return('You casted '+selectedSpell.spellName+" for "+selectedSpell.spellDamage+" damage.");
  } else{return("You don't know that spell!");}
  player.spells[spellIdx].spellCharge = currentSpellCharge;
};
var levelCheck = function(){
  if (enemiesAtLarge.length==0) {return('You complete this level!');}
};

// //script run
// player.moveTo(treasureRoom);
// player.pickUpAll();
// player.equipAll();
// player.equipAll();
// player.moveTo(secretLibrary);
// player.attackTarget(goblin1);
// player.attackTarget(goblin2);
// player.pickUpAll();
// player.equipAll();
// player.moveTo(bossRoom);
// player.attackTarget(darkPriest, 0);
// player.attackTarget(darkPriest);<commit_msg>Revert "fix moveTo return values"<commit_after>//constructor function
var locationCreator = function(name, description){
  this.name = name;
  this.description = description;
  this.items = [];
  this.enemies = [];
  locationList.push(this);
};
var playerCreator = function(name, description){
  this.name=name;
  this.description=description;
  this.health=150;
  this.items=[];
  this.spells=[];
  this.currentLocation=tinyCave;
  this.attack=0;
  this.blockCharge=0;
};
var itemCreator = function(name, description, type, stat, location){
  this.name = name;
  this.description = description;
  this.type = type;
  switch (this.type){
    case 'weapon':
      this.attack = stat;
      break;
    case 'shield':
      this.blockCharge = stat;
      break;
    default:
      return('error type');
      break;
  }
  location.items.push(this);
};
var spellBookCreator = function(name, description, spellName, spellCharge, spellDamage, location){
  this.name = name;
  this.description = description;
  this.spellName = spellName;
  this.spellCharge = spellCharge;
  this.spellDamage = spellDamage;
  this.type = 'spellbook';
  location.items.push(this);
};
var badGuyCreator = function(name, description, health, attack, type, location){
  this.name = name;
  this.description = description;
  this.health = health;
  this.attack = attack;
  this.type = type;
  location.enemies.push(this);
  enemiesAtLarge.push(this);
};

//creation
var locationList = [];
var enemiesAtLarge = [];
var player = new playerCreator("Red Knight", 'Tall, kinda handsome with wavy blond hair, sort of arrogant and simpleminded. Wears heavy armor painted in red.');

var tinyCave = new locationCreator("Tiny Cave", "Tiny Cave, wet, and full of tiny spiders. Entry point of a larger cave.");
var treasureRoom = new locationCreator("Treasure Room","A big chest sits in the middle of the room");
var secretLibrary = new locationCreator("Secret Library", "A well-lit library...in a cave...");
var bossRoom = new locationCreator("Boss Room", "Welcome! This is the BOSS ROOM! It's big and has a boss in it!");

var bigBadSword = new itemCreator("Big Bad Sword","Heavy. Not well crafted but sharp enough to kill a man.", 'weapon', 15, treasureRoom);
var horribleRedShield = new itemCreator("Horrible Red Shield","Painted in red with a sigil of a boar. Sturdy, but ugly looking round metal shield.", 'shield', 5, treasureRoom);
var uglyRedBook = new spellBookCreator("Ugly Red Book", 'An ugly looking red book, with some gibberish in it.', "Red Fireball", 1, 10, secretLibrary);

var darkPriest = new badGuyCreator("Dark Priest", "Dark Priest of Total Darkness.", 25, 1000, 'boss', bossRoom);
var goblin1 = new badGuyCreator("Goblin", "Green, tiny, annoying", 1, 5, 'minon', secretLibrary);
var goblin2 = new badGuyCreator("Goblin", "Green, tiny, annoying", 1, 5, 'minon', secretLibrary);

//action functions
var encounter = function(location){
  var currentEmemies = location.enemies;
  if (currentEmemies.length>0) {
    for (idx in currentEmemies){
      return('You encounter '+currentEmemies[idx].name+".");
    }
  }
  else {
    return('No enemies here.');
  }
};
var found = function(location){
  var currentItems = location.items;
  if (currentItems.length>0) {
    for (idx in currentItems){
      return('There is a '+currentItems[idx].name+' in this room.');
    }
  }
  else{return('Nothing left in this room.');}
};
var locationMatcher = function(locationPrompt){
  locationPrompt = locationPrompt.toLowerCase();
  switch (locationPrompt){
    case 'tiny cave':
      return(tinyCave);
      break;
    case 'treasure room':
      return(treasureRoom);
      break;
    case 'secret library':
      return(secretLibrary);
      break;
    case 'boss room':
      return(bossRoom);
      break;
    default:
      alert('No such location.');
      break;
  }
};
player.moveTo = function(){
  var locationPrompt = prompt("Enter location.");
  var selection = locationMatcher(locationPrompt);
  this.currentLocation = selection;
  return('You move to '+selection.name);
  encounter(selection);
  found(selection);
};
player.pickUpAll = function(){
  var itemsInLocation = this.currentLocation.items;
  if (itemsInLocation.length>0) {
    for (idx in itemsInLocation){
      this.items.push(itemsInLocation[idx]);
      return('You pick up '+itemsInLocation[idx].name);}
      this.currentLocation.items.splice(idx, 1);
  } else{return('There\'s nothing to pick up.');}
  this.currentLocation.items = [];
};
player.equipAll = function(){
  var itemsGained = this.items;
  for (idx in itemsGained){
    var item = itemsGained[idx];
    switch (item.type){
      case 'weapon':
      this.attack = item.attack;
      break;
      case 'shield':
      this.blockCharge = item.blockCharge;
      break;
      case 'spellbook':
      this.spells.push(item);
      break;
      default:
      return('You have nothing to equip.');
      break;
    }
  }
};
player.attackTarget = function(enemy,selectAttack){
  var enemiesInSight = this.currentLocation.enemies;
  if (enemiesInSight.indexOf(enemy)>=0) {
    if (isNaN(selectAttack)) {weaponSwing(enemy);} else{spellCast(enemy, selectAttack);}
  }
  else{return('No enemies here.');}
  enemyStatus(enemy, this.currentLocation);
  turnSwitch(enemiesInSight);
  levelCheck();
};
var enemyStatus = function(enemyObject,location){
  var eIdx = location.enemies.indexOf(enemyObject);
  if (enemyObject.health <= 0) {
    if (enemyObject.type === 'boss') {return("You slain the boss!");}
    else{return('You defeted '+enemyObject.name);}
    location.enemies.splice(eIdx,1);
    enemiesAtLarge.splice(eIdx,1);
  } else{return('It still lives with '+enemyObject.health+' health left.');}
};
var turnSwitch = function(enemiesInSight){
  if (enemiesInSight.length>0) {
    return('There are enemies still living:\n');
    for (idx in enemiesInSight){
      return(enemiesInSight[idx].name+'\n');
      enemyAttack(enemiesInSight[idx]);
    }
  } else{return('This room is clear.');}
};
var enemyAttack = function(enemyObject){
  var currentDamage = enemyObject.attack;
  var currentBlock = player.blockCharge;
  return(enemyObject.name+" start to attack you!");
  if (currentBlock === 0) {
    player.health -= currentDamage;
    return('You are hit for '+currentDamage+' damage!');}
  else if (currentDamage <= currentBlock) {
    currentBlock -= 1;
    return('You block the attack!');}
  else{
    currentBlock = 0;
    return('You block the attack, but it breaks your shield!');}
  player.blockCharge = currentBlock;
  player.status();
};
player.status = function(){
  if (player.health <= 0) {
    return('You died!');
  }
};
var weaponSwing = function(enemy){
  enemy.health -= player.attack;
  return("You attacked "+enemy.name+" for "+player.attack+" damage.");
};
var spellCast = function(enemy, spellIdx){
  var selectedSpell = player.spells[spellIdx];
  var currentSpellCharge = selectedSpell.spellCharge;
  if (isNaN(selectedSpell)&&currentSpellCharge>0) {
    enemy.health -= selectedSpell.spellDamage;
    currentSpellCharge -= 1;
    return('You casted '+selectedSpell.spellName+" for "+selectedSpell.spellDamage+" damage.");
  } else{return("You don't know that spell!");}
  player.spells[spellIdx].spellCharge = currentSpellCharge;
};
var levelCheck = function(){
  if (enemiesAtLarge.length==0) {return('You complete this level!');}
};

// //script run
// player.moveTo(treasureRoom);
// player.pickUpAll();
// player.equipAll();
// player.equipAll();
// player.moveTo(secretLibrary);
// player.attackTarget(goblin1);
// player.attackTarget(goblin2);
// player.pickUpAll();
// player.equipAll();
// player.moveTo(bossRoom);
// player.attackTarget(darkPriest, 0);
// player.attackTarget(darkPriest);<|endoftext|>


<commit_before>const {assert} = require('chai');
const cp = require('child_process');
const uuid = require(`uuid`);

const containerAnalysis = require('@google-cloud/containeranalysis');
const client = new containerAnalysis.v1beta1.GrafeasV1Beta1Client();

const execSync = cmd => cp.execSync(cmd, {encoding: 'utf-8'});

const uuidVal = uuid.v4();
const noteId = `test-note-${uuidVal}`;
const resourceUrl = `gcr.io/test-project/test-image-${uuidVal}`;
const subscriptionId = `occurrence-subscription-${uuidVal}`;
const timeoutSeconds = 5;
const retries = 5;

const {PubSub} = require('@google-cloud/pubsub');
const pubsub = new PubSub();
const topicName = 'container-analysis-occurrences-v1beta1';
const topic = pubsub.topic(topicName);

let projectId;
let formattedParent;
let formattedNoteName;

describe('Note tests', function() {
  before(async function() {
    // define projectId and related vars
    projectId = await client.getProjectId();
    formattedParent = `projects/${projectId}`;
    formattedNoteName = `projects/${projectId}/notes/${noteId}`;
  });
  after(async function() {
    const [allOccurrences] = await client.listOccurrences({
      parent: formattedParent,
      filter: `resourceUrl = "${resourceUrl}"`,
    });

    allOccurrences.forEach(async occurrence => {
      await client.deleteOccurrence({name: occurrence.name});
      console.log(`deleted occurrence ${occurrence.name}`);
    });

    const [allNotes] = await client.listNotes({
      parent: formattedParent,
    });

    allNotes.forEach(async note => {
      await client.deleteNote({name: note.name});
      console.log(`deleted note ${note.name}`);
    });
  });
  it('should create a note', function() {
    const output = execSync(`node createNote.js "${projectId}" "${noteId}"`);
    assert.include(output, new RegExp(`Note ${formattedNoteName} created.`));
  });

  it('should get note', function() {
    const output = execSync(`node getNote.js "${projectId}" "${noteId}"`);
    assert.include(output, new RegExp(`Note name: ${formattedNoteName}`));
  });

  it('should create occurrence', function() {
    const output = execSync(
      `node createOccurrence.js "${projectId}" "${noteId}" "${projectId}" "${resourceUrl}"`
    );
    assert.include(output, new RegExp(`Occurrence created`));
  });

  it('should get occurrence', async function() {
    const [occurrences] = await client.listOccurrences({
      parent: formattedParent,
    });
    assert(occurrences.length > 0);

    const occurrence = occurrences[0];
    const occurrenceId = occurrence.name.split('/')[3];
    let output;
    for (let i = 0; i < retries; i++) {
      output = execSync(
        `node getOccurrence.js "${projectId}" "${occurrenceId}"`
      );
      if (output.includes('Occurrence name:')) {
        break;
      }
    }

    assert.include(output, new RegExp(`Occurrence name: ${occurrence.name}`));
  });

  it('should get occurences for note', function() {
    const output = execSync(
      `node occurrencesForNote.js "${projectId}" "${noteId}"`
    );
    assert.include(output, /Occurrences:/);
  });

  it('should get occurrences for image', function() {
    const output = execSync(
      `node occurrencesForImage.js "${projectId}" "${resourceUrl}"`
    );
    assert.include(output, new RegExp(`Occurrences for ${resourceUrl}`));
  });

  it('should get discovery info for image', async function() {
    const discoveryNoteRequest = {
      parent: formattedParent,
      noteId: `${noteId}-discovery`,
      note: {
        discovery: {},
      },
    };

    await client.createNote(discoveryNoteRequest);

    const occurrenceRequest = {
      parent: formattedParent,
      occurrence: {
        noteName: `${formattedNoteName}-discovery`,
        discovered: {
          discovered: {
            analysisStatus: 'FINISHED_SUCCESS',
          },
        },
        resource: {
          uri: resourceUrl,
        },
      },
    };

    await client.createOccurrence(occurrenceRequest);

    const output = execSync(
      `node getDiscoveryInfo "${projectId}" "${resourceUrl}"`
    );
    assert.include(
      output,
      new RegExp(`Discovery Occurrences for ${resourceUrl}`)
    );
  });

  it('should get high severity vulnerabilities for image', async function() {
    const criticalNoteReq = {
      parent: formattedParent,
      noteId: `${noteId}-critical`,
      note: {
        vulnerability: {
          severity: 'CRITICAL',
        },
      },
    };

    await client.createNote(criticalNoteReq);

    const criticalOccurrenceReq = {
      parent: formattedParent,
      occurrence: {
        noteName: `${formattedNoteName}-critical`,
        vulnerability: {
          vulnerability: {
            severity: 'CRITICAL',
          },
        },
        resource: {
          uri: resourceUrl,
        },
      },
    };

    await client.createOccurrence(criticalOccurrenceReq);

    const output = execSync(
      `node highVulnerabilitiesForImage "${projectId}" "${resourceUrl}"`
    );

    assert.include(
      output,
      new RegExp(`High Severity Vulnerabilities for ${resourceUrl}`)
    );
  });

  it('should get all vulnerabilites for image', function() {
    const output = execSync(
      `node vulnerabilityOccurrencesForImage "${projectId}" "${resourceUrl}"`
    );
    assert.include(output, new RegExp(`All Vulnerabilities for ${resourceUrl}`));
  });

  it('should delete occurrence', async function() {
    const [occurrences] = await client.listOccurrences({
      parent: formattedParent,
    });
    assert(occurrences.length > 0);
    const occurrence = occurrences[0];
    const occurrenceId = occurrence.name.split('/')[3];

    const output = execSync(
      `node deleteOccurrence.js "${projectId}" "${occurrenceId}"`
    );
    assert.include(output, new RegExp(`Occurrence deleted.`));
  });
  it('should delete note', function() {
    const output = execSync(`node deleteNote.js "${projectId}" "${noteId}" `);
    assert.include(output, new RegExp(`Note ${formattedNoteName} deleted.`));
  });
});

// eslint-disable-next-line no-warning-comments
// TODO: complete polling sample
xdescribe('polling', function() {
  before(async function() {
    // define project id and related vars
    projectId = await client.getProjectId();
    formattedParent = `projects/${projectId}`;
    formattedNoteName = `projects/${projectId}/notes/${noteId}`;

    const discoveryNoteRequest = {
      parent: formattedParent,
      noteId: `${noteId}-discovery-polling`,
      note: {
        discovery: {
          continuousAnalysis: 'INACTIVE',
        },
      },
    };

    await client.createNote(discoveryNoteRequest);

    const occurrenceRequest = {
      parent: formattedParent,
      occurrence: {
        noteName: `${formattedNoteName}-discovery-polling`,
        discovered: {
          discovered: {
            analysisStatus: 'FINISHED_SUCCESS',
          },
        },
      },
      resource: {
        uri: resourceUrl,
      },
    };

    await client.createOccurrence(occurrenceRequest);
  });

  after(async function() {
    const [discoveryOccurrences] = await client.listNoteOccurrences({
      name: `${formattedNoteName}-discovery-polling`,
    });
    discoveryOccurrences.forEach(async occurrence => {
      await client.deleteOccurrence({name: occurrence.name});
    });
    await client.deleteNote({name: `${formattedNoteName}-discovery-polling`});
  });

  it('should successfully poll latest discovery occurrence', function() {
    const output = execSync(
      `node pollDiscoveryOccurrenceFinished.js "${projectId}" "${resourceUrl}" "${timeoutSeconds}"`
    );
    assert.include(
      output,
      new RegExp(`Polled Discovery Occurrences for ${resourceUrl}`)
    );
  });
});

describe('pubsub', function() {
  before(async function() {
    // define project id and related vars
    projectId = await client.getProjectId();
    formattedParent = `projects/${projectId}`;
    formattedNoteName = `projects/${projectId}/notes/${noteId}`;
  });

  beforeEach(async function() {
    await topic.createSubscription(subscriptionId);
    const pubSubNoteReq = {
      parent: formattedParent,
      noteId: `${noteId}-pubsub`,
      note: {
        vulnerability: {},
      },
    };
    await client.createNote(pubSubNoteReq);
  });

  afterEach(async function() {
    await client.deleteNote({name: `${formattedNoteName}-pubsub`});
    await pubsub.subscription(subscriptionId).delete();
  });

  it('should get accurate count of occurrences from pubsub topic', async function() {
    const expectedNum = 3;
    const pubSubOccurrenceReq = {
      parent: formattedParent,
      occurrence: {
        noteName: `${formattedNoteName}-pubsub`,
        vulnerability: {
          vulnerability: {},
        },
        resource: {
          uri: resourceUrl,
        },
      },
    };

    // empty subscription
    execSync(
      `node occurrencePubSub.js "${projectId}" "${subscriptionId}" "${timeoutSeconds}"`
    );

    // make sure empty
    const empty = execSync(
      `node occurrencePubSub.js "${projectId}" "${subscriptionId}" "${timeoutSeconds}"`
    );

    assert.include(empty, new RegExp(`Polled 0 occurrences`));
    // create test occurrences
    for (let i = 0; i < expectedNum; i++) {
      const [pubSubOccurrence] = await client.createOccurrence(
        pubSubOccurrenceReq
      );
      await client.deleteOccurrence({name: pubSubOccurrence.name});
    }
    const output = execSync(
      `node occurrencePubSub.js "${projectId}" "${subscriptionId}" "${timeoutSeconds}"`
    );

    // make sure pubsub number matches
    assert.include(output, new RegExp(`Polled ${expectedNum} occurrences`));
  });
});
<commit_msg>added create topic logic to fix ci test error<commit_after>const {assert} = require('chai');
const cp = require('child_process');
const uuid = require(`uuid`);

const containerAnalysis = require('@google-cloud/containeranalysis');
const client = new containerAnalysis.v1beta1.GrafeasV1Beta1Client();

const execSync = cmd => cp.execSync(cmd, {encoding: 'utf-8'});

const uuidVal = uuid.v4();
const noteId = `test-note-${uuidVal}`;
const resourceUrl = `gcr.io/test-project/test-image-${uuidVal}`;
const subscriptionId = `occurrence-subscription-${uuidVal}`;
const timeoutSeconds = 5;
const retries = 5;

const {PubSub} = require('@google-cloud/pubsub');
const pubsub = new PubSub();
const topicName = 'container-analysis-occurrences-v1beta1';
let topic;

let projectId;
let formattedParent;
let formattedNoteName;

describe('Note tests', function() {
  before(async function() {
    // define projectId and related vars
    projectId = await client.getProjectId();
    formattedParent = `projects/${projectId}`;
    formattedNoteName = `projects/${projectId}/notes/${noteId}`;
  });
  after(async function() {
    const [allOccurrences] = await client.listOccurrences({
      parent: formattedParent,
      filter: `resourceUrl = "${resourceUrl}"`,
    });

    allOccurrences.forEach(async occurrence => {
      await client.deleteOccurrence({name: occurrence.name});
      console.log(`deleted occurrence ${occurrence.name}`);
    });

    const [allNotes] = await client.listNotes({
      parent: formattedParent,
    });

    allNotes.forEach(async note => {
      await client.deleteNote({name: note.name});
      console.log(`deleted note ${note.name}`);
    });
  });
  it('should create a note', function() {
    const output = execSync(`node createNote.js "${projectId}" "${noteId}"`);
    assert.include(output, new RegExp(`Note ${formattedNoteName} created.`));
  });

  it('should get note', function() {
    const output = execSync(`node getNote.js "${projectId}" "${noteId}"`);
    assert.include(output, new RegExp(`Note name: ${formattedNoteName}`));
  });

  it('should create occurrence', function() {
    const output = execSync(
      `node createOccurrence.js "${projectId}" "${noteId}" "${projectId}" "${resourceUrl}"`
    );
    assert.include(output, new RegExp(`Occurrence created`));
  });

  it('should get occurrence', async function() {
    const [occurrences] = await client.listOccurrences({
      parent: formattedParent,
    });
    assert(occurrences.length > 0);

    const occurrence = occurrences[0];
    const occurrenceId = occurrence.name.split('/')[3];
    let output;
    for (let i = 0; i < retries; i++) {
      output = execSync(
        `node getOccurrence.js "${projectId}" "${occurrenceId}"`
      );
      if (output.includes('Occurrence name:')) {
        break;
      }
    }

    assert.include(output, new RegExp(`Occurrence name: ${occurrence.name}`));
  });

  it('should get occurences for note', function() {
    const output = execSync(
      `node occurrencesForNote.js "${projectId}" "${noteId}"`
    );
    assert.include(output, /Occurrences:/);
  });

  it('should get occurrences for image', function() {
    const output = execSync(
      `node occurrencesForImage.js "${projectId}" "${resourceUrl}"`
    );
    assert.include(output, new RegExp(`Occurrences for ${resourceUrl}`));
  });

  it('should get discovery info for image', async function() {
    const discoveryNoteRequest = {
      parent: formattedParent,
      noteId: `${noteId}-discovery`,
      note: {
        discovery: {},
      },
    };

    await client.createNote(discoveryNoteRequest);

    const occurrenceRequest = {
      parent: formattedParent,
      occurrence: {
        noteName: `${formattedNoteName}-discovery`,
        discovered: {
          discovered: {
            analysisStatus: 'FINISHED_SUCCESS',
          },
        },
        resource: {
          uri: resourceUrl,
        },
      },
    };

    await client.createOccurrence(occurrenceRequest);

    const output = execSync(
      `node getDiscoveryInfo "${projectId}" "${resourceUrl}"`
    );
    assert.include(
      output,
      new RegExp(`Discovery Occurrences for ${resourceUrl}`)
    );
  });

  it('should get high severity vulnerabilities for image', async function() {
    const criticalNoteReq = {
      parent: formattedParent,
      noteId: `${noteId}-critical`,
      note: {
        vulnerability: {
          severity: 'CRITICAL',
        },
      },
    };

    await client.createNote(criticalNoteReq);

    const criticalOccurrenceReq = {
      parent: formattedParent,
      occurrence: {
        noteName: `${formattedNoteName}-critical`,
        vulnerability: {
          vulnerability: {
            severity: 'CRITICAL',
          },
        },
        resource: {
          uri: resourceUrl,
        },
      },
    };

    await client.createOccurrence(criticalOccurrenceReq);

    const output = execSync(
      `node highVulnerabilitiesForImage "${projectId}" "${resourceUrl}"`
    );

    assert.include(
      output,
      new RegExp(`High Severity Vulnerabilities for ${resourceUrl}`)
    );
  });

  it('should get all vulnerabilites for image', function() {
    const output = execSync(
      `node vulnerabilityOccurrencesForImage "${projectId}" "${resourceUrl}"`
    );
    assert.include(output, new RegExp(`All Vulnerabilities for ${resourceUrl}`));
  });

  it('should delete occurrence', async function() {
    const [occurrences] = await client.listOccurrences({
      parent: formattedParent,
    });
    assert(occurrences.length > 0);
    const occurrence = occurrences[0];
    const occurrenceId = occurrence.name.split('/')[3];

    const output = execSync(
      `node deleteOccurrence.js "${projectId}" "${occurrenceId}"`
    );
    assert.include(output, new RegExp(`Occurrence deleted.`));
  });
  it('should delete note', function() {
    const output = execSync(`node deleteNote.js "${projectId}" "${noteId}" `);
    assert.include(output, new RegExp(`Note ${formattedNoteName} deleted.`));
  });
});

// eslint-disable-next-line no-warning-comments
// TODO: complete polling sample
xdescribe('polling', function() {
  before(async function() {
    // define project id and related vars
    projectId = await client.getProjectId();
    formattedParent = `projects/${projectId}`;
    formattedNoteName = `projects/${projectId}/notes/${noteId}`;

    const discoveryNoteRequest = {
      parent: formattedParent,
      noteId: `${noteId}-discovery-polling`,
      note: {
        discovery: {
          continuousAnalysis: 'INACTIVE',
        },
      },
    };

    await client.createNote(discoveryNoteRequest);

    const occurrenceRequest = {
      parent: formattedParent,
      occurrence: {
        noteName: `${formattedNoteName}-discovery-polling`,
        discovered: {
          discovered: {
            analysisStatus: 'FINISHED_SUCCESS',
          },
        },
      },
      resource: {
        uri: resourceUrl,
      },
    };

    await client.createOccurrence(occurrenceRequest);
  });

  after(async function() {
    const [discoveryOccurrences] = await client.listNoteOccurrences({
      name: `${formattedNoteName}-discovery-polling`,
    });
    discoveryOccurrences.forEach(async occurrence => {
      await client.deleteOccurrence({name: occurrence.name});
    });
    await client.deleteNote({name: `${formattedNoteName}-discovery-polling`});
  });

  it('should successfully poll latest discovery occurrence', function() {
    const output = execSync(
      `node pollDiscoveryOccurrenceFinished.js "${projectId}" "${resourceUrl}" "${timeoutSeconds}"`
    );
    assert.include(
      output,
      new RegExp(`Polled Discovery Occurrences for ${resourceUrl}`)
    );
  });
});

describe('pubsub', function() {
  before(async function() {
    // define project id and related vars
    projectId = await client.getProjectId();
    formattedParent = `projects/${projectId}`;
    formattedNoteName = `projects/${projectId}/notes/${noteId}`;
    await pubsub.createTopic(topicName);
    topic = pubsub.topic(topicName);
  });

  beforeEach(async function() {
    await topic.createSubscription(subscriptionId);
    const pubSubNoteReq = {
      parent: formattedParent,
      noteId: `${noteId}-pubsub`,
      note: {
        vulnerability: {},
      },
    };
    await client.createNote(pubSubNoteReq);
  });

  afterEach(async function() {
    await client.deleteNote({name: `${formattedNoteName}-pubsub`});
    await pubsub.subscription(subscriptionId).delete();
  });

  it('should get accurate count of occurrences from pubsub topic', async function() {
    const expectedNum = 3;
    const pubSubOccurrenceReq = {
      parent: formattedParent,
      occurrence: {
        noteName: `${formattedNoteName}-pubsub`,
        vulnerability: {
          vulnerability: {},
        },
        resource: {
          uri: resourceUrl,
        },
      },
    };

    // empty subscription
    execSync(
      `node occurrencePubSub.js "${projectId}" "${subscriptionId}" "${timeoutSeconds}"`
    );

    // make sure empty
    const empty = execSync(
      `node occurrencePubSub.js "${projectId}" "${subscriptionId}" "${timeoutSeconds}"`
    );

    assert.include(empty, new RegExp(`Polled 0 occurrences`));
    // create test occurrences
    for (let i = 0; i < expectedNum; i++) {
      const [pubSubOccurrence] = await client.createOccurrence(
        pubSubOccurrenceReq
      );
      await client.deleteOccurrence({name: pubSubOccurrence.name});
    }
    const output = execSync(
      `node occurrencePubSub.js "${projectId}" "${subscriptionId}" "${timeoutSeconds}"`
    );

    // make sure pubsub number matches
    assert.include(output, new RegExp(`Polled ${expectedNum} occurrences`));
  });
});
<|endoftext|>


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

import FieldError from '../../../../../../src/js/components/form/FieldError';
import FieldInput from '../../../../../../src/js/components/form/FieldInput';
import FieldLabel from '../../../../../../src/js/components/form/FieldLabel';
import FormGroup from '../../../../../../src/js/components/form/FormGroup';
import ReducerUtil from '../../../../../../src/js/utils/ReducerUtil';
import {FormReducer as env} from '../../reducers/serviceForm/EnvironmentVariables';
import {FormReducer as labels} from '../../reducers/serviceForm/Labels';

class EnvironmentFormSection extends Component {
  constructor() {
    super(...arguments);

    this.state = {
      reducers: ReducerUtil.combineReducers(
        EnvironmentFormSection.configReducers
      )
    };
  }

  getEnvironmentLines(data) {
    const {errors} = this.props;

    return data.map((env, key) => {
      let keyLabel = null;
      let valueLabel = null;
      if (key === 0) {
        keyLabel = <FieldLabel>Key</FieldLabel>;
        valueLabel = <FieldLabel>Value</FieldLabel>;
      }

      return (

          <FormGroup
            className="column-5"
            required={false}
            showError={Boolean(errors.env[key])}>
            {keyLabel}
            <FieldInput
              name={`env.${key}.key`}
              type="text"
              value={env.key}/>
            <FieldError>{errors.env[key]}</FieldError>
            :
          </FormGroup>
          <FormGroup
            className="column-5"
            required={false}
            showError={Boolean(errors.env[key])}>
            {valueLabel}
            <FieldInput
              name={`env.${key}.value`}
              type="text"
              value={env.value}/>
            <FieldError>{errors.env[key]}</FieldError>
          </FormGroup>
          <FormGroup className="flex flex-item-align-end column-2">

              Delete

          </FormGroup>

    ); });
  }

  getLabelsLines(data) {
    const {errors} = this.props;

    return data.map((label, key) => {
      let keyLabel = null;
      let valueLabel = null;
      if (key === 0) {
        keyLabel = <FieldLabel>Key</FieldLabel>;
        valueLabel = <FieldLabel>Value</FieldLabel>;
      }

      return (

          <FormGroup
            className="column-5"
            required={false}
            showError={Boolean(errors.labels[key])}>
            {keyLabel}
            <FieldInput
              name={`labels.${key}.key`}
              type="text"
              value={label.key}/>
            :
            <FieldError>{errors.labels[key]}</FieldError>
          </FormGroup>
          <FormGroup
            className="column-5"
            required={false}
            showError={Boolean(errors.labels[key])}>
            {valueLabel}
            <FieldInput
              name={`labels.${key}.value`}
              type="text"
              value={label.value}/>
            <FieldError>{errors.labels[key]}</FieldError>
          </FormGroup>
          <FormGroup className="flex flex-item-align-end column-2">

              Delete

          </FormGroup>

      );
    });
  }

  render() {
    let {data} = this.props;

    return (

          Environment Variables

          Set up environment variables for each task your service launches.

        {this.getEnvironmentLines(data.env)}

            + Add Environment Variable

          Labels

          Attach metadata to expose additional information to other services.

        {this.getLabelsLines(data.labels)}

            + Add Label

    );
  }
}

EnvironmentFormSection.defaultProps = {
  data: {},
  errors: {
    env: [],
    labels: []
  },
  onAddItem() {},
  onRemoveItem() {}
};

EnvironmentFormSection.propTypes = {
  data: React.PropTypes.object,
  errors: React.PropTypes.object,
  onAddItem: React.PropTypes.func,
  onRemoveItem: React.PropTypes.func
};

EnvironmentFormSection.configReducers = {
  env,
  labels
};

EnvironmentFormSection.validationReducers = {
  labels() {
    return [];
  },
  env() {
    return [];
  }
};

module.exports = EnvironmentFormSection;
<commit_msg>Remove unnecessary constructor from component<commit_after>import React, {Component} from 'react';

import FieldError from '../../../../../../src/js/components/form/FieldError';
import FieldInput from '../../../../../../src/js/components/form/FieldInput';
import FieldLabel from '../../../../../../src/js/components/form/FieldLabel';
import FormGroup from '../../../../../../src/js/components/form/FormGroup';
import {FormReducer as env} from '../../reducers/serviceForm/EnvironmentVariables';
import {FormReducer as labels} from '../../reducers/serviceForm/Labels';

class EnvironmentFormSection extends Component {

  getEnvironmentLines(data) {
    const {errors} = this.props;

    return data.map((env, key) => {
      let keyLabel = null;
      let valueLabel = null;
      if (key === 0) {
        keyLabel = <FieldLabel>Key</FieldLabel>;
        valueLabel = <FieldLabel>Value</FieldLabel>;
      }

      return (

          <FormGroup
            className="column-5"
            required={false}
            showError={Boolean(errors.env[key])}>
            {keyLabel}
            <FieldInput
              name={`env.${key}.key`}
              type="text"
              value={env.key}/>
            <FieldError>{errors.env[key]}</FieldError>
            :
          </FormGroup>
          <FormGroup
            className="column-5"
            required={false}
            showError={Boolean(errors.env[key])}>
            {valueLabel}
            <FieldInput
              name={`env.${key}.value`}
              type="text"
              value={env.value}/>
            <FieldError>{errors.env[key]}</FieldError>
          </FormGroup>
          <FormGroup className="flex flex-item-align-end column-2">

              Delete

          </FormGroup>

    ); });
  }

  getLabelsLines(data) {
    const {errors} = this.props;

    return data.map((label, key) => {
      let keyLabel = null;
      let valueLabel = null;
      if (key === 0) {
        keyLabel = <FieldLabel>Key</FieldLabel>;
        valueLabel = <FieldLabel>Value</FieldLabel>;
      }

      return (

          <FormGroup
            className="column-5"
            required={false}
            showError={Boolean(errors.labels[key])}>
            {keyLabel}
            <FieldInput
              name={`labels.${key}.key`}
              type="text"
              value={label.key}/>
            :
            <FieldError>{errors.labels[key]}</FieldError>
          </FormGroup>
          <FormGroup
            className="column-5"
            required={false}
            showError={Boolean(errors.labels[key])}>
            {valueLabel}
            <FieldInput
              name={`labels.${key}.value`}
              type="text"
              value={label.value}/>
            <FieldError>{errors.labels[key]}</FieldError>
          </FormGroup>
          <FormGroup className="flex flex-item-align-end column-2">

              Delete

          </FormGroup>

      );
    });
  }

  render() {
    let {data} = this.props;

    return (

          Environment Variables

          Set up environment variables for each task your service launches.

        {this.getEnvironmentLines(data.env)}

            + Add Environment Variable

          Labels

          Attach metadata to expose additional information to other services.

        {this.getLabelsLines(data.labels)}

            + Add Label

    );
  }
}

EnvironmentFormSection.defaultProps = {
  data: {},
  errors: {
    env: [],
    labels: []
  },
  onAddItem() {},
  onRemoveItem() {}
};

EnvironmentFormSection.propTypes = {
  data: React.PropTypes.object,
  errors: React.PropTypes.object,
  onAddItem: React.PropTypes.func,
  onRemoveItem: React.PropTypes.func
};

EnvironmentFormSection.configReducers = {
  env,
  labels
};

EnvironmentFormSection.validationReducers = {
  labels() {
    return [];
  },
  env() {
    return [];
  }
};

module.exports = EnvironmentFormSection;
<|endoftext|>


<commit_before>
/**
 * 查詢 www.moedict.tw
 * 成功查詢的頁面：https://www.moedict.tw/%E5%8B%BE%E8%90%8C
 * http://localhost:3000/moedict/勾萌
 *
 * 成功查詢的頁面：https://www.moedict.tw/%E5%AE%8B
 * http://localhost:3000/moedict/宋
 *
 * 失敗查詢的頁面：https://www.moedict.tw/%E4%B8%8D%E8%90%8C
 * http://localhost:3000/moedict/不萌
 *
 */

CONFIG.module_alias["dict.tw"] = "dict.tw";
launch_proxy["dict.tw"] = function (_output, _query, _mode) {

var _options = {
    module: "dict.tw",
    query: _query,

    // 正式查詢
    url: "http://dict.tw/dict/" + encodeURI(_query),

    encoding: "utf8",

    // --------------------------------------------------
    /**
     * 沒找到資料的選擇器
     */
    //content_not_found_selector: "body",
    content_not_found_string: '<body itemscope="itemscope" itemtype="http://schema.org/ItemList">',

    /**
     * 取出指定元素的HTML程式碼
     */
    //html_selector: ".syllable:first-of-type",

    /**
     * 取出指定元素的純文字
     * 取出音節(斷句)
     */
    //text_selector: ".syllable:first-of-type",

    /**
     * 指定處理元素的方法
     */
    process: function (_content) {
        var _p = $(_content).find(".syllable:first");
        _content = _p[0].text;
        return _content;
    },

    // ------------------------

    /**
     * 指定use_agnet (可省略)
     */
    //user_agent: "Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.102011-10-16 20:23:10",

    /**
     * 指定來源網頁 referer (可省略)
     */
    //referer: "https://zh.wikipedia.org/wiki/Wikipedia:%E9%A6%96%E9%A1%B5",

    // ------------------------
    /**
     * 參考來源網頁的名稱
     */
    //referer_name: "dict.tw線上字典",

    /**
     * 參考來源網頁
     */
    //referer_source: "https://zh.wikipedia.org/w/index.php?title=" + encodeURI(_query) + "&oldformat=true"
};

web_crawler(_output, _options, _mode);

//_res.send(_query);
// ----------------------------------------

};  // launch_proxy = function (_output, _query) {
<commit_msg>20181225 加上解釋查詢看看<commit_after>
/**
 * 查詢 www.moedict.tw
 * 成功查詢的頁面：https://www.moedict.tw/%E5%8B%BE%E8%90%8C
 * http://localhost:3000/moedict/勾萌
 *
 * 成功查詢的頁面：https://www.moedict.tw/%E5%AE%8B
 * http://localhost:3000/moedict/宋
 *
 * 失敗查詢的頁面：https://www.moedict.tw/%E4%B8%8D%E8%90%8C
 * http://localhost:3000/moedict/不萌
 *
 */

CONFIG.module_alias["dict.tw"] = "dict.tw";
launch_proxy["dict.tw"] = function (_output, _query, _mode) {

var _options = {
    module: "dict.tw",
    query: _query,

    // 正式查詢
    url: "http://dict.tw/dict/" + encodeURI(_query),

    encoding: "utf8",

    // --------------------------------------------------
    /**
     * 沒找到資料的選擇器
     */
    //content_not_found_selector: "body",
    content_not_found_string: '<body itemscope="itemscope" itemtype="http://schema.org/ItemList">',

    /**
     * 取出指定元素的HTML程式碼
     */
    //html_selector: ".syllable:first-of-type",

    /**
     * 取出指定元素的純文字
     * 取出音節(斷句)
     */
    //text_selector: ".syllable:first-of-type",

    /**
     * 指定處理元素的方法
     */
    process: function (_content) {
        var _s = $(_content).find(".syllable:first");
        var _syllable =_s[0].text;
        var _d = $(_content).find(".phone:first");
        var _def = _d[0].text;
        _content = _s + _d;
        return _content;
    },

    // ------------------------

    /**
     * 指定use_agnet (可省略)
     */
    //user_agent: "Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.102011-10-16 20:23:10",

    /**
     * 指定來源網頁 referer (可省略)
     */
    //referer: "https://zh.wikipedia.org/wiki/Wikipedia:%E9%A6%96%E9%A1%B5",

    // ------------------------
    /**
     * 參考來源網頁的名稱
     */
    //referer_name: "dict.tw線上字典",

    /**
     * 參考來源網頁
     */
    //referer_source: "https://zh.wikipedia.org/w/index.php?title=" + encodeURI(_query) + "&oldformat=true"
};

web_crawler(_output, _options, _mode);

//_res.send(_query);
// ----------------------------------------

};  // launch_proxy = function (_output, _query) {
<|endoftext|>


<commit_before>/*global defineSuite*/
defineSuite([
        'Scene/RectanglePrimitive',
        'Core/BoundingSphere',
        'Core/Cartesian3',
        'Core/defaultValue',
        'Core/Ellipsoid',
        'Core/GeographicProjection',
        'Core/Math',
        'Core/Rectangle',
        'Core/RectangleGeometry',
        'Renderer/ClearCommand',
        'Scene/SceneMode',
        'Specs/createCamera',
        'Specs/createContext',
        'Specs/createFrameState',
        'Specs/createScene',
        'Specs/destroyContext',
        'Specs/destroyScene',
        'Specs/pick',
        'Specs/render'
    ], function(
        RectanglePrimitive,
        BoundingSphere,
        Cartesian3,
        defaultValue,
        Ellipsoid,
        GeographicProjection,
        CesiumMath,
        Rectangle,
        RectangleGeometry,
        ClearCommand,
        SceneMode,
        createCamera,
        createContext,
        createFrameState,
        createScene,
        destroyContext,
        destroyScene,
        pick,
        render) {
    "use strict";
    /*global jasmine,describe,xdescribe,it,xit,expect,beforeEach,afterEach,beforeAll,afterAll,spyOn,runs,waits,waitsFor*/

    var context;
    var frameState;
    var rectangle;
    var us;

    beforeAll(function() {
        context = createContext();
        frameState = createFrameState();
    });

    afterAll(function() {
        destroyContext(context);
    });

    beforeEach(function() {
        rectangle = new RectanglePrimitive();

        us = context.uniformState;
        us.update(context, createFrameState(createCamera({
            eye : new Cartesian3(1.02, 0.0, 0.0),
            target : Cartesian3.ZERO,
            up : Cartesian3.UNIT_Z
        })));
    });

    afterEach(function() {
        rectangle = rectangle && rectangle.destroy();
        us = undefined;
    });

    function createRectangle(options) {
        options = defaultValue(options, defaultValue.EMPTY_OBJECT);
        var ellipsoid = defaultValue(options.ellipsoid, Ellipsoid.UNIT_SPHERE);

        var e = new RectanglePrimitive({
            ellipsoid : ellipsoid,
            granularity : CesiumMath.toRadians(20.0),
            rectangle : Rectangle.fromDegrees(-20.0, -20.0, 20.0, 20.0),
            id : options.id,
            asynchronous : false,
            debugShowBoundingVolume : options.debugShowBoundingVolume
        });
        e.material.uniforms.color.alpha = 1.0;

        return e;
    }

    it('gets defaults', function() {
        expect(rectangle.show).toEqual(true);
        expect(rectangle.ellipsoid).toEqual(Ellipsoid.WGS84);
        expect(rectangle.granularity).toEqual(CesiumMath.RADIANS_PER_DEGREE);
        expect(rectangle.height).toEqual(0.0);
        expect(rectangle.rotation).toEqual(0.0);
        expect(rectangle.textureRotationAngle).toEqual(0.0);
        expect(rectangle.material.uniforms.color).toEqual({
            red : 1.0,
            green : 1.0,
            blue : 0.0,
            alpha : 0.5
        });
        expect(rectangle.asynchronous).toEqual(true);
        expect(rectangle.debugShowBoundingVolume).toEqual(false);
    });

    it('renders', function() {
        rectangle = createRectangle();
        rectangle.material.uniforms.color = {
            red : 1.0,
            green : 0.0,
            blue : 0.0,
            alpha : 1.0
        };

        ClearCommand.ALL.execute(context);
        expect(context.readPixels()).toEqual([0, 0, 0, 0]);

        render(context, frameState, rectangle);
        expect(context.readPixels()).not.toEqual([0, 0, 0, 0]);
    });

    it('does not render when show is false', function() {
        rectangle = createRectangle();
        rectangle.material.uniforms.color = {
            red : 1.0,
            green : 0.0,
            blue : 0.0,
            alpha : 1.0
        };
        rectangle.show = false;

        expect(render(context, frameState, rectangle)).toEqual(0);
    });

    it('does not render without rectangle', function() {
        rectangle = new RectanglePrimitive();
        rectangle.ellipsoid = Ellipsoid.UNIT_SPHERE;
        rectangle.granularity = CesiumMath.toRadians(20.0);
        expect(render(context, frameState, rectangle)).toEqual(0);
    });

    it('renders bounding volume with debugShowBoundingVolume', function() {
        var scene = createScene();
        var rectangle = scene.primitives.add(createRectangle({
            ellipsoid : Ellipsoid.WGS84,
            debugShowBoundingVolume : true
        }));

        var commandList = [];
        rectangle.update(context, frameState, commandList);

        var sphere = commandList[0].boundingVolume;
        var center = Cartesian3.clone(sphere.center);
        var radius = sphere.radius;

        var camera = scene.camera;
        var direction = Ellipsoid.WGS84.geodeticSurfaceNormal(center, camera.direction);
        Cartesian3.negate(direction, direction);
        Cartesian3.normalize(direction, direction);
        var right = Cartesian3.cross(direction, Cartesian3.UNIT_Z, camera.right);
        Cartesian3.normalize(right, right);
        Cartesian3.cross(right, direction, camera.up);

        var scalar = Cartesian3.magnitude(center) + radius;
        Cartesian3.normalize(center, center);
        Cartesian3.multiplyByScalar(center, scalar, camera.position);

        var pixels = scene.renderForSpecs();
        expect(pixels[0]).not.toEqual(0);
        expect(pixels[1]).toEqual(0);
        expect(pixels[2]).toEqual(0);
        expect(pixels[3]).toEqual(255);

        destroyScene(scene);
    });

    it('is picked', function() {
        rectangle = createRectangle({
            id : 'id'
        });

        var pickedObject = pick(context, frameState, rectangle, 0, 0);
        expect(pickedObject.primitive).toEqual(rectangle);
        expect(pickedObject.id).toEqual('id');
    });

    it('is not picked (show === false)', function() {
        rectangle = createRectangle();
        rectangle.show = false;

        var pickedObject = pick(context, frameState, rectangle, 0, 0);
        expect(pickedObject).not.toBeDefined();
    });

    it('is not picked (alpha === 0.0)', function() {
        rectangle = createRectangle();
        rectangle.material.uniforms.color.alpha = 0.0;

        var pickedObject = pick(context, frameState, rectangle, 0, 0);
        expect(pickedObject).not.toBeDefined();
    });

    it('test 3D bounding sphere', function() {
        var ellipsoid = Ellipsoid.WGS84;
        rectangle = createRectangle({
            ellipsoid : ellipsoid
        });
        var commandList = [];
        rectangle.update(context, frameState, commandList);
        var boundingVolume = commandList[0].boundingVolume;
        expect(boundingVolume).toEqual(BoundingSphere.fromRectangle3D(rectangle.rectangle, ellipsoid));
    });

    it('test Columbus view bounding sphere', function() {
        var ellipsoid = Ellipsoid.WGS84;
        rectangle = createRectangle({
            ellipsoid : ellipsoid
        });

        var mode = frameState.mode;
        frameState.mode = SceneMode.COLUMBUS_VIEW;
        var commandList = [];
        rectangle.update(context, frameState, commandList);
        var boundingVolume = commandList[0].boundingVolume;
        frameState.mode = mode;

        var rectangleGeometry = RectangleGeometry.createGeometry(new RectangleGeometry({
            rectangle : rectangle.rectangle,
            ellipsoid : ellipsoid
        }));
        var projectedPoints = [];
        var projection = new GeographicProjection(ellipsoid);
        for (var i = 0; i < rectangleGeometry.attributes.position.values.length; i += 3) {
            var p = Cartesian3.fromArray(rectangleGeometry.attributes.position.values, i);
            projectedPoints.push(projection.project(ellipsoid.cartesianToCartographic(p)));
        }

        var expected = BoundingSphere.fromPoints(projectedPoints);
        expected.center = Cartesian3.fromElements(expected.center.z, expected.center.x, expected.center.y);
        expect(boundingVolume.center).toEqualEpsilon(expected.center, CesiumMath.EPSILON9);
        expect(boundingVolume.radius).toEqualEpsilon(expected.radius, CesiumMath.EPSILON9);
    });

    it('test 2D bounding sphere', function() {
        var ellipsoid = Ellipsoid.WGS84;
        rectangle = createRectangle({
            ellipsoid : ellipsoid
        });

        var mode = frameState.mode;
        frameState.mode = SceneMode.SCENE2D;
        var commandList = [];
        rectangle.update(context, frameState, commandList);
        var boundingVolume = commandList[0].boundingVolume;
        frameState.mode = mode;

        var rectangleGeometry = RectangleGeometry.createGeometry(new RectangleGeometry({
            rectangle : rectangle.rectangle,
            ellipsoid : ellipsoid
        }));
        var projectedPoints = [];
        var projection = new GeographicProjection(ellipsoid);
        for (var i = 0; i < rectangleGeometry.attributes.position.values.length; i += 3) {
            var p = Cartesian3.fromArray(rectangleGeometry.attributes.position.values, i);
            projectedPoints.push(projection.project(ellipsoid.cartesianToCartographic(p)));
        }

        var expected = BoundingSphere.fromPoints(projectedPoints);
        expected.center = Cartesian3.fromElements(0.0, expected.center.x, expected.center.y);
        expect(boundingVolume.center).toEqualEpsilon(expected.center, CesiumMath.EPSILON9);
        expect(boundingVolume.radius).toEqualEpsilon(expected.radius, CesiumMath.EPSILON9);
    });

    it('isDestroyed', function() {
        var e = new RectanglePrimitive();
        expect(e.isDestroyed()).toEqual(false);
        e.destroy();
        expect(e.isDestroyed()).toEqual(true);
    });

    it('throws when updated/rendered without a ellipsoid', function() {
        rectangle = createRectangle();
        rectangle.ellipsoid = undefined;

        expect(function() {
            rectangle.update(context, frameState);
        }).toThrowDeveloperError();
    });

    it('throws when updated/rendered without an invalid granularity', function() {
        rectangle = createRectangle();
        rectangle.granularity = -1.0;

        expect(function() {
            rectangle.update(context, frameState);
        }).toThrowDeveloperError();
    });

    it('throws when rendered without a material', function() {
        rectangle = createRectangle();
        rectangle.material = undefined;

        expect(function() {
            render(context, frameState, rectangle);
        }).toThrowDeveloperError();
    });
}, 'WebGL');<commit_msg>Fix RectanglePrimitive test with WebGL validation.<commit_after>/*global defineSuite*/
defineSuite([
        'Scene/RectanglePrimitive',
        'Core/BoundingSphere',
        'Core/Cartesian3',
        'Core/defaultValue',
        'Core/Ellipsoid',
        'Core/GeographicProjection',
        'Core/Math',
        'Core/Rectangle',
        'Core/RectangleGeometry',
        'Renderer/ClearCommand',
        'Scene/SceneMode',
        'Specs/createCamera',
        'Specs/createContext',
        'Specs/createFrameState',
        'Specs/createScene',
        'Specs/destroyContext',
        'Specs/destroyScene',
        'Specs/pick',
        'Specs/render'
    ], function(
        RectanglePrimitive,
        BoundingSphere,
        Cartesian3,
        defaultValue,
        Ellipsoid,
        GeographicProjection,
        CesiumMath,
        Rectangle,
        RectangleGeometry,
        ClearCommand,
        SceneMode,
        createCamera,
        createContext,
        createFrameState,
        createScene,
        destroyContext,
        destroyScene,
        pick,
        render) {
    "use strict";
    /*global jasmine,describe,xdescribe,it,xit,expect,beforeEach,afterEach,beforeAll,afterAll,spyOn,runs,waits,waitsFor*/

    var context;
    var frameState;
    var rectangle;
    var us;

    beforeAll(function() {
        context = createContext();
    });

    afterAll(function() {
        destroyContext(context);
    });

    beforeEach(function() {
        rectangle = new RectanglePrimitive();

        frameState = createFrameState(createCamera({
            eye : new Cartesian3(1.02, 0.0, 0.0),
            target : Cartesian3.ZERO,
            up : Cartesian3.UNIT_Z
        }));

        us = context.uniformState;
        us.update(context, frameState);
    });

    afterEach(function() {
        rectangle = rectangle && rectangle.destroy();
        us = undefined;
    });

    function createRectangle(options) {
        options = defaultValue(options, defaultValue.EMPTY_OBJECT);
        var ellipsoid = defaultValue(options.ellipsoid, Ellipsoid.UNIT_SPHERE);

        var e = new RectanglePrimitive({
            ellipsoid : ellipsoid,
            granularity : CesiumMath.toRadians(20.0),
            rectangle : Rectangle.fromDegrees(-20.0, -20.0, 20.0, 20.0),
            id : options.id,
            asynchronous : false,
            debugShowBoundingVolume : options.debugShowBoundingVolume
        });
        e.material.uniforms.color.alpha = 1.0;

        return e;
    }

    it('gets defaults', function() {
        expect(rectangle.show).toEqual(true);
        expect(rectangle.ellipsoid).toEqual(Ellipsoid.WGS84);
        expect(rectangle.granularity).toEqual(CesiumMath.RADIANS_PER_DEGREE);
        expect(rectangle.height).toEqual(0.0);
        expect(rectangle.rotation).toEqual(0.0);
        expect(rectangle.textureRotationAngle).toEqual(0.0);
        expect(rectangle.material.uniforms.color).toEqual({
            red : 1.0,
            green : 1.0,
            blue : 0.0,
            alpha : 0.5
        });
        expect(rectangle.asynchronous).toEqual(true);
        expect(rectangle.debugShowBoundingVolume).toEqual(false);
    });

    it('renders', function() {
        rectangle = createRectangle();
        rectangle.material.uniforms.color = {
            red : 1.0,
            green : 0.0,
            blue : 0.0,
            alpha : 1.0
        };

        ClearCommand.ALL.execute(context);
        expect(context.readPixels()).toEqual([0, 0, 0, 0]);

        render(context, frameState, rectangle);
        expect(context.readPixels()).not.toEqual([0, 0, 0, 0]);
    });

    it('does not render when show is false', function() {
        rectangle = createRectangle();
        rectangle.material.uniforms.color = {
            red : 1.0,
            green : 0.0,
            blue : 0.0,
            alpha : 1.0
        };
        rectangle.show = false;

        expect(render(context, frameState, rectangle)).toEqual(0);
    });

    it('does not render without rectangle', function() {
        rectangle = new RectanglePrimitive();
        rectangle.ellipsoid = Ellipsoid.UNIT_SPHERE;
        rectangle.granularity = CesiumMath.toRadians(20.0);
        expect(render(context, frameState, rectangle)).toEqual(0);
    });

    it('renders bounding volume with debugShowBoundingVolume', function() {
        var rectangle = createRectangle({
            ellipsoid : Ellipsoid.WGS84,
            debugShowBoundingVolume : true
        });

        var commandList = [];
        rectangle.update(context, frameState, commandList);

        var sphere = commandList[0].boundingVolume;
        var center = Cartesian3.clone(sphere.center);
        var radius = sphere.radius;

        var camera = frameState.camera;
        var direction = Ellipsoid.WGS84.geodeticSurfaceNormal(center, camera.direction);
        Cartesian3.negate(direction, direction);
        Cartesian3.normalize(direction, direction);
        var right = Cartesian3.cross(direction, Cartesian3.UNIT_Z, camera.right);
        Cartesian3.normalize(right, right);
        Cartesian3.cross(right, direction, camera.up);

        var scalar = Cartesian3.magnitude(center) + radius;
        Cartesian3.normalize(center, center);
        Cartesian3.multiplyByScalar(center, scalar, camera.position);

        render(context, frameState, rectangle);
        expect(context.readPixels()).not.toEqual([0, 0, 0, 0]);
    });

    it('is picked', function() {
        rectangle = createRectangle({
            id : 'id'
        });

        var pickedObject = pick(context, frameState, rectangle, 0, 0);
        expect(pickedObject.primitive).toEqual(rectangle);
        expect(pickedObject.id).toEqual('id');
    });

    it('is not picked (show === false)', function() {
        rectangle = createRectangle();
        rectangle.show = false;

        var pickedObject = pick(context, frameState, rectangle, 0, 0);
        expect(pickedObject).not.toBeDefined();
    });

    it('is not picked (alpha === 0.0)', function() {
        rectangle = createRectangle();
        rectangle.material.uniforms.color.alpha = 0.0;

        var pickedObject = pick(context, frameState, rectangle, 0, 0);
        expect(pickedObject).not.toBeDefined();
    });

    it('test 3D bounding sphere', function() {
        var ellipsoid = Ellipsoid.WGS84;
        rectangle = createRectangle({
            ellipsoid : ellipsoid
        });
        var commandList = [];
        rectangle.update(context, frameState, commandList);
        var boundingVolume = commandList[0].boundingVolume;
        expect(boundingVolume).toEqual(BoundingSphere.fromRectangle3D(rectangle.rectangle, ellipsoid));
    });

    it('test Columbus view bounding sphere', function() {
        var ellipsoid = Ellipsoid.WGS84;
        rectangle = createRectangle({
            ellipsoid : ellipsoid
        });

        var mode = frameState.mode;
        frameState.mode = SceneMode.COLUMBUS_VIEW;
        var commandList = [];
        rectangle.update(context, frameState, commandList);
        var boundingVolume = commandList[0].boundingVolume;
        frameState.mode = mode;

        var rectangleGeometry = RectangleGeometry.createGeometry(new RectangleGeometry({
            rectangle : rectangle.rectangle,
            ellipsoid : ellipsoid
        }));
        var projectedPoints = [];
        var projection = new GeographicProjection(ellipsoid);
        for (var i = 0; i < rectangleGeometry.attributes.position.values.length; i += 3) {
            var p = Cartesian3.fromArray(rectangleGeometry.attributes.position.values, i);
            projectedPoints.push(projection.project(ellipsoid.cartesianToCartographic(p)));
        }

        var expected = BoundingSphere.fromPoints(projectedPoints);
        expected.center = Cartesian3.fromElements(expected.center.z, expected.center.x, expected.center.y);
        expect(boundingVolume.center).toEqualEpsilon(expected.center, CesiumMath.EPSILON9);
        expect(boundingVolume.radius).toEqualEpsilon(expected.radius, CesiumMath.EPSILON9);
    });

    it('test 2D bounding sphere', function() {
        var ellipsoid = Ellipsoid.WGS84;
        rectangle = createRectangle({
            ellipsoid : ellipsoid
        });

        var mode = frameState.mode;
        frameState.mode = SceneMode.SCENE2D;
        var commandList = [];
        rectangle.update(context, frameState, commandList);
        var boundingVolume = commandList[0].boundingVolume;
        frameState.mode = mode;

        var rectangleGeometry = RectangleGeometry.createGeometry(new RectangleGeometry({
            rectangle : rectangle.rectangle,
            ellipsoid : ellipsoid
        }));
        var projectedPoints = [];
        var projection = new GeographicProjection(ellipsoid);
        for (var i = 0; i < rectangleGeometry.attributes.position.values.length; i += 3) {
            var p = Cartesian3.fromArray(rectangleGeometry.attributes.position.values, i);
            projectedPoints.push(projection.project(ellipsoid.cartesianToCartographic(p)));
        }

        var expected = BoundingSphere.fromPoints(projectedPoints);
        expected.center = Cartesian3.fromElements(0.0, expected.center.x, expected.center.y);
        expect(boundingVolume.center).toEqualEpsilon(expected.center, CesiumMath.EPSILON9);
        expect(boundingVolume.radius).toEqualEpsilon(expected.radius, CesiumMath.EPSILON9);
    });

    it('isDestroyed', function() {
        var e = new RectanglePrimitive();
        expect(e.isDestroyed()).toEqual(false);
        e.destroy();
        expect(e.isDestroyed()).toEqual(true);
    });

    it('throws when updated/rendered without a ellipsoid', function() {
        rectangle = createRectangle();
        rectangle.ellipsoid = undefined;

        expect(function() {
            rectangle.update(context, frameState);
        }).toThrowDeveloperError();
    });

    it('throws when updated/rendered without an invalid granularity', function() {
        rectangle = createRectangle();
        rectangle.granularity = -1.0;

        expect(function() {
            rectangle.update(context, frameState);
        }).toThrowDeveloperError();
    });

    it('throws when rendered without a material', function() {
        rectangle = createRectangle();
        rectangle.material = undefined;

        expect(function() {
            render(context, frameState, rectangle);
        }).toThrowDeveloperError();
    });
}, 'WebGL');<|endoftext|>