<commit_before>// Handle events in body
Template.home.events({
    // When the project name changes, update the Project Summary section of the UI
    'change #PrjName': function (event) {
        console.log("Project changed to " + event.target.value);
        // Get the project name and update UI
        Session.set("projectName", event.target.value);
        updateUIFromPrj();
    },
    // When the project name is clicked, clear-up the UI
    'click #PrjName': function () {
        // Clear the input so that a new project can be selected
        console.log("PrjName clicked, clearing Project Name so that the pulldown shows all projects");
        $("#PrjName").val("");
        Session.set("projectName", "");
        clearUI();
    },
    // When LastTID link was clicked, move the test selector and refresh the UI from Test KB
    'click #lastTIDTxt': function(){
        var lastTID = Session.get("lastTID");
        console.log("Continuing at lastTID " + lastTID)
        $("#testSel").val(lastTID);
        updateUIFromTestKB();
        updateUIFromIssueColl()
    },
    // When the project parameters are changed, persist them
    'change #PrjNotes, change #PrjSoftware': function (event) {
        console.log("Changed " + event.target.id);
        saveProjectDataFromUI();
        updateUIFromPrj();
    },
    // When the scope/methodology selector is changed, persist the value
    'change #ScopeSel': function (event) {
        console.log("Changed scope/methodology selector")
        Session.set("projectScope", event.target.value);
        saveProjectDataFromUI();
    },
    // When the test selector is changed, update the Testing and Generic Issue sections
    'change #testSel': function () {
        console.log("Changed test selection")
        Session.set("lastTID", $("#testSel").val());
        updateUIFromTestKB();
        $('#testNameTA').val("");
        refreshLastTIDLink();
        saveProjectDataFromUI(); // save last TID
        updateUIFromIssueColl()
    },
    // When a test player button is changed, update the Testing and Generic Issue sections
    'click #btnBack': function () {
        selected = $("#testSel").prop("selectedIndex") - 1;
        if (selected <= 0) selected = 1;
        console.log("Selected: " + selected);
        $("#testSel").prop("selectedIndex", selected);
        Session.set("lastTID", $("#testSel").val());
        updateUIFromTestKB();
        $('#testNameTA').typeahead('val', "");
        refreshLastTIDLink();
        saveProjectDataFromUI();
        updateUIFromIssueColl()
    },
    // When a test player button is changed, update the Testing and Generic Issue sections
    'click #btnNext': function () {
        selected = $("#testSel").prop("selectedIndex") + 1;
        if (selected >= $('#testSel > option').length)
            selected = $('#testSel > option').length - 1;
        console.log("Selected: " + selected);
        $("#testSel").prop("selectedIndex", selected);
        Session.set("lastTID", $("#testSel").val());
        updateUIFromTestKB();
        $('#testNameTA').typeahead('val', "");
        refreshLastTIDLink();
        saveProjectDataFromUI();
        updateUIFromIssueColl()
    },
    // When the test name type-ahead is clicked, clear the previous value to help with the search
    'click #testNameTA': function () {
        // Clear the input so that a new test name can be selected
        console.log("Test name text area clicked, clearing field so that another test can be chosen");
        $('#testNameTA').typeahead('val', "");
    },
    // When the New Test button is pressed, clear the UI and create another test
    'click #kbBtnNew': function () {
        console.log('Creating new test: ' + $('#TTestName').val());
        $("#testSel").prop("selectedIndex", 0);
        clearTestingFields();
        clearIssueFields();
        newTest();
    },
    // When the test fields values change, update the Test KB
    'change #TTestName, change #TTesterSupport, change #TTRef, change #cwename, change #cweid, change #TIssueName, change .testKbCB, change #TSeverity, change #TRef1, change #TRef2': function (event) {
        updateTestKBFromUI(event.target.id, event.target.value);
    },
    // When the Specific Issue Data changes, save it to the Issue collection
    'change #IURIs, change #IEvidence, change #IScreenshots, change #IPriority': function (event) {
        saveIssueDataFromUI(event.target.id, event.target.value);

        // Update titles so that mouse-over information matches the content
        $("#IURIs").attr("title", $("#IURIs").val());
        $("#IEvidence").attr("title", $("#IEvidence").val());
        $("#INotes").attr("title", $("#INotes").val());
        updateScreenshots();
    },

    // When the Specific Issue Data changes, parse it if it's formatted as a Burp issue. Then, save it to the Issue collection
    'change #INotes': function (event) {

        // If the note is Burp-formatted, parse it
        var notes = $("#INotes").val();
        var lines = notes.split('\n');
        var issue, evidence, urls;
        var urlSection=false;
        var newNotes="";
        for (var i in lines){
            var t = lines[i].split(':');

            // Capture the Issue Name
            if (lines[i].startsWith('Issue:')){
                issue       = t[1].trim();
            }

            // Capture the URL list
            else if (lines[i].startsWith('URL(s):')){
                urlSection = true;
            }

            else if (urlSection){
                var url = lines[i];
                if ((url !== undefined) && (url.length > 0)){
                    url = url.replace("^ - ", "");
                    urls += url + "\n";
                }
                else
                    urlSection = false;
            }

            // Capture the evidence
            else if (lines[i].startsWith('Evidence:')){
                evidence    = t[1].trim();
            }

            // In the updated notes, prune what we've captured above
            else{
                newNotes = lines[i];
            }
        }

        // Push the captured data to the UI and DB
        if ((issue !== undefined) && (issue.length > 0)){
            saveIssueDataFromUI("#TIssueName", issue);
            $("#TIssueName").val(issue);
        }
        if ((evidence !== undefined) && (evidence.length > 0)){
            // Decode the Base64 value
            evidence = decodeURIComponent(Array.prototype.map.call(atob(evidence), function(c) {
                    return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
                }).join(''));
            saveIssueDataFromUI("#IEvidence", evidence);
            $("#IEvidence").val(evidence);
        }
        if ((urls !== undefined) && (urls.length > 0)){
            saveIssueDataFromUI("#IURIs", urls);
            $("#IURIs").val(urls);
        }
        if (newNotes.length > 0){
            saveIssueDataFromUI("#INotes", newNotes);
            $("#INotes").val(newNotes);
        }

        // Update titles so that mouse-over information matches the content
        $("#IURIs").attr("title", $("#IURIs").val());
        $("#IEvidence").attr("title", $("#IEvidence").val());
        $("#INotes").attr("title", $("#INotes").val());
    },

    // When some fields are clicked, increase the text box size
    'click #IURIs, click #IEvidence, click #IScreenshots, click #INotes, click #PrjNotes, click #TTesterSupport': function (event) {
        //console.log("Increasing the height for " + event.target.id);
        $("#" + event.target.id).height(200);
    },
    // When some fields are unselected, decrease the text box size to a default height
    'blur #IURIs, blur #IEvidence, blur #IScreenshots, blur #INotes, blur #PrjNotes, blur #TTesterSupport': function (event) {
        //console.log("Decreasing the height for " + event.target.id);
        $("#" + event.target.id).height(20);
    },
    // When Evidence and Notes fields are double-clicked, prefill them with template text.
    'dblclick #IEvidence, dblclick #INotes': function () {
        addIssueTemplateTextToUI();
    },
    // When pasting images in Evidence, add a Base64 representation
    'paste #IScreenshots': function (event) {
        pasteScreenshotToUI(event);
    },
    // Generate an HTML report when the 'HTML Report' button is pressed
    'click #btnHtmlReport': function () {
        var prjName = $("#PrjName").val();
        console.log("Generating HTML report for project " + prjName);
        window.open("/report/html/"+prjName, "DownloadWin");
    },
    // Generate a CSV report when the 'CSV Report' button is pressed
    'click #btnCsvReport': function () {
        var prjName = $("#PrjName").val();
        console.log("Generating CSV report for project " + prjName);
        window.open("/report/csv/"+prjName, "DownloadWin");
    },
    // Update this app when the 'Update App' button is pressed
    'click #btnUpdate': function () {
        console.log("Trying to update the WAPT Runner code from GIT...");
        Meteor.call('runCode', function (err, response) {
            if (response !== undefined)
                console.log(response);
            if (err !== undefined)
                console.log(err);
        });
    },
});

// Event handlers for the issue list
Template.myIssueTmpl.events({
    // Delete Issue
    "click .delete": function (event) {
        console.log('Delete clicked from myIssueTmpl! ID=' + this._id);
        issueColl.remove(this._id);
    },
    // Show the issue details when clicking in the list
    "click .isTD": function (event) {
        console.log('Clicked in myIssueTmpl ID=' + this._id + ". TID=" + this.TID);
        $("#testSel").val(this.TID);
        Session.set("lastTID", $("#testSel").val());
        updateUIFromTestKB();
        $('#testNameTA').typeahead('val', "");
        refreshLastTIDLink();
        saveProjectDataFromUI(); // save last TID
        updateUIFromIssueColl()
   }
});
<commit_msg>Minor update<commit_after>// Handle events in body
Template.home.events({
    // When the project name changes, update the Project Summary section of the UI
    'change #PrjName': function (event) {
        console.log("Project changed to " + event.target.value);
        // Get the project name and update UI
        Session.set("projectName", event.target.value);
        updateUIFromPrj();
    },
    // When the project name is clicked, clear-up the UI
    'click #PrjName': function () {
        // Clear the input so that a new project can be selected
        console.log("PrjName clicked, clearing Project Name so that the pulldown shows all projects");
        $("#PrjName").val("");
        Session.set("projectName", "");
        clearUI();
    },
    // When LastTID link was clicked, move the test selector and refresh the UI from Test KB
    'click #lastTIDTxt': function(){
        var lastTID = Session.get("lastTID");
        console.log("Continuing at lastTID " + lastTID)
        $("#testSel").val(lastTID);
        updateUIFromTestKB();
        updateUIFromIssueColl()
    },
    // When the project parameters are changed, persist them
    'change #PrjNotes, change #PrjSoftware': function (event) {
        console.log("Changed " + event.target.id);
        saveProjectDataFromUI();
        updateUIFromPrj();
    },
    // When the scope/methodology selector is changed, persist the value
    'change #ScopeSel': function (event) {
        console.log("Changed scope/methodology selector")
        Session.set("projectScope", event.target.value);
        saveProjectDataFromUI();
    },
    // When the test selector is changed, update the Testing and Generic Issue sections
    'change #testSel': function () {
        console.log("Changed test selection")
        Session.set("lastTID", $("#testSel").val());
        updateUIFromTestKB();
        $('#testNameTA').val("");
        refreshLastTIDLink();
        saveProjectDataFromUI(); // save last TID
        updateUIFromIssueColl()
    },
    // When a test player button is changed, update the Testing and Generic Issue sections
    'click #btnBack': function () {
        selected = $("#testSel").prop("selectedIndex") - 1;
        if (selected <= 0) selected = 1;
        console.log("Selected: " + selected);
        $("#testSel").prop("selectedIndex", selected);
        Session.set("lastTID", $("#testSel").val());
        updateUIFromTestKB();
        $('#testNameTA').typeahead('val', "");
        refreshLastTIDLink();
        saveProjectDataFromUI();
        updateUIFromIssueColl()
    },
    // When a test player button is changed, update the Testing and Generic Issue sections
    'click #btnNext': function () {
        selected = $("#testSel").prop("selectedIndex") + 1;
        if (selected >= $('#testSel > option').length)
            selected = $('#testSel > option').length - 1;
        console.log("Selected: " + selected);
        $("#testSel").prop("selectedIndex", selected);
        Session.set("lastTID", $("#testSel").val());
        updateUIFromTestKB();
        $('#testNameTA').typeahead('val', "");
        refreshLastTIDLink();
        saveProjectDataFromUI();
        updateUIFromIssueColl()
    },
    // When the test name type-ahead is clicked, clear the previous value to help with the search
    'click #testNameTA': function () {
        // Clear the input so that a new test name can be selected
        console.log("Test name text area clicked, clearing field so that another test can be chosen");
        $('#testNameTA').typeahead('val', "");
    },
    // When the New Test button is pressed, clear the UI and create another test
    'click #kbBtnNew': function () {
        console.log('Creating new test: ' + $('#TTestName').val());
        $("#testSel").prop("selectedIndex", 0);
        clearTestingFields();
        clearIssueFields();
        newTest();
    },
    // When the test fields values change, update the Test KB
    'change #TTestName, change #TTesterSupport, change #TTRef, change #cwename, change #cweid, change #TIssueName, change .testKbCB, change #TSeverity, change #TRef1, change #TRef2': function (event) {
        updateTestKBFromUI(event.target.id, event.target.value);
    },
    // When the Specific Issue Data changes, save it to the Issue collection
    'change #IURIs, change #IEvidence, change #IScreenshots, change #IPriority': function (event) {
        saveIssueDataFromUI(event.target.id, event.target.value);

        // Update titles so that mouse-over information matches the content
        $("#IURIs").attr("title", $("#IURIs").val());
        $("#IEvidence").attr("title", $("#IEvidence").val());
        $("#INotes").attr("title", $("#INotes").val());
        updateScreenshots();
    },

    // When the Specific Issue Data changes, parse it if it's formatted as a Burp issue. Then, save it to the Issue collection
    'change #INotes': function (event) {

        // If the note is Burp-formatted, parse it
        var notes = $("#INotes").val();
        var lines = notes.split('\n');
        var issue, evidence, urls;
        var urlSection=false;
        var newNotes="";
        for (var i in lines){
            var t = lines[i].split(':');

            // Capture the Issue Name
            if (lines[i].startsWith('Issue:')){
                issue       = t[1].trim();
            }

            // Capture the URL list
            else if (lines[i].startsWith('URL(s):')){
                urlSection = true;
            }

            else if (urlSection){
                var url = lines[i];
                if ((url !== undefined) && (url.length > 0)){
                    url = url.replace("^ - ", "");
                    urls += url + "\n";
                }
                else
                    urlSection = false;
            }

            // Capture the evidence
            else if (lines[i].startsWith('Evidence:')){
                evidence    = t[1].trim();
            }

            // In the updated notes, prune what we've captured above
            else{
                newNotes += lines[i];
            }
        }

        // Push the captured data to the UI and DB
        if ((issue !== undefined) && (issue.length > 0)){
            saveIssueDataFromUI("#TIssueName", issue);
            $("#TIssueName").val(issue);
        }
        if ((evidence !== undefined) && (evidence.length > 0)){
            // Decode the Base64 value
            evidence = decodeURIComponent(Array.prototype.map.call(atob(evidence), function(c) {
                    return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
                }).join(''));
            saveIssueDataFromUI("#IEvidence", evidence);
            $("#IEvidence").val(evidence);
        }
        if ((urls !== undefined) && (urls.length > 0)){
            saveIssueDataFromUI("#IURIs", urls);
            $("#IURIs").val(urls);
        }
        if (newNotes.length > 0){
            saveIssueDataFromUI("#INotes", newNotes);
            $("#INotes").val(newNotes);
        }

        // Update titles so that mouse-over information matches the content
        $("#IURIs").attr("title", $("#IURIs").val());
        $("#IEvidence").attr("title", $("#IEvidence").val());
        $("#INotes").attr("title", $("#INotes").val());
    },

    // When some fields are clicked, increase the text box size
    'click #IURIs, click #IEvidence, click #IScreenshots, click #INotes, click #PrjNotes, click #TTesterSupport': function (event) {
        //console.log("Increasing the height for " + event.target.id);
        $("#" + event.target.id).height(200);
    },
    // When some fields are unselected, decrease the text box size to a default height
    'blur #IURIs, blur #IEvidence, blur #IScreenshots, blur #INotes, blur #PrjNotes, blur #TTesterSupport': function (event) {
        //console.log("Decreasing the height for " + event.target.id);
        $("#" + event.target.id).height(20);
    },
    // When Evidence and Notes fields are double-clicked, prefill them with template text.
    'dblclick #IEvidence, dblclick #INotes': function () {
        addIssueTemplateTextToUI();
    },
    // When pasting images in Evidence, add a Base64 representation
    'paste #IScreenshots': function (event) {
        pasteScreenshotToUI(event);
    },
    // Generate an HTML report when the 'HTML Report' button is pressed
    'click #btnHtmlReport': function () {
        var prjName = $("#PrjName").val();
        console.log("Generating HTML report for project " + prjName);
        window.open("/report/html/"+prjName, "DownloadWin");
    },
    // Generate a CSV report when the 'CSV Report' button is pressed
    'click #btnCsvReport': function () {
        var prjName = $("#PrjName").val();
        console.log("Generating CSV report for project " + prjName);
        window.open("/report/csv/"+prjName, "DownloadWin");
    },
    // Update this app when the 'Update App' button is pressed
    'click #btnUpdate': function () {
        console.log("Trying to update the WAPT Runner code from GIT...");
        Meteor.call('runCode', function (err, response) {
            if (response !== undefined)
                console.log(response);
            if (err !== undefined)
                console.log(err);
        });
    },
});

// Event handlers for the issue list
Template.myIssueTmpl.events({
    // Delete Issue
    "click .delete": function (event) {
        console.log('Delete clicked from myIssueTmpl! ID=' + this._id);
        issueColl.remove(this._id);
    },
    // Show the issue details when clicking in the list
    "click .isTD": function (event) {
        console.log('Clicked in myIssueTmpl ID=' + this._id + ". TID=" + this.TID);
        $("#testSel").val(this.TID);
        Session.set("lastTID", $("#testSel").val());
        updateUIFromTestKB();
        $('#testNameTA').typeahead('val', "");
        refreshLastTIDLink();
        saveProjectDataFromUI(); // save last TID
        updateUIFromIssueColl()
   }
});
<|endoftext|>


<commit_before>////////////////////////////////////////////////////////////////////////////////
// Server Interface
////////////////////////////////////////////////////////////////////////////////

function requestMap() {
  return [
    {x: 0, z: 0, seH: 0, swH: 0, neH: 0, nwH: 0},
    {x: 0, z: 1, seH: 0, swH: 0, neH: 0, nwH: 0},
    {x: 0, z: 2, seH: 0, swH: 0, neH: 0, nwH: 0},
    {x: 0, z: 3, seH: 0, swH: 0, neH: 0, nwH: 0},
    {x: 0, z: 4, seH: 0, swH: 0, neH: 0, nwH: 0},
    {x: 1, z: 0, seH: 0, swH: 0, neH: 0, nwH: 0},
    {x: 1, z: 1, seH: 0, swH: 0, neH: 0, nwH: 0},
    {x: 1, z: 2, seH: 0, swH: 0, neH: 0, nwH: 0},
    {x: 1, z: 3, seH: 0, swH: 0, neH: 0, nwH: 0},
    {x: 1, z: 4, seH: 0, swH: 0, neH: 0, nwH: 0},
    {x: 2, z: 0, seH: 0, swH: 0, neH: 0, nwH: 0},
    {x: 2, z: 1, seH: 0, swH: 0, neH: 0, nwH: 0},
    {x: 2, z: 2, seH: 0, swH: 0, neH: 0, nwH: 0},
    {x: 2, z: 3, seH: 0, swH: 0, neH: 0, nwH: 0},
    {x: 2, z: 4, seH: 0, swH: 0, neH: 0, nwH: 0},
    {x: 3, z: 0, seH: 0, swH: 0, neH: 0, nwH: 0},
    {x: 3, z: 1, seH: 0, swH: 0, neH: 0, nwH: 0},
    {x: 3, z: 2, seH: 0, swH: 0, neH: 0, nwH: 0},
    {x: 3, z: 3, seH: 0, swH: 0, neH: 0, nwH: 0},
    {x: 3, z: 4, seH: 0, swH: 0, neH: 0, nwH: 0},
    {x: 4, z: 0, seH: 0, swH: 0, neH: 0, nwH: 0},
    {x: 4, z: 1, seH: 0, swH: 0, neH: 0, nwH: 0},
    {x: 4, z: 2, seH: 0, swH: 0, neH: 0, nwH: 0},
    {x: 4, z: 3, seH: 0, swH: 0, neH: 0, nwH: 0},
    {x: 4, z: 4, seH: 0, swH: 0, neH: 0, nwH: 0}
  ];
}

function requestMove(x, z) {
  if (activeUnit != null) {
    moveUnit(activeUnit.uuid, x, z);
  }
}

function pocessUnits() {
  addUnit("abc", 0, 0);
  addUnit("cba", 0, 2);
  addUnit("ars", 0, 4);

  moveUnit("abc", 3, 4);
  moveUnit("cba", 2, 2);
  moveUnit("ars", 4, 3);
}

////////////////////////////////////////////////////////////////////////////////
// Renderer
////////////////////////////////////////////////////////////////////////////////

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);

var renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

var clickable = [];

// Tile/map Management

var map = {
  tiles: {},
  minX: NaN,
  maxX: NaN,
  minY: NaN,
  maxY: NaN,
  minZ: NaN,
  maxZ: NaN
};

function _getMax(existingVal, newVal) {
  if (isNaN(existingVal)) {
    return newVal;
  }
  return Math.max(existingVal, newVal);
}

function _getMin(existingVal, newVal) {
  if (isNaN(existingVal)) {
    return newVal;
  }
  return Math.min(existingVal, newVal);
}

function addTile(tileDef) {
  var tile = _addTile(
    tileDef.x + 0, tileDef.z + 0, // a
    tileDef.x + 0, tileDef.z + 1, // b
    tileDef.x + 1, tileDef.z + 0, // c
    tileDef.x + 1, tileDef.z + 1, // d
    tileDef.seH,
    tileDef.swH,
    tileDef.neH,
    tileDef.nwH
  );

  scene.add(tile);

  tile.x = tileDef.x;
  tile.z = tileDef.z;
  tile.height = (tileDef.seH + tileDef.swH + tileDef.neH + tileDef.nwH) / 4;
  tile.def = tileDef;
  tile.aspire_type = "tile";

  map.minX = _getMin(map.minX, tile.x);
  map.minZ = _getMin(map.minZ, tile.z);
  map.minY = _getMin(map.minY, tile.height);
  map.maxX = _getMax(map.maxX, tile.x + 1);
  map.maxZ = _getMax(map.maxZ, tile.z + 1);
  map.maxY = _getMin(map.maxY, tile.height);

  if (!(tile.x in map.tiles)) {
    map.tiles[tile.x] = {}
  }
  map.tiles[tile.x][tile.z] = tile;

  clickable.push(tile);
}

function _addTile(ax, az, bx, bz, cx, cz, dx, dz, ha, hb, hc, hd) {
  var geometry = new THREE.PlaneGeometry(5, 5, 1, 1);
  geometry.vertices[0] = new THREE.Vector3(ax, ha, az);
  geometry.vertices[1] = new THREE.Vector3(bx, hb, bz);
  geometry.vertices[2] = new THREE.Vector3(cx, hc, cz);
  geometry.vertices[3] = new THREE.Vector3(dx, hd, dz);

  var material = new THREE.MeshPhongMaterial({ color: 0x6F6CC5, specular: 0x555555, shininess: 30, side: THREE.DoubleSide});
  return new THREE.Mesh(geometry, material);
}

function loadMap(tileMap) {
  for (var tile in tileMap) {
    addTile(tileMap[tile]);
  }
}

// Unit Management

var units = {}
var activeUnit = null;

function _initUnitAt(unit, x, z) {
  var y = map.tiles[x][z].height + (unit.height / 2);
  unit.position.set(x + 0.5, y, z + 0.5);
  unit.targPos = new THREE.Vector3(x + 0.5, y, z + 0.5);
}

function addUnit(uuid, x, z) {
  var geometry = new THREE.BoxGeometry(.5, .5, .5);
  var material = new THREE.MeshPhongMaterial({ color: 0x00FF00, specular: 0x555555, shininess: 30, side: THREE.DoubleSide});

  var unit = new THREE.Mesh( geometry, material );
  unit.aspire_type = "unit";
  unit.uuid = uuid;
  unit.height = geometry.parameters.height;
  _initUnitAt(unit, x, z);

  units[uuid] = unit;

  scene.add(unit);

  clickable.push(unit);

  return unit;
}

function setActiveUnit(uuid) {
  activeUnit = units[uuid];
  cameraLookAt(activeUnit);
}

function moveUnit(uuid, x, z) {
  var unit = units[uuid];
  unit.targPos.set(x + 0.5, map.tiles[x][z].height + (unit.height / 2), z + 0.5);
}

function remUnit(uuid) {
  var unit = units[uuid];
  scene.remove(unit);
  clickable.remove(unit);
  delete units[uuid];
}

// Camera Controls
function cameraLookAt(unit) {
  if (unit != null) {
    camera.lookAt(unit.position);
  }
}

function adjustCamera(x, y, z) {
  camera.targPos.x = Math.min(map.maxX + 5, Math.max(map.minX - 5, camera.targPos.x + x));
  camera.targPos.y = Math.min(map.maxY + 5, Math.max(map.minY + 2, camera.targPos.y + y));
  camera.targPos.z = Math.min(map.maxZ + 5, Math.max(map.minZ - 5, camera.targPos.z + z));
}

camera.position.x = -2;
camera.position.y = 3;
camera.position.z = 7;
camera.targPos = new THREE.Vector3(camera.position.x, camera.position.y, camera.position.z);

camera.lookAt(new THREE.Vector3(0, 1, 0));

// Lighting
var light = new THREE.AmbientLight(0x404040); // soft white light
scene.add( light );

var directionalLight = new THREE.DirectionalLight(0xffffff, 0.5);
directionalLight.position.set(0, 1, 0);
scene.add( directionalLight );

// Load game data
loadMap(requestMap(""));
pocessUnits("");

// Rendering & Movement constants
var MOVEMENT_PRECISION = 1;
var MOVEMENT_UNIT = 0.1;

function processMovement(moveable) {
  if (moveable.position.x.toFixed(MOVEMENT_PRECISION) !== moveable.targPos.x.toFixed(MOVEMENT_PRECISION)) {
    if (moveable.position.x < moveable.targPos.x) {
      moveable.position.x += MOVEMENT_UNIT;
    } else {
      moveable.position.x -= MOVEMENT_UNIT;
    }
  }
  if (moveable.position.y.toFixed(MOVEMENT_PRECISION) !== moveable.targPos.y.toFixed(MOVEMENT_PRECISION)) {
    if (moveable.position.y < moveable.targPos.y) {
      moveable.position.y += MOVEMENT_UNIT;
    } else {
      moveable.position.y -= MOVEMENT_UNIT;
    }
  }
  if (moveable.position.z.toFixed(MOVEMENT_PRECISION) !== moveable.targPos.z.toFixed(MOVEMENT_PRECISION)) {
    if (moveable.position.z < moveable.targPos.z) {
      moveable.position.z += MOVEMENT_UNIT;
    } else {
      moveable.position.z -= MOVEMENT_UNIT;
    }
  }
}

var focusRings = [];

function _updateFocusRings() {
  var unitOfChange = 1.0 / focusRings.length;
  for (var ring in focusRings) {
    var focusRing = focusRings[ring];
    focusRing.position.set(activeUnit.position.x, activeUnit.position.y, activeUnit.position.z);
    if ((Number(ring) + 1) % 2 === 0) {
      focusRing.rotateX(.1);
    } else {
      focusRing.rotateY(.1);
    }
  }
}

function drawFocusRing() {
  if (focusRings.length === 0) {
    if (activeUnit != null) {
      var geometry = new THREE.RingGeometry(0.5, 0.6, 32);
      var material = new THREE.MeshBasicMaterial({color: 0xffff00, side: THREE.DoubleSide});
      focusRings = [
        new THREE.Mesh(geometry, material),
        new THREE.Mesh(geometry, material)
      ];
      _updateFocusRings();
      for (var ring in focusRings) {
        scene.add(focusRings[ring]);
      }
    }
  } else {
    if (activeUnit == null) {
      for (var ring in focusRings) {
        scene.remove(focusRings[ring]);
      }
    } else {
      _updateFocusRings();
    }
  }
}

function render() {
  setTimeout(function() {
    requestAnimationFrame(render);

    scene.traverse(function(moveable) {
        if (!moveable.hasOwnProperty("targPos")) {
          return;
        }
        processMovement(moveable);
        cameraLookAt(activeUnit);
      }
    );

    processMovement(camera);
    drawFocusRing();
  }, 1000 / 60);

  renderer.render(scene, camera);
}
render();

window.addEventListener('resize', onWindowResize, false);

function onWindowResize(){

    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();

    renderer.setSize( window.innerWidth, window.innerHeight );

}
<commit_msg>Small optimization<commit_after>////////////////////////////////////////////////////////////////////////////////
// Server Interface
////////////////////////////////////////////////////////////////////////////////

function requestMap() {
  return [
    {x: 0, z: 0, seH: 0, swH: 0, neH: 0, nwH: 0},
    {x: 0, z: 1, seH: 0, swH: 0, neH: 0, nwH: 0},
    {x: 0, z: 2, seH: 0, swH: 0, neH: 0, nwH: 0},
    {x: 0, z: 3, seH: 0, swH: 0, neH: 0, nwH: 0},
    {x: 0, z: 4, seH: 0, swH: 0, neH: 0, nwH: 0},
    {x: 1, z: 0, seH: 0, swH: 0, neH: 0, nwH: 0},
    {x: 1, z: 1, seH: 0, swH: 0, neH: 0, nwH: 0},
    {x: 1, z: 2, seH: 0, swH: 0, neH: 0, nwH: 0},
    {x: 1, z: 3, seH: 0, swH: 0, neH: 0, nwH: 0},
    {x: 1, z: 4, seH: 0, swH: 0, neH: 0, nwH: 0},
    {x: 2, z: 0, seH: 0, swH: 0, neH: 0, nwH: 0},
    {x: 2, z: 1, seH: 0, swH: 0, neH: 0, nwH: 0},
    {x: 2, z: 2, seH: 0, swH: 0, neH: 0, nwH: 0},
    {x: 2, z: 3, seH: 0, swH: 0, neH: 0, nwH: 0},
    {x: 2, z: 4, seH: 0, swH: 0, neH: 0, nwH: 0},
    {x: 3, z: 0, seH: 0, swH: 0, neH: 0, nwH: 0},
    {x: 3, z: 1, seH: 0, swH: 0, neH: 0, nwH: 0},
    {x: 3, z: 2, seH: 0, swH: 0, neH: 0, nwH: 0},
    {x: 3, z: 3, seH: 0, swH: 0, neH: 0, nwH: 0},
    {x: 3, z: 4, seH: 0, swH: 0, neH: 0, nwH: 0},
    {x: 4, z: 0, seH: 0, swH: 0, neH: 0, nwH: 0},
    {x: 4, z: 1, seH: 0, swH: 0, neH: 0, nwH: 0},
    {x: 4, z: 2, seH: 0, swH: 0, neH: 0, nwH: 0},
    {x: 4, z: 3, seH: 0, swH: 0, neH: 0, nwH: 0},
    {x: 4, z: 4, seH: 0, swH: 0, neH: 0, nwH: 0}
  ];
}

function requestMove(x, z) {
  if (activeUnit != null) {
    moveUnit(activeUnit.uuid, x, z);
  }
}

function pocessUnits() {
  addUnit("abc", 0, 0);
  addUnit("cba", 0, 2);
  addUnit("ars", 0, 4);

  moveUnit("abc", 3, 4);
  moveUnit("cba", 2, 2);
  moveUnit("ars", 4, 3);
}

////////////////////////////////////////////////////////////////////////////////
// Renderer
////////////////////////////////////////////////////////////////////////////////

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);

var renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

var clickable = [];

// Tile/map Management

var map = {
  tiles: {},
  minX: NaN,
  maxX: NaN,
  minY: NaN,
  maxY: NaN,
  minZ: NaN,
  maxZ: NaN
};

function _getMax(existingVal, newVal) {
  if (isNaN(existingVal)) {
    return newVal;
  }
  return Math.max(existingVal, newVal);
}

function _getMin(existingVal, newVal) {
  if (isNaN(existingVal)) {
    return newVal;
  }
  return Math.min(existingVal, newVal);
}

function addTile(tileDef) {
  var tile = _addTile(
    tileDef.x + 0, tileDef.z + 0, // a
    tileDef.x + 0, tileDef.z + 1, // b
    tileDef.x + 1, tileDef.z + 0, // c
    tileDef.x + 1, tileDef.z + 1, // d
    tileDef.seH,
    tileDef.swH,
    tileDef.neH,
    tileDef.nwH
  );

  scene.add(tile);

  tile.x = tileDef.x;
  tile.z = tileDef.z;
  tile.height = (tileDef.seH + tileDef.swH + tileDef.neH + tileDef.nwH) / 4;
  tile.def = tileDef;
  tile.aspire_type = "tile";

  map.minX = _getMin(map.minX, tile.x);
  map.minZ = _getMin(map.minZ, tile.z);
  map.minY = _getMin(map.minY, tile.height);
  map.maxX = _getMax(map.maxX, tile.x + 1);
  map.maxZ = _getMax(map.maxZ, tile.z + 1);
  map.maxY = _getMin(map.maxY, tile.height);

  if (!(tile.x in map.tiles)) {
    map.tiles[tile.x] = {}
  }
  map.tiles[tile.x][tile.z] = tile;

  clickable.push(tile);
}

function _addTile(ax, az, bx, bz, cx, cz, dx, dz, ha, hb, hc, hd) {
  var geometry = new THREE.PlaneGeometry(5, 5, 1, 1);
  geometry.vertices[0] = new THREE.Vector3(ax, ha, az);
  geometry.vertices[1] = new THREE.Vector3(bx, hb, bz);
  geometry.vertices[2] = new THREE.Vector3(cx, hc, cz);
  geometry.vertices[3] = new THREE.Vector3(dx, hd, dz);

  var material = new THREE.MeshPhongMaterial({ color: 0x6F6CC5, specular: 0x555555, shininess: 30, side: THREE.DoubleSide});
  return new THREE.Mesh(geometry, material);
}

function loadMap(tileMap) {
  for (var tile in tileMap) {
    addTile(tileMap[tile]);
  }
}

// Unit Management

var units = {}
var activeUnit = null;

function _initUnitAt(unit, x, z) {
  var y = map.tiles[x][z].height + (unit.height / 2);
  unit.position.set(x + 0.5, y, z + 0.5);
  unit.targPos = new THREE.Vector3(x + 0.5, y, z + 0.5);
}

function addUnit(uuid, x, z) {
  var geometry = new THREE.BoxGeometry(.5, .5, .5);
  var material = new THREE.MeshPhongMaterial({ color: 0x00FF00, specular: 0x555555, shininess: 30, side: THREE.DoubleSide});

  var unit = new THREE.Mesh( geometry, material );
  unit.aspire_type = "unit";
  unit.uuid = uuid;
  unit.height = geometry.parameters.height;
  _initUnitAt(unit, x, z);

  units[uuid] = unit;

  scene.add(unit);

  clickable.push(unit);

  return unit;
}

function setActiveUnit(uuid) {
  activeUnit = units[uuid];
  cameraLookAt(activeUnit);
}

function moveUnit(uuid, x, z) {
  var unit = units[uuid];
  unit.targPos.set(x + 0.5, map.tiles[x][z].height + (unit.height / 2), z + 0.5);
}

function remUnit(uuid) {
  var unit = units[uuid];
  scene.remove(unit);
  clickable.remove(unit);
  delete units[uuid];
}

// Camera Controls
function cameraLookAt(unit) {
  if (unit != null) {
    camera.lookAt(unit.position);
  }
}

function adjustCamera(x, y, z) {
  camera.targPos.x = Math.min(map.maxX + 5, Math.max(map.minX - 5, camera.targPos.x + x));
  camera.targPos.y = Math.min(map.maxY + 5, Math.max(map.minY + 2, camera.targPos.y + y));
  camera.targPos.z = Math.min(map.maxZ + 5, Math.max(map.minZ - 5, camera.targPos.z + z));
}

camera.position.x = -2;
camera.position.y = 3;
camera.position.z = 7;
camera.targPos = new THREE.Vector3(camera.position.x, camera.position.y, camera.position.z);

camera.lookAt(new THREE.Vector3(0, 1, 0));

// Lighting
var light = new THREE.AmbientLight(0x404040); // soft white light
scene.add( light );

var directionalLight = new THREE.DirectionalLight(0xffffff, 0.5);
directionalLight.position.set(0, 1, 0);
scene.add( directionalLight );

// Load game data
loadMap(requestMap(""));
pocessUnits("");

// Rendering & Movement constants
var MOVEMENT_PRECISION = 1;
var MOVEMENT_UNIT = 0.1;

function processMovement(moveable) {
  if (moveable.position.x.toFixed(MOVEMENT_PRECISION) !== moveable.targPos.x.toFixed(MOVEMENT_PRECISION)) {
    if (moveable.position.x < moveable.targPos.x) {
      moveable.position.x += MOVEMENT_UNIT;
    } else {
      moveable.position.x -= MOVEMENT_UNIT;
    }
  }
  if (moveable.position.y.toFixed(MOVEMENT_PRECISION) !== moveable.targPos.y.toFixed(MOVEMENT_PRECISION)) {
    if (moveable.position.y < moveable.targPos.y) {
      moveable.position.y += MOVEMENT_UNIT;
    } else {
      moveable.position.y -= MOVEMENT_UNIT;
    }
  }
  if (moveable.position.z.toFixed(MOVEMENT_PRECISION) !== moveable.targPos.z.toFixed(MOVEMENT_PRECISION)) {
    if (moveable.position.z < moveable.targPos.z) {
      moveable.position.z += MOVEMENT_UNIT;
    } else {
      moveable.position.z -= MOVEMENT_UNIT;
    }
  }
}

var focusRings = [];

function _updateFocusRings() {
  var unitOfChange = 1.0 / focusRings.length;
  for (var ring in focusRings) {
    var focusRing = focusRings[ring];
    focusRing.position.set(activeUnit.position.x, activeUnit.position.y, activeUnit.position.z);
    if ((Number(ring) + 1) % 2 === 0) {
      focusRing.rotateX(.1);
    } else {
      focusRing.rotateY(.1);
    }
  }
}

function drawFocusRing() {
  if (focusRings.length === 0) {
    if (activeUnit != null) {
      var geometry = new THREE.RingGeometry(0.5, 0.6, 32);
      var material = new THREE.MeshBasicMaterial({color: 0xffff00, side: THREE.DoubleSide});
      focusRings = [
        new THREE.Mesh(geometry, material),
        new THREE.Mesh(geometry, material)
      ];
      _updateFocusRings();
      for (var ring in focusRings) {
        scene.add(focusRings[ring]);
      }
    }
  } else {
    if (activeUnit == null) {
      for (var ring in focusRings) {
        scene.remove(focusRings[ring]);
      }
    } else {
      _updateFocusRings();
    }
  }
}

function render() {
  setTimeout(function() {
    requestAnimationFrame(render);

    scene.traverse(function(moveable) {
        if (!moveable.hasOwnProperty("targPos")) {
          return;
        }
        processMovement(moveable);
      }
    );

    processMovement(camera);
    cameraLookAt(activeUnit);
    drawFocusRing();
  }, 1000 / 60);

  renderer.render(scene, camera);
}
render();

window.addEventListener('resize', onWindowResize, false);

function onWindowResize(){

    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();

    renderer.setSize( window.innerWidth, window.innerHeight );

}
<|endoftext|>


<commit_before>const React = require("react");
const { Route, IndexRoute } = require("react-router");
const actions = require("./actions/login-actions");

const App = require("./components/App");
const Home = require("./components/Home");
const Polls = require("./components/Polls");
const Poll = require("./components/Poll");
const Login = require("./components/Login");
const Register = require("./components/Register");
const User = require("./components/User");
const Logout = require("./components/Logout");

const wrapStoreToRoutes = function(store) {

  const requireAuth = function(nextState, replaceState) {
    const state = store.getState();

    if(state.user === null) {
      replaceState({ pathname: "/login" });
    }
  };

  const delegateAuth = function(nextState, replaceState) {
    const state = store.getState();

    if(state.user) {
      replaceState({ pathname: "/user/" + state.login.user.id });
    }
  };

  const logout = function(nextState, replaceState) {
    const state = store.getState();

    if(state.user) {
      store.dispatch(actions.logout());
      replaceState({ pathname: "/login" });
    }
    else {
      replaceState({ pathname: "/login" });
    }
  };

  return (
    <Route path="/" component={App}>
      <IndexRoute component={Home}/>
      <Route path="/polls" component={Polls}/>
      <Route path="/polls/:pollId" component={Poll}/>
      <Route path="/login" component={Login} onEnter={delegateAuth}/>
      <Route path="/register" component={Register} onEnter={delegateAuth}/>
      <Route path="/user/:userId" component={User} onEnter={requireAuth}/>
      <Route path="/logout" component={Logout} onEnter={logout}/>
    </Route>
  );
};

module.exports = wrapStoreToRoutes;
<commit_msg>fix invalid user location in store<commit_after>const React = require("react");
const { Route, IndexRoute } = require("react-router");
const actions = require("./actions/login-actions");

const App = require("./components/App");
const Home = require("./components/Home");
const Polls = require("./components/Polls");
const Poll = require("./components/Poll");
const Login = require("./components/Login");
const Register = require("./components/Register");
const User = require("./components/User");
const Logout = require("./components/Logout");

const wrapStoreToRoutes = function(store) {

  const requireAuth = function(nextState, replaceState) {
    const state = store.getState();

    if(state.user === null) {
      replaceState({ pathname: "/login" });
    }
  };

  const delegateAuth = function(nextState, replaceState) {
    const state = store.getState();

    if(state.user) {
      replaceState({ pathname: "/user/" + state.user.id });
    }
  };

  const logout = function(nextState, replaceState) {
    const state = store.getState();

    if(state.user) {
      store.dispatch(actions.logout());
      replaceState({ pathname: "/login" });
    }
    else {
      replaceState({ pathname: "/login" });
    }
  };

  return (
    <Route path="/" component={App}>
      <IndexRoute component={Home}/>
      <Route path="/polls" component={Polls}/>
      <Route path="/polls/:pollId" component={Poll}/>
      <Route path="/login" component={Login} onEnter={delegateAuth}/>
      <Route path="/register" component={Register} onEnter={delegateAuth}/>
      <Route path="/user/:userId" component={User} onEnter={requireAuth}/>
      <Route path="/logout" component={Logout} onEnter={logout}/>
    </Route>
  );
};

module.exports = wrapStoreToRoutes;
<|endoftext|>


<commit_before>var socket = io.connect('http://130.206.83.5');
var start;

socket.on('connect', function(){
	function d(){
		if (working == false){
			var tag = document.createElement('script');
			tag.src = "https://www.youtube.com/iframe_api";
			var firstScriptTag = document.getElementsByTagName('script')[0];
			firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
			working = true;
		}
	}
	var working = false;
	socket.on('ads', function(data) {

		console.log(data);
		d();
		document.getElementById('loadingTitle').style.display = "none";
		ads = data;
		ad = 0;
		start = true;
	});
});<commit_msg>Alex es gay<commit_after>var socket = io.connect('http://130.206.83.5');
var start;

socket.on('connect', function(){
	function d(){
		if (working == false){
			var tag = document.createElement('script');
			tag.src = "https://www.youtube.com/iframe_api";
			var firstScriptTag = document.getElementsByTagName('script')[0];
			firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
			working = true;
		}
	}

	function permuteArray(sort){
		 var rsort = new Array(sort.length);
		 for(var idx = 0; idx < sort.length; idx++)
		 {
		     rsort[idx] = sort[idx];
		 }

		 // then proceed to shuffle the rsort array
		 for(var idx = 0; idx < rsort.length; idx++)
		 {
		    var swpIdx = idx + Math.floor(Math.random() * (rsort.length - idx));
		    // now swap elements at idx and swpIdx
		    var tmp = rsort[idx];
		    rsort[idx] = rsort[swpIdx];
		    rsort[swpIdx] = tmp;
		 }
		 return rsort;
	};

	var working = false;
	socket.on('ads', function(data) {

		console.log(data);
		d();
		document.getElementById('loadingTitle').style.display = "none";
		data = permuteArray(data);
		ads = data;
		ad = 0;
		start = true;
	});
});<|endoftext|>


<commit_before>'use strict';

function float(max) {
    if (undefined === max || 0 > max) {
        max = 100;
    }

    return Math.random() * max;
}

function int(max) {
    return Math.floor(float(max));
}

function string(length) {
    var chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789',
        randomString = '',
        randomNumber,
        i;

    length = length || 8;
    for (i = 0; i < length; i += 1) {
        randomNumber = int(chars.length);
        randomString += chars.substring(randomNumber, randomNumber + 1);
    }

    return randomString;
}
function protocol() {
    var protocols = ['http', 'https'];

    return protocols[int(protocols.length)] + '://';
}

function host() {
    return string() + '.' + string(20) + '.' + string(3);
}

function url(root) {
    var path = '/' + string();

    if (root) {
        return root + path;
    }

    return protocol() + host() + path;
}

function simpleObject() {
    return {
        [string()]: string()
    };
}

function listOf(constructor) {
    var list = [],
        listSize = int(),
        i;

    for (i = 0; i < listSize; i += 1) {
        list.push(constructor());
    }

    return list;
}

module.exports = {
    string: string,
    int: int,
    url: url,
    simpleObject: simpleObject,
    listOf: listOf
};
<commit_msg>lowercased the host portion of the url because case doesnt matter<commit_after>'use strict';

function float(max) {
    if (undefined === max || 0 > max) {
        max = 100;
    }

    return Math.random() * max;
}

function int(max) {
    return Math.floor(float(max));
}

function string(length) {
    var chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789',
        randomString = '',
        randomNumber,
        i;

    length = length || 8;
    for (i = 0; i < length; i += 1) {
        randomNumber = int(chars.length);
        randomString += chars.substring(randomNumber, randomNumber + 1);
    }

    return randomString;
}
function protocol() {
    var protocols = ['http', 'https'];

    return protocols[int(protocols.length)] + '://';
}

function host() {
    return (string() + '.' + string(20) + '.' + string(3)).toLowerCase();
}

function url(root) {
    var path = '/' + string();

    if (root) {
        return root + path;
    }

    return protocol() + host() + path;
}

function simpleObject() {
    return {
        [string()]: string()
    };
}

function listOf(constructor) {
    var list = [],
        listSize = int(),
        i;

    for (i = 0; i < listSize; i += 1) {
        list.push(constructor());
    }

    return list;
}

module.exports = {
    string: string,
    int: int,
    url: url,
    simpleObject: simpleObject,
    listOf: listOf
};
<|endoftext|>


<commit_before>const minimist = require('minimist')
const { build, printCommands, printWtf } = require('gluegun')
const header = require('../brand/header')
const { isNil } = require('ramda')

/**
 * Kick off a run.
 *
 * @param  {array}      argv An array of command line arguments.
 * @return {RunContext}      The gluegun RunContext
 */
module.exports = async function run (argv) {
  // parse the cmd line
  const cmd = minimist(argv.slice(2))

  // create a runtime
  const runtime = build()
    .brand('ignite')
    .loadDefault(`${__dirname}/../plugins/default`)
    .configFile('./ignite.toml')
    .load(`${__dirname}/../core`)
    .loadAll('node_modules', 'ignite-*')
    .token('commandName', 'cliCommand')
    .token('commandDescription', 'cliDescription')
    .token('extensionName', 'contextExtension')
    .createRuntime()

  // wtf mode shows problems with plugins, commands, and extensions
  if (cmd.wtf) {
    printWtf(runtime)
    process.exit(0)
  }

  // run the command
  const context = await runtime.run()

  // print the commands (TODO: but not if we just ran i guess)
  if (isNil(context.plugin) || isNil(context.command)) {
    header()
    printCommands(context)
  }

  // send it back to make testing easier
  return context
}
<commit_msg>Uses the full path to the node_modules.<commit_after>const minimist = require('minimist')
const { build, printCommands, printWtf } = require('gluegun')
const header = require('../brand/header')
const { isNil } = require('ramda')

/**
 * Kick off a run.
 *
 * @param  {array}      argv An array of command line arguments.
 * @return {RunContext}      The gluegun RunContext
 */
module.exports = async function run (argv) {
  // parse the cmd line
  const cmd = minimist(argv.slice(2))

  // create a runtime
  const runtime = build()
    .brand('ignite')
    .configFile('ignite.toml')
    .loadDefault(`${__dirname}/../plugins/default`)
    .loadAll(`${process.cwd()}/node_modules`, 'ignite-*')
    .token('commandName', 'cliCommand')
    .token('commandDescription', 'cliDescription')
    .token('extensionName', 'contextExtension')
    .createRuntime()

  // wtf mode shows problems with plugins, commands, and extensions
  if (cmd.wtf) {
    printWtf(runtime)
    process.exit(0)
  }

  // run the command
  const context = await runtime.run()

  // print the commands (TODO: but not if we just ran i guess)
  if (isNil(context.plugin) || isNil(context.command)) {
    header()
    printCommands(context)
  }

  if (context.error) {
    console.dir(context.error)
  }

  // send it back to make testing easier
  return context
}
<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react';
import bowser from 'bowser';
import classNames from 'classnames';
import THREE from 'three';
import TWEEN from 'tween.js';
import Stats from 'stats.js';
import lodashThrottle from 'lodash/throttle';
import lodashIsEqual from 'lodash/isEqual';

import Stripes from '../Stripes';

import { randomWithRange } from '../../businessLogic/mathHelpers';
import { averageRGB,
         currentColorInTween,
         getColorFromPosition,
         mergeTopAndBottomColors,
         randomRGB } from '../../businessLogic/threeHelpers';

import './orthofloat.scss';

export default class Orthofloat extends Component {
    constructor(props) {
        super(props);

        this.state = {
            windowHeight: window.innerHeight,
            windowWidth: window.innerWidth
        };
    }

    componentWillMount() {
        this.setVendorPrefix();
        this.stripeWidth = 25;
    }

    componentDidMount() {
        this.initializeScene();

        this.windowResizeFunc = lodashThrottle(() => this.onWindowResize(), 16.667);
        window.addEventListener('resize', this.windowResizeFunc);
    }

    componentWillReceiveProps(nextProps) {
        if (!lodashIsEqual(nextProps.bottomColor, this.props.bottomColor)) {
            const { randomShapeMaterialBottom, randomShapeMaterialTop, randomShapeMaterialMid } = this;
            const oldColors = mergeTopAndBottomColors(this.props.topColor, this.props.bottomColor);
            const newColors = mergeTopAndBottomColors(nextProps.topColor, nextProps.bottomColor);

            const tween = new TWEEN.Tween(oldColors)
                .to(newColors, 1000)
                .easing(TWEEN.Easing.Quadratic.Out)
                .onUpdate(function() {
                    randomShapeMaterialBottom.color = currentColorInTween(this, 'bottom');
                    randomShapeMaterialTop.color = currentColorInTween(this, 'top');

                    randomShapeMaterialMid.color = averageRGB(
                        randomShapeMaterialBottom.color,
                        randomShapeMaterialTop.color
                    );
                })
                .start();
        }
    }

    componentWillUnmount() {
        window.removeEventListener('resize', this.windowResizeFunc);
    }

    initializeScene() {
        this.scene = new THREE.Scene();

        this.initializeCamera();
        this.initializeMeshes();
        this.initializeLights();
        this.initializeRenderer();

        if (this.props.initializeWithStats) {
            this.initializeStats();
        }

        this.renderAnimation();
    }

    initializeCamera() {
        const { windowHeight, windowWidth } = this.state;
        this.camFactor = 16;
        this.camera = new THREE.OrthographicCamera(
            windowWidth / - this.camFactor,
            windowWidth / this.camFactor,
            windowHeight / this.camFactor,
            windowHeight / - this.camFactor,
            -200,
            500
        );
        this.camera.position.x = 120;
        this.camera.lookAt(this.scene.position);
    }

    initializeMeshes() {
        this.meshSize = 2.5;
        this.initializeRandomShapes();
        this.initializeTetrahedrons();
    }

    initializeRandomShapes() {
        const { bottomColor, topColor } = this.props;
        const threeTopColor = new THREE.Color(topColor.r, topColor.g, topColor.b);
        const threeBottomColor = new THREE.Color(bottomColor.r, bottomColor.g, bottomColor.b);
        this.randomShapeMaterialTop = new THREE.MeshBasicMaterial({ color: threeTopColor });
        this.randomShapeMaterialBottom = new THREE.MeshBasicMaterial({ color: threeBottomColor });
        const averageColor = averageRGB(this.randomShapeMaterialTop.color, this.randomShapeMaterialBottom.color);
        this.randomShapeMaterialMid = new THREE.MeshBasicMaterial({
            color: new THREE.Color(averageColor.r, averageColor.g, averageColor.b)
        });
        this.randomShapes = [];
        for (let i = 0; i < 53; i++) {
            let shape;
            switch (i % 5) {
                case 0:
                    shape = new THREE.Mesh(this.generateRandomGeometry(), this.randomShapeMaterialTop);
                    break;
                case 1:
                    shape = new THREE.Mesh(this.generateRandomGeometry(), this.randomShapeMaterialBottom);
                    break;
                case 2:
                    shape = new THREE.Mesh(this.generateRandomGeometry(), this.randomShapeMaterialMid);
                    break;
                case 3:
                    shape = new THREE.Mesh(
                        this.generateRandomGeometry(),
                        new THREE.MeshBasicMaterial({ color: threeTopColor })
                    );
                    shape.colorTopToBottom = true;
                    break;
                case 4:
                default:
                    shape = new THREE.Mesh(
                        this.generateRandomGeometry(),
                        new THREE.MeshBasicMaterial({ color: threeBottomColor })
                    );
                    shape.colorBottomToTop = true;
            }
            this.setMeshInSpace(shape);
            this.randomShapes.push(shape);
            this.scene.add(shape);
        }
    }

    generateRandomGeometry() {
        const meshSize = randomWithRange(0.25, 2) * this.meshSize;
        switch (Math.floor(Math.random() * 11)) {
            case 10:
                return new THREE.TorusKnotGeometry(
                    meshSize, meshSize / 3, 40, 12, randomWithRange(1, 20), randomWithRange(1, 20)
                );
            case 9:
                return new THREE.TorusGeometry(meshSize, meshSize / 4, 16, 16, 4);
            case 8:
                return new THREE.SphereGeometry(meshSize, 16, 16);
            case 7:
                return new THREE.RingGeometry(meshSize / 2, meshSize, 16);
            case 6:
                return new THREE.PlaneGeometry(meshSize, meshSize, 0);
            case 5:
                return new THREE.OctahedronGeometry(meshSize, 0);
            case 4:
                return new THREE.IcosahedronGeometry(meshSize, 0);
            case 3:
                return new THREE.DodecahedronGeometry(meshSize, 0);
            case 2:
                return new THREE.CylinderGeometry(meshSize, meshSize, meshSize, 16);
            case 1:
                return new THREE.CircleGeometry(meshSize, 16);
            case 0:
            default:
                return new THREE.BoxGeometry(meshSize, meshSize, meshSize);
        }
    }

    initializeTetrahedrons() {
        const tetraGeometry = new THREE.TetrahedronGeometry(this.meshSize);
        const color = new THREE.Color(0xff6ba9);
        const tetraMaterial = new THREE.MeshBasicMaterial({color});
        this.tetras = [];
        for (let i = 0; i < 50; i++) {
            const tetra = new THREE.Mesh(tetraGeometry, tetraMaterial);
            this.setMeshInSpace(tetra);
            this.tetras.push(tetra);
            this.scene.add(tetra);
        }
    }

    setMeshInSpace(mesh) {
        const { windowHeight, windowWidth } = this.state;
        mesh.position.y = randomWithRange(windowHeight / 16, windowHeight / -16);
        mesh.position.z = randomWithRange(windowWidth / 16, windowWidth / -16);
        mesh.rotation.set(randomWithRange(0, Math.PI), randomWithRange(0, Math.PI), randomWithRange(0, Math.PI));
        mesh.rotationSpeed = {
            x: randomWithRange(-0.01, 0.01),
            y: randomWithRange(-0.01, 0.01),
            z: randomWithRange(-0.01, 0.01)
        };
        mesh.yVelocity = randomWithRange(0.03, 0.1);
        mesh.zVelocity = randomWithRange(-0.01, 0.01);
    }

    initializeLights() {
        const directionalLight = new THREE.DirectionalLight( 0xffffff, 0.7 );
        directionalLight.position.set(60, 60, 60);
        this.scene.add(directionalLight);

        const ambientLight = new THREE.AmbientLight(0x4B4B4B);
        this.scene.add(ambientLight);
    }

    initializeRenderer() {
        const { windowHeight, windowWidth } = this.state;
        this.renderer = new THREE.WebGLRenderer({ alpha: true });
        this.renderer.setSize(windowWidth, windowHeight);

        this.el.appendChild(this.renderer.domElement);
        this.renderer.render(this.scene, this.camera);
    }

    initializeStats() {
        this.stats = new Stats();
        this.el.appendChild(this.stats.dom);
    }

    setVendorPrefix() {
        if (bowser.webkit) {
            this.vendorPrefix = '-webkit-';
        } else if (bowser.firefox) {
            this.vendorPrefix = '-moz-';
        } else if (bowser.opera) {
            this.vendorPrefix = '-o-';
        } else {
            this.vendorPrefix = '';
        }
    }

    onWindowResize() {
        const windowHeight = window.innerHeight,
              windowWidth = window.innerWidth;

        this.setState({ windowHeight, windowWidth });

        this.renderer.setSize(windowWidth, windowHeight);

        this.camera.left = windowWidth / -this.camFactor;
        this.camera.right = windowWidth / this.camFactor;
        this.camera.top = windowHeight / this.camFactor;
        this.camera.bottom = windowHeight / -this.camFactor;
        this.camera.updateProjectionMatrix();
    }

    renderAnimation() {
        if (this.stats && this.props.showStats) {
            this.stats.begin();
        }

        const { windowHeight, windowWidth } = this.state;
        const { topColor, bottomColor } = this.props;

        for (let mesh of this.randomShapes) {
            this.moveMesh(mesh);

            if (mesh.colorTopToBottom) {
                mesh.material.color = getColorFromPosition(mesh.position.y, windowHeight, topColor, bottomColor);
            } else if (mesh.colorBottomToTop) {
                mesh.material.color = getColorFromPosition(mesh.position.y, windowHeight, bottomColor, topColor);
            }
        }

        for (let mesh of this.tetras) {
            this.moveMesh(mesh);
        }

        TWEEN.update();
        this.renderer.render(this.scene, this.camera);

        if (this.stats && this.props.showStats) {
            this.stats.end();
        }

        requestAnimationFrame(() => this.renderAnimation());
    }

    moveMesh(mesh) {
        const { windowHeight, windowWidth } = this.state;

        // if shape is above top of window
        if (mesh.position.y > (windowHeight / 16 + this.meshSize * 3)) {
            // put it below the bottom of the window and give it a random z position
            mesh.position.y -= (windowHeight / 8 + this.meshSize * 6);
            mesh.position.z = randomWithRange(windowWidth / 16, windowWidth / -16);

            // give it new velocities
            mesh.yVelocity = randomWithRange(0.03, 0.1);
            mesh.zVelocity = randomWithRange(-0.01, 0.01);

            // give the mesh new rotation speeds
            for (let axis of ['x', 'y', 'z']) {
                mesh.rotationSpeed[axis] = randomWithRange(-0.01, 0.01);
            }
        }

        // translate the mesh
        mesh.position.y += mesh.yVelocity;
        mesh.position.z += mesh.zVelocity;

        // rotate the mesh around its axes
        for (let axis of ['x', 'y', 'z']) {
            mesh.rotation[axis] += mesh.rotationSpeed[axis];
        }
    }

    render() {
        const { showStats, topColor, bottomColor } = this.props;
        const { windowHeight, windowWidth } = this.state;
        const className = classNames('orthofloat-wrapper', { 'show-stats': showStats });
        const topColorStyle = (new THREE.Color(topColor.r, topColor.g, topColor.b)).getStyle();
        const bottomColorStyle = (new THREE.Color(bottomColor.r, bottomColor.g, bottomColor.b)).getStyle();
        const wrapperStyle = {
            backgroundImage: `${this.vendorPrefix}linear-gradient(${topColorStyle}, ${bottomColorStyle})`
        };

        return (
            <div className={className} style={wrapperStyle} ref={c => this.el = c}>
                <Stripes stripeWidth={this.stripeWidth}
                         vendorPrefix={this.vendorPrefix}
                         topColorStyle={topColorStyle}
                         bottomColorStyle={bottomColorStyle}
                         windowWidth={windowWidth} />
            </div>
        );
    }
}

Orthofloat.propTypes = {
    bottomColor: PropTypes.shape({
        r: PropTypes.number.isRequired,
        g: PropTypes.number.isRequired,
        b: PropTypes.number.isRequired
    }),
    topColor: PropTypes.shape({
        r: PropTypes.number.isRequired,
        g: PropTypes.number.isRequired,
        b: PropTypes.number.isRequired
    }),
    initializeWithStats: PropTypes.bool,
    showStats: PropTypes.bool
};

Orthofloat.defaultProps = {
    bottomColor: randomRGB(),
    topColor: randomRGB(),
    initializeWithStats: false,
    showStats: false
};<commit_msg>assign randomShape a new geometry when it goes to bottom of screen<commit_after>import React, { Component, PropTypes } from 'react';
import bowser from 'bowser';
import classNames from 'classnames';
import THREE from 'three';
import TWEEN from 'tween.js';
import Stats from 'stats.js';
import lodashThrottle from 'lodash/throttle';
import lodashIsEqual from 'lodash/isEqual';

import Stripes from '../Stripes';

import { randomWithRange } from '../../businessLogic/mathHelpers';
import { averageRGB,
         currentColorInTween,
         getColorFromPosition,
         mergeTopAndBottomColors,
         randomRGB } from '../../businessLogic/threeHelpers';

import './orthofloat.scss';

export default class Orthofloat extends Component {
    constructor(props) {
        super(props);

        this.state = {
            windowHeight: window.innerHeight,
            windowWidth: window.innerWidth
        };
    }

    componentWillMount() {
        this.setVendorPrefix();
        this.stripeWidth = 25;
    }

    componentDidMount() {
        this.initializeScene();

        this.windowResizeFunc = lodashThrottle(() => this.onWindowResize(), 16.667);
        window.addEventListener('resize', this.windowResizeFunc);
    }

    componentWillReceiveProps(nextProps) {
        if (!lodashIsEqual(nextProps.bottomColor, this.props.bottomColor)) {
            const { randomShapeMaterialBottom, randomShapeMaterialTop, randomShapeMaterialMid } = this;
            const oldColors = mergeTopAndBottomColors(this.props.topColor, this.props.bottomColor);
            const newColors = mergeTopAndBottomColors(nextProps.topColor, nextProps.bottomColor);

            const tween = new TWEEN.Tween(oldColors)
                .to(newColors, 1000)
                .easing(TWEEN.Easing.Quadratic.Out)
                .onUpdate(function() {
                    randomShapeMaterialBottom.color = currentColorInTween(this, 'bottom');
                    randomShapeMaterialTop.color = currentColorInTween(this, 'top');

                    randomShapeMaterialMid.color = averageRGB(
                        randomShapeMaterialBottom.color,
                        randomShapeMaterialTop.color
                    );
                })
                .start();
        }
    }

    componentWillUnmount() {
        window.removeEventListener('resize', this.windowResizeFunc);
    }

    initializeScene() {
        this.scene = new THREE.Scene();

        this.initializeCamera();
        this.initializeMeshes();
        this.initializeLights();
        this.initializeRenderer();

        if (this.props.initializeWithStats) {
            this.initializeStats();
        }

        this.renderAnimation();
    }

    initializeCamera() {
        const { windowHeight, windowWidth } = this.state;
        this.camFactor = 16;
        this.camera = new THREE.OrthographicCamera(
            windowWidth / - this.camFactor,
            windowWidth / this.camFactor,
            windowHeight / this.camFactor,
            windowHeight / - this.camFactor,
            -200,
            500
        );
        this.camera.position.x = 120;
        this.camera.lookAt(this.scene.position);
    }

    initializeMeshes() {
        this.meshSize = 2.5;
        this.initializeRandomShapes();
        this.initializeTetrahedrons();
    }

    initializeRandomShapes() {
        const { bottomColor, topColor } = this.props;
        const threeTopColor = new THREE.Color(topColor.r, topColor.g, topColor.b);
        const threeBottomColor = new THREE.Color(bottomColor.r, bottomColor.g, bottomColor.b);
        this.randomShapeMaterialTop = new THREE.MeshBasicMaterial({ color: threeTopColor });
        this.randomShapeMaterialBottom = new THREE.MeshBasicMaterial({ color: threeBottomColor });
        const averageColor = averageRGB(this.randomShapeMaterialTop.color, this.randomShapeMaterialBottom.color);
        this.randomShapeMaterialMid = new THREE.MeshBasicMaterial({
            color: new THREE.Color(averageColor.r, averageColor.g, averageColor.b)
        });
        this.randomShapes = [];
        for (let i = 0; i < 53; i++) {
            let shape;
            switch (i % 5) {
                case 0:
                    shape = new THREE.Mesh(this.generateRandomGeometry(), this.randomShapeMaterialTop);
                    break;
                case 1:
                    shape = new THREE.Mesh(this.generateRandomGeometry(), this.randomShapeMaterialBottom);
                    break;
                case 2:
                    shape = new THREE.Mesh(this.generateRandomGeometry(), this.randomShapeMaterialMid);
                    break;
                case 3:
                    shape = new THREE.Mesh(
                        this.generateRandomGeometry(),
                        new THREE.MeshBasicMaterial({ color: threeTopColor })
                    );
                    shape.colorTopToBottom = true;
                    break;
                case 4:
                default:
                    shape = new THREE.Mesh(
                        this.generateRandomGeometry(),
                        new THREE.MeshBasicMaterial({ color: threeBottomColor })
                    );
                    shape.colorBottomToTop = true;
            }
            this.setMeshInSpace(shape);
            this.randomShapes.push(shape);
            this.scene.add(shape);
        }
    }

    generateRandomGeometry() {
        const meshSize = randomWithRange(0.25, 2) * this.meshSize;
        switch (Math.floor(Math.random() * 11)) {
            case 10:
                return new THREE.TorusKnotGeometry(
                    meshSize, meshSize / 3, 40, 12, randomWithRange(1, 20), randomWithRange(1, 20)
                );
            case 9:
                return new THREE.TorusGeometry(meshSize, meshSize / 4, 16, 16, 4);
            case 8:
                return new THREE.SphereGeometry(meshSize, 16, 16);
            case 7:
                return new THREE.RingGeometry(meshSize / 2, meshSize, 16);
            case 6:
                return new THREE.PlaneGeometry(meshSize, meshSize, 0);
            case 5:
                return new THREE.OctahedronGeometry(meshSize, 0);
            case 4:
                return new THREE.IcosahedronGeometry(meshSize, 0);
            case 3:
                return new THREE.DodecahedronGeometry(meshSize, 0);
            case 2:
                return new THREE.CylinderGeometry(meshSize, meshSize, meshSize, 16);
            case 1:
                return new THREE.CircleGeometry(meshSize, 16);
            case 0:
            default:
                return new THREE.BoxGeometry(meshSize, meshSize, meshSize);
        }
    }

    initializeTetrahedrons() {
        const tetraGeometry = new THREE.TetrahedronGeometry(this.meshSize);
        const color = new THREE.Color(0xff6ba9);
        const tetraMaterial = new THREE.MeshBasicMaterial({color});
        this.tetras = [];
        for (let i = 0; i < 50; i++) {
            const tetra = new THREE.Mesh(tetraGeometry, tetraMaterial);
            this.setMeshInSpace(tetra);
            this.tetras.push(tetra);
            this.scene.add(tetra);
        }
    }

    setMeshInSpace(mesh) {
        const { windowHeight, windowWidth } = this.state;
        mesh.position.y = randomWithRange(windowHeight / 16, windowHeight / -16);
        mesh.position.z = randomWithRange(windowWidth / 16, windowWidth / -16);
        mesh.rotation.set(randomWithRange(0, Math.PI), randomWithRange(0, Math.PI), randomWithRange(0, Math.PI));
        mesh.rotationSpeed = {
            x: randomWithRange(-0.01, 0.01),
            y: randomWithRange(-0.01, 0.01),
            z: randomWithRange(-0.01, 0.01)
        };
        mesh.yVelocity = randomWithRange(0.03, 0.1);
        mesh.zVelocity = randomWithRange(-0.01, 0.01);
    }

    initializeLights() {
        const directionalLight = new THREE.DirectionalLight( 0xffffff, 0.7 );
        directionalLight.position.set(60, 60, 60);
        this.scene.add(directionalLight);

        const ambientLight = new THREE.AmbientLight(0x4B4B4B);
        this.scene.add(ambientLight);
    }

    initializeRenderer() {
        const { windowHeight, windowWidth } = this.state;
        this.renderer = new THREE.WebGLRenderer({ alpha: true });
        this.renderer.setSize(windowWidth, windowHeight);

        this.el.appendChild(this.renderer.domElement);
        this.renderer.render(this.scene, this.camera);
    }

    initializeStats() {
        this.stats = new Stats();
        this.el.appendChild(this.stats.dom);
    }

    setVendorPrefix() {
        if (bowser.webkit) {
            this.vendorPrefix = '-webkit-';
        } else if (bowser.firefox) {
            this.vendorPrefix = '-moz-';
        } else if (bowser.opera) {
            this.vendorPrefix = '-o-';
        } else {
            this.vendorPrefix = '';
        }
    }

    onWindowResize() {
        const windowHeight = window.innerHeight,
              windowWidth = window.innerWidth;

        this.setState({ windowHeight, windowWidth });

        this.renderer.setSize(windowWidth, windowHeight);

        this.camera.left = windowWidth / -this.camFactor;
        this.camera.right = windowWidth / this.camFactor;
        this.camera.top = windowHeight / this.camFactor;
        this.camera.bottom = windowHeight / -this.camFactor;
        this.camera.updateProjectionMatrix();
    }

    renderAnimation() {
        if (this.stats && this.props.showStats) {
            this.stats.begin();
        }

        const { windowHeight, windowWidth } = this.state;
        const { topColor, bottomColor } = this.props;

        for (let mesh of this.randomShapes) {
            // if shape is above top of window
            if (mesh.position.y > (windowHeight / 16 + this.meshSize * 4)) {
                mesh.geometry = this.generateRandomGeometry();
                this.repositionMeshToBottom(mesh);
            }

            this.moveMesh(mesh);

            if (mesh.colorTopToBottom) {
                mesh.material.color = getColorFromPosition(mesh.position.y, windowHeight, topColor, bottomColor);
            } else if (mesh.colorBottomToTop) {
                mesh.material.color = getColorFromPosition(mesh.position.y, windowHeight, bottomColor, topColor);
            }
        }

        for (let mesh of this.tetras) {
            // if shape is above top of window
            if (mesh.position.y > (windowHeight / 16 + this.meshSize * 4)) {
                this.repositionMeshToBottom(mesh);
            }

            this.moveMesh(mesh);
        }

        TWEEN.update();
        this.renderer.render(this.scene, this.camera);

        if (this.stats && this.props.showStats) {
            this.stats.end();
        }

        requestAnimationFrame(() => this.renderAnimation());
    }

    repositionMeshToBottom(mesh) {
        const { windowHeight, windowWidth } = this.state;
        // put it below the bottom of the window and give it a random z position
        mesh.position.y -= (windowHeight / 8 + this.meshSize * 8);
        mesh.position.z = randomWithRange(windowWidth / 16, windowWidth / -16);

        // give it new velocities
        mesh.yVelocity = randomWithRange(0.03, 0.1);
        mesh.zVelocity = randomWithRange(-0.01, 0.01);

        // give the mesh new rotation speeds
        for (let axis of ['x', 'y', 'z']) {
            mesh.rotationSpeed[axis] = randomWithRange(-0.01, 0.01);
        }
    }

    moveMesh(mesh) {
        const { windowHeight, windowWidth } = this.state;

        // translate the mesh
        mesh.position.y += mesh.yVelocity;
        mesh.position.z += mesh.zVelocity;

        // rotate the mesh around its axes
        for (let axis of ['x', 'y', 'z']) {
            mesh.rotation[axis] += mesh.rotationSpeed[axis];
        }
    }

    render() {
        const { showStats, topColor, bottomColor } = this.props;
        const { windowHeight, windowWidth } = this.state;
        const className = classNames('orthofloat-wrapper', { 'show-stats': showStats });
        const topColorStyle = (new THREE.Color(topColor.r, topColor.g, topColor.b)).getStyle();
        const bottomColorStyle = (new THREE.Color(bottomColor.r, bottomColor.g, bottomColor.b)).getStyle();
        const wrapperStyle = {
            backgroundImage: `${this.vendorPrefix}linear-gradient(${topColorStyle}, ${bottomColorStyle})`
        };

        return (
            <div className={className} style={wrapperStyle} ref={c => this.el = c}>
                <Stripes stripeWidth={this.stripeWidth}
                         vendorPrefix={this.vendorPrefix}
                         topColorStyle={topColorStyle}
                         bottomColorStyle={bottomColorStyle}
                         windowWidth={windowWidth} />
            </div>
        );
    }
}

Orthofloat.propTypes = {
    bottomColor: PropTypes.shape({
        r: PropTypes.number.isRequired,
        g: PropTypes.number.isRequired,
        b: PropTypes.number.isRequired
    }),
    topColor: PropTypes.shape({
        r: PropTypes.number.isRequired,
        g: PropTypes.number.isRequired,
        b: PropTypes.number.isRequired
    }),
    initializeWithStats: PropTypes.bool,
    showStats: PropTypes.bool
};

Orthofloat.defaultProps = {
    bottomColor: randomRGB(),
    topColor: randomRGB(),
    initializeWithStats: false,
    showStats: false
};<|endoftext|>


<commit_before>function updateCounter(new_value, classname)
{

	var CurrentValue = $(classname).text();

	$({someValue: CurrentValue}).animate({someValue: new_value}, {
		duration: 3000,
		easing:'swing',
		step: function () {
			$(classname).text(Math.round(this.someValue));
		}
	});

}

(function cron()
{

	$.ajax({
		url: 'core/process/aru.php?type=home_update',
		success: function (data) {

			var pokemon	= data[0];
			var lure	= data[1];

			var gym		= data[2];
			var red		= data[3];
			var blue	= data[4];
			var yellow	= data[5];
			var neutral	= data[6];

			updateCounter(pokemon,'.total-pkm-js');
			updateCounter(lure,'.total-lure-js');
			updateCounter(gym,'.total-gym-js');
			updateCounter(red,'.total-valor-js');
			updateCounter(blue,'.total-mystic-js');
			updateCounter(yellow,'.total-instinct-js');
			updateCounter(neutral,'.total-rocket-js');

		},
		complete: function () {
			// Schedule the next request when the current one's complete
			setTimeout(cron, 5000);
		}
	});
})();

(function spawn()
{

	var last_uid = $('.last-mon-js div:first-child').attr('data-pokeuid');

	$.ajax({
		url: 'core/process/aru.php?type=spawnlist_update&last_uid='+last_uid,
		success: function (data) {

			if (!$.isEmptyObject(data)) {

                                $(data).each(function(index,element) {
                                    $('.last-mon-js').prepend(element.html);

                                    // stop timer of last child

                                    stopTimer();
                                    // replace child
                                    $('.last-mon-js > div:last-child').fadeOut();
                                    $('.last-mon-js > div:first-child').fadeIn();
                                    $('.last-mon-js > div:last-child').remove();

                                    // start timer for new child
                                    startTimer(element.countdown,element.pokemon_uid);
                                });

			}

		},
		complete: function () {
			// Schedule the next request when the current one's complete
			setTimeout(spawn, 5000);
		}
	});
})();

// Array with timer IDs
var timers = [];

function startTimer(duration, element)
{       timers.push(setInterval(function () {
                $("[data-pokeuid='"+element+"']").find('.pokemon-timer').text(formatDuration(duration));
		if (--duration >= 0) {
            		$("[data-pokeuid='"+element+"']").find('.pokemon-timer').css({ 'color': 'rgb(62, 150, 62)'});
		} else {
			$("[data-pokeuid='"+element+"']").find('.pokemon-timer').css({ 'color': 'rgb(210, 118, 118)'});
		}
	}, 1000));
}

function stopTimer()
{
	var lastTimer = timers.shift();
	clearInterval(lastTimer);
}

function formatDuration(remainingTime) {
    var countdown = remainingTime, hours, minutes, seconds;
    hours = Math.abs(parseInt(countdown / 3600, 10));
    minutes = Math.abs(parseInt((countdown / 60) % 60, 10));
    seconds = Math.abs(parseInt(countdown % 60, 10));

    hours = hours < 10 ? "0" + hours : hours;
    minutes = minutes < 10 ? "0" + minutes : minutes;
    seconds = seconds < 10 ? "0" + seconds: seconds;

    var output = (countdown<0?"- ":"")+hours + ":" + minutes + ":" + seconds;
    return output;
}<commit_msg>Fix spaces<commit_after>function updateCounter(new_value, classname)
{

	var CurrentValue = $(classname).text();

	$({someValue: CurrentValue}).animate({someValue: new_value}, {
		duration: 3000,
		easing:'swing',
		step: function () {
			$(classname).text(Math.round(this.someValue));
		}
	});

}

(function cron()
{

	$.ajax({
		url: 'core/process/aru.php?type=home_update',
		success: function (data) {

			var pokemon	= data[0];
			var lure	= data[1];

			var gym		= data[2];
			var red		= data[3];
			var blue	= data[4];
			var yellow	= data[5];
			var neutral	= data[6];

			updateCounter(pokemon,'.total-pkm-js');
			updateCounter(lure,'.total-lure-js');
			updateCounter(gym,'.total-gym-js');
			updateCounter(red,'.total-valor-js');
			updateCounter(blue,'.total-mystic-js');
			updateCounter(yellow,'.total-instinct-js');
			updateCounter(neutral,'.total-rocket-js');

		},
		complete: function () {
			// Schedule the next request when the current one's complete
			setTimeout(cron, 5000);
		}
	});
})();

(function spawn()
{

	var last_uid = $('.last-mon-js div:first-child').attr('data-pokeuid');

	$.ajax({
		url: 'core/process/aru.php?type=spawnlist_update&last_uid='+last_uid,
		success: function (data) {

			if (!$.isEmptyObject(data)) {

				$(data).each(function(index,element) {
					$('.last-mon-js').prepend(element.html);

					// stop timer of last child
					stopTimer();

					// replace child
					$('.last-mon-js > div:last-child').fadeOut();
					$('.last-mon-js > div:first-child').fadeIn();
					$('.last-mon-js > div:last-child').remove();

					// start timer for new child
					startTimer(element.countdown,element.pokemon_uid);
				});

			}

		},
		complete: function () {
			// Schedule the next request when the current one's complete
			setTimeout(spawn, 5000);
		}
	});
})();

// Array with timer IDs
var timers = [];

function startTimer(duration, element)
{
	timers.push(setInterval(function () {
		$("[data-pokeuid='"+element+"']").find('.pokemon-timer').text(formatDuration(duration));
		if (--duration >= 0) {
			$("[data-pokeuid='"+element+"']").find('.pokemon-timer').css({ 'color': 'rgb(62, 150, 62)'});
		} else {
			$("[data-pokeuid='"+element+"']").find('.pokemon-timer').css({ 'color': 'rgb(210, 118, 118)'});
		}
	}, 1000));
}

function stopTimer()
{
	var lastTimer = timers.shift();
	clearInterval(lastTimer);
}

function formatDuration(remainingTime)
{
	var countdown = remainingTime, hours, minutes, seconds;
	hours = Math.abs(parseInt(countdown / 3600, 10));
	minutes = Math.abs(parseInt((countdown / 60) % 60, 10));
	seconds = Math.abs(parseInt(countdown % 60, 10));

	hours = hours < 10 ? "0" + hours : hours;
	minutes = minutes < 10 ? "0" + minutes : minutes;
	seconds = seconds < 10 ? "0" + seconds: seconds;

	var output = (countdown<0?"- ":"")+hours + ":" + minutes + ":" + seconds;
	return output;
}
<|endoftext|>


<commit_before>/**
 * This example shows the basic usage of the process_manager library.
**/

// Require npm modules
var q = require('q');

var process_manager;
var utils;
var getExecution;
var node_binary;

// master_process object
var mp;
var mpEventEmitter;

var DEBUG_TEST = false;
var print = function(argA, argB) {
    if(DEBUG_TEST) {
        var msg = 'BT:';
        if(argA) {
            if(argB) {
                console.log(msg, argA, argB);
            } else {
                console.log(msg, argA);
            }
        } else {
            console.log(msg);
        }
    }
};

var createMasterProcess = function() {
	var defered = q.defer();
	mp = new process_manager.master_process();
	defered.resolve(mp);
	return defered.promise;
};
var receivedTestEvents = [];
var initializeMasterProcess = function(eventTitle) {
	var defered = q.defer();
	mpEventEmitter = mp.init();
	mpEventEmitter.on(eventTitle, function(data) {
		print('Received slave_process \'test\' emit', eventTitle, data);
		receivedTestEvents.push(data);
	});
	defered.resolve(mpEventEmitter);
	return defered.promise;
};

var returnedData = [];
var run = function(cwd, execPath) {
	var defered = q.defer();
	// Generic Procedure after initialization
	// 1. Starting slave process
	// 2. Sending a test message
	// 3. Stop the slave process

	// The child process to create
	var childProcessToFork = './test/basic_test_slave.js';

	print('Starting Basic Example');
	var qStartOptions = {
		'startupInfo': 'aa',
		'DEBUG_MODE': false,
	}
	if(execPath !== '') {
		qStartOptions.cwd = cwd;
		qStartOptions.execPath = execPath;
	}
	getExecution(mp, 'qStart', childProcessToFork, qStartOptions)(returnedData)
	.then(getExecution(mp, 'sendMessage', {'dataMessage': 'aB'}))
	.then(getExecution(mp, 'send', 'message', {'dataMessage': 'aB'}))
	.then(getExecution(mp, 'sendReceive', {'dataMessage': 'aa'}))

	// .then(getExecution(mp, 'getProcessInfo'))
	.then(getExecution(mp, 'qStop'))
	.then(function(bundle) {
		print('Received Data');
		bundle.forEach(function(data) {
			var pData;
			if(data.retData) {
				pData = data.retData;
			} else {
				pData = data.errData;
			}
			if(DEBUG_TEST) {
				console.log('\t- ' + data.functionCall + ':', pData);
			}
		});
		print('Finished Basic Example');
		defered.resolve();
	});
	return defered.promise;
};

exports.tests = {
	/**
	 * Creating a new master_process instance.  Is a synchronous function.
	 */
	'create_master_process': function(test) {
		var expectedFunctionList = [
			'init',
			'start',
			'qStart',
			'stop',
			'qStop',
			'sendReceive',
			'sendMessage',
			'send',
			'getProcessInfo',
			'getEventEmitter'
		];

		createMasterProcess()
		.then(function(retData) {
			// Verify function list
			var mpKeys = Object.keys(retData);
			var foundFunctions = [];
			mpKeys.forEach(function(mpKey) {
				if(typeof(retData[mpKey]) === 'function') {
					foundFunctions.push(mpKey);
				}
			});
			test.deepEqual(foundFunctions, expectedFunctionList, 'detected invalid function list');
			test.done();
		});
	},
	/**
	 * Initialize the master_process instance, this will spin up a new
	 * child_process that is ready to start sending & receiving messages.
	 */
	'initialize_master_process': function(test) {
		var eventTitle = 'test';
		initializeMasterProcess(eventTitle)
		.then(function(retData) {
			var expectedFunctionList = [
				'startChildProcess',
				'qSendInternalMessage',
				'qSendReceiveMessage',
				'sendReceiveMessage',
				'sendMessage',
				'emitMessage',
				'qStopChildProcess',
				'stopChildProcess'
			];
			var mpKeys = Object.keys(retData);
			var foundFunctions = [];
			mpKeys.forEach(function(mpKey) {
				if(typeof(retData[mpKey]) === 'function') {
					foundFunctions.push(mpKey);
				}
			});
			test.deepEqual(foundFunctions, expectedFunctionList, 'detected invalid function list');

			// Verify returned element is an event emitter
			var msg = 'initializing the master process didn\t return an event emitter';
			test.strictEqual(typeof(retData.on),'function', msg);

			test.done();
		});
	},
	'verify_event_listeners': function(test) {
		var expectedListeners = [
			'criticalError',
			'messageBufferFull',
			'ReceivedInvalidMessage',
			'test'
		];

		var events = mpEventEmitter._events;
		var eventKeys = Object.keys(events);
		var foundEventListeners = [];
		eventKeys.forEach(function(key) {
			if(typeof(events[key]) === 'function') {
				foundEventListeners.push(key);
			}
		});

		var msg = 'invalid event listeners detected';
		test.deepEqual(foundEventListeners, expectedListeners, msg);
		test.done();
	},
	'basic_execution': function(test) {
		var expectedTestEvents = [
			'Test Data',
			'Test Data'
		];

		var expectedReturnData = [
			{
				'functionCall': 'qStart',
				'retData': {
					'startupInfo': 'aa',
					'DEBUG_MODE': false,
					'cwd': process.cwd(),
					'execPath': node_binary
				}
			}, {
				'functionCall': 'sendMessage',
				'retData': undefined
			}, {
				'functionCall': 'send',
				'retData': undefined
			}, {
				'functionCall': 'sendReceive',
				'retData': {
					'arbitraryData': 'Arbitrary data from basic_test_slave.js'
				}
			}, {
				'functionCall': 'qStop',
				'retData': { 'numLostMessages': 0 }
			}
		];
		run(process.cwd(), node_binary)
		.then(function(data) {
			test.ok(true);
			// Check to make sure that the testEvents were fired
			test.deepEqual(receivedTestEvents, expectedTestEvents, 'Issue with event messaging');

			// Check to make sure that the the sendReceive/master_process
			// functions were called properly
			test.deepEqual(returnedData, expectedReturnData, 'Issue with send receive messaging');
			test.done();
		});
	}
};
exports.setImports = function(imports) {
	process_manager = imports.process_manager;
	utils = imports.utils;
	getExecution = utils.getExecution;
	node_binary = imports.node_binary;
};
<commit_msg>Chris's test descriptions.<commit_after>/**
 * This example shows the basic usage of the process_manager library.
**/

// Require npm modules
var q = require('q');

var process_manager;
var utils;
var getExecution;
var node_binary;

// master_process object
var mp;
var mpEventEmitter;

var DEBUG_TEST = false;
var print = function(argA, argB) {
    if(DEBUG_TEST) {
        var msg = 'BT:';
        if(argA) {
            if(argB) {
                console.log(msg, argA, argB);
            } else {
                console.log(msg, argA);
            }
        } else {
            console.log(msg);
        }
    }
};

var createMasterProcess = function() {
	var defered = q.defer();
	mp = new process_manager.master_process();
	defered.resolve(mp);
	return defered.promise;
};
var receivedTestEvents = [];
var initializeMasterProcess = function(eventTitle) {
	var defered = q.defer();
	mpEventEmitter = mp.init();
	mpEventEmitter.on(eventTitle, function(data) {
		print('Received slave_process \'test\' emit', eventTitle, data);
		receivedTestEvents.push(data);
	});
	defered.resolve(mpEventEmitter);
	return defered.promise;
};

var returnedData = [];
var run = function(cwd, execPath) {
	var defered = q.defer();
	// Generic Procedure after initialization
	// 1. Starting slave process
	// 2. Sending a test message
	// 3. Stop the slave process

	// The child process to create
	var childProcessToFork = './test/basic_test_slave.js';

	print('Starting Basic Example');
	var qStartOptions = {
		'startupInfo': 'aa',
		'DEBUG_MODE': false,
	}
	if(execPath !== '') {
		qStartOptions.cwd = cwd;
		qStartOptions.execPath = execPath;
	}
	getExecution(mp, 'qStart', childProcessToFork, qStartOptions)(returnedData)
	.then(getExecution(mp, 'sendMessage', {'dataMessage': 'aB'}))
	.then(getExecution(mp, 'send', 'message', {'dataMessage': 'aB'}))
	.then(getExecution(mp, 'sendReceive', {'dataMessage': 'aa'}))

	// .then(getExecution(mp, 'getProcessInfo'))
	.then(getExecution(mp, 'qStop'))
	.then(function(bundle) {
		print('Received Data');
		bundle.forEach(function(data) {
			var pData;
			if(data.retData) {
				pData = data.retData;
			} else {
				pData = data.errData;
			}
			if(DEBUG_TEST) {
				console.log('\t- ' + data.functionCall + ':', pData);
			}
		});
		print('Finished Basic Example');
		defered.resolve();
	});
	return defered.promise;
};

exports.tests = {
	/**
	 * Creating a new master_process instance.  Is a synchronous function.
	 */
	'create_master_process': function(test) {
		var expectedFunctionList = [
			'init',
			'start',
			'qStart',
			'stop',
			'qStop',
			'sendReceive',
			'sendMessage',
			'send',
			'getProcessInfo',
			'getEventEmitter'
		];

		createMasterProcess()
		.then(function(retData) {
			// Verify function list
			var mpKeys = Object.keys(retData);
			var foundFunctions = [];
			mpKeys.forEach(function(mpKey) {
				if(typeof(retData[mpKey]) === 'function') {
					foundFunctions.push(mpKey);
				}
			});
			test.deepEqual(foundFunctions, expectedFunctionList, 'detected invalid function list');
			test.done();
		});
	},
	/**
	 * Initialize the master_process instance, this test makes sure that
	 * initializing the master process returns an event listener.  this process
	 * can be done synchronously but is wrapped by a promise to make it async.
	 */
	'initialize_master_process': function(test) {
		var eventTitle = 'test';
		initializeMasterProcess(eventTitle)
		.then(function(retData) {
			var expectedFunctionList = [
				'startChildProcess',
				'qSendInternalMessage',
				'qSendReceiveMessage',
				'sendReceiveMessage',
				'sendMessage',
				'emitMessage',
				'qStopChildProcess',
				'stopChildProcess'
			];
			var mpKeys = Object.keys(retData);
			var foundFunctions = [];
			mpKeys.forEach(function(mpKey) {
				if(typeof(retData[mpKey]) === 'function') {
					foundFunctions.push(mpKey);
				}
			});
			test.deepEqual(foundFunctions, expectedFunctionList, 'detected invalid function list');

			// Verify returned element is an event emitter
			var msg = 'initializing the master process didn\t return an event emitter';
			test.strictEqual(typeof(retData.on),'function', msg);

			test.done();
		});
	},
	'verify_event_listeners': function(test) {
		var expectedListeners = [
			'criticalError',
			'messageBufferFull',
			'ReceivedInvalidMessage',
			'test'
		];

		var events = mpEventEmitter._events;
		var eventKeys = Object.keys(events);
		var foundEventListeners = [];
		eventKeys.forEach(function(key) {
			if(typeof(events[key]) === 'function') {
				foundEventListeners.push(key);
			}
		});

		var msg = 'invalid event listeners detected';
		test.deepEqual(foundEventListeners, expectedListeners, msg);
		test.done();
	},
	/**
	 * This test starts a new process and performs some IO to the process and
	 * checks the results of the sendReceive message as well as the send &
	 * sendMessage functions.  The one way messages get handled by the
	 * previously established event listeners.
	 */
	'basic_execution': function(test) {
		var expectedTestEvents = [
			'Test Data',
			'Test Data'
		];

		var expectedReturnData = [
			{
				'functionCall': 'qStart',
				'retData': {
					'startupInfo': 'aa',
					'DEBUG_MODE': false,
					'cwd': process.cwd(),
					'execPath': node_binary
				}
			}, {
				'functionCall': 'sendMessage',
				'retData': undefined
			}, {
				'functionCall': 'send',
				'retData': undefined
			}, {
				'functionCall': 'sendReceive',
				'retData': {
					'arbitraryData': 'Arbitrary data from basic_test_slave.js'
				}
			}, {
				'functionCall': 'qStop',
				'retData': { 'numLostMessages': 0 }
			}
		];
		run(process.cwd(), node_binary)
		.then(function(data) {
			test.ok(true);
			// Check to make sure that the testEvents were fired
			test.deepEqual(receivedTestEvents, expectedTestEvents, 'Issue with event messaging');

			// Check to make sure that the the sendReceive/master_process
			// functions were called properly
			test.deepEqual(returnedData, expectedReturnData, 'Issue with send receive messaging');
			test.done();
		});
	}
};
exports.setImports = function(imports) {
	process_manager = imports.process_manager;
	utils = imports.utils;
	getExecution = utils.getExecution;
	node_binary = imports.node_binary;
};
<|endoftext|>