<commit_before>/**
 * Created by truthlighting on 9/20/2016.
 */
/**
 * This guys does the other half of energy collection. The miner gets it from the source, and the helper does the
 * transportation. We don't want them just going for the nearest source, as that means that if we have more than one
 * miner, all the helpers will only go for the first miner. To counter this, we assign them to a miner the same way
 * we assign a miner to a source
 */

var helper = {
    parts: [
        [MOVE, CARRY],
        [MOVE, CARRY, MOVE, CARRY],
        [MOVE, CARRY, MOVE, CARRY, MOVE, CARRY]
    ],

    assignMiner: function () {
        var creep = this.creep;

        var miner = creep.pos.findClosestByPath(FIND_MY_CREEPS, {
            filter: function (miner) {
                if (miner.memory.role == 'miner' && miner.memory.helpers.length < miner.memory.helpersNeeded)
                    return true;

                return false;
            }
        });

        if (miner == undefined)
            return;

        creep.memory.miner = miner.id;
        miner.memory.helpers.push(creep.id);
    },

    /**
     * @TODO: Make helpers smarter about avoiding miners, instead of just waiting till they're 5 tiles away
     * @TODO: When spawns are at .25, and extensions have >= 200, help builders before filling shit up
     */
    action: function () {
        var creep = this.creep;

        if (creep.memory.courier !== undefined && creep.memory.courier == true) {
            creep.memory.courier = false;
            return;
        }

        //If this helper isn't assigned to a miner, find one and assign him to it. If it is assigned to a miner,
        //then find that miner by his id
        if (creep.memory.miner == undefined)
            this.assignMiner();

        var miner = Game.getObjectById(creep.memory.miner);

        if (miner == null) {
            creep.suicide();
            return;
        }
        //console.log("i'm here1");
        //If we can still pick up energy, let's do that
        //console.log("miner: " + miner);
        //console.log("creep:" + creep);
        //console.log("creep.carry: (" + _.sum(creep.carry) + ") < creep.carryCapacity (" + creep.carryCapacity + ")");
        //console.log(_.sum(creep.carry) < creep.carryCapacity);
        if (_.sum(creep.carry) < creep.carryCapacity) {
            //console.log("i'm here");
            if (creep.pos.isNearTo(miner)) {
                var energy = creep.pos.findInRange(FIND_DROPPED_ENERGY, 1)[0];
                //console.log("energy: " + energy);
                creep.pickup(energy);
            }
            else {
                if (miner.memory.isNearSource)
                    creep.moveTo(miner);
            }

            return;
        }

        var target = null;
        //console.log("I'm here");
        //Okay, everything below is for dropping energy off

        if (!target) {
            console.log("I'm heree");
            //var spawn = creep.pos.findClosestByPath(FIND_MY_SPAWNS);
            var energyStructures = creep.room.find(FIND_STRUCTURES, {
                            filter: (structure) => {
                                return (structure.structureType == STRUCTURE_EXTENSION ||
                                structure.structureType == STRUCTURE_SPAWN) &&
                //            structure.structureType == STRUCTURE_TOWER) &&
                                (structure.energy < structure.energyCapacity);
                            }
            })
            var energyStructure = creep.room.findClosestByPath(energyStructures);
            console.log("energyStructure: " + energyStructure);
            //If we found it, set it as our target
            if (energyStructure)
                target = energyStructure;
        }
        console.log(energyStructures);
        console.log(energyStructure);
        console.log(target);
        //console.log(" creep.pos.findPathTo: " + creep.pos.findPathTo(target));
        //Let's get the direction we want to go in
        var targetDirection = creep.pos.findPathTo(target, { ignoreCreeps: true })[0].direction;
        //console.log("I'm here 3");
        //Let's look for a courier in that direction. We'll check on making sure they're the right
        //role, if they can hold any energy, if they're in range and if they're in the same direction
        var leftDir = targetDirection - 1;
        var rightDir = targetDirection + 1;

        if (leftDir < 1)
            leftDir += 8;
        if (leftDir > 8)
            leftDir -= 8;

        if (rightDir < 1)
            rightDir += 8;
        if (rightDir > 8)
            rightDir -= 8;
        console.log("I'm here 2");
        var courier = creep.pos.findClosestByPath(FIND_MY_CREEPS, {
            filter: function (possibleTarget) {
                return (
                    possibleTarget.memory.role == creep.memory.role
//					&& possibleTarget.memory.miner == creep.memory.miner
                    && _.sum(possibleTarget.carry) < possibleTarget.carryCapacity
                    && creep.pos.inRangeTo(possibleTarget, 1)
                    && (
                        creep.pos.getDirectionTo(possibleTarget) == targetDirection
                        || creep.pos.getDirectionTo(possibleTarget) == leftDir
                        || creep.pos.getDirectionTo(possibleTarget) == rightDir
                    )
                );
            }
        });
        console.log("im here");
        //If we found a courier, make that courier our new target
        if (courier !== null && !creep.pos.isNearTo(target)) {
            target = courier;
            target.memory.courier = true;
        }
        //console.log("target: " + target);
        //If we're near to the target, either give it our energy or drop it
        if (creep.pos.isNearTo(target)) {
            if (_.sum(target.carry) < target.carryCapacity) {
                creep.transfer(target, RESOURCE_ENERGY);
            }
            else
                creep.drop(RESOURCE_ENERGY);
        }
        //Let's do the moving
        else {
            creep.moveTo(target);
        }
    }
};

module.exports = helper;<commit_msg>fixing miner<commit_after>/**
 * Created by truthlighting on 9/20/2016.
 */
/**
 * This guys does the other half of energy collection. The miner gets it from the source, and the helper does the
 * transportation. We don't want them just going for the nearest source, as that means that if we have more than one
 * miner, all the helpers will only go for the first miner. To counter this, we assign them to a miner the same way
 * we assign a miner to a source
 */

var helper = {
    parts: [
        [MOVE, CARRY],
        [MOVE, CARRY, MOVE, CARRY],
        [MOVE, CARRY, MOVE, CARRY, MOVE, CARRY]
    ],

    assignMiner: function () {
        var creep = this.creep;

        var miner = creep.pos.findClosestByPath(FIND_MY_CREEPS, {
            filter: function (miner) {
                if (miner.memory.role == 'miner' && miner.memory.helpers.length < miner.memory.helpersNeeded)
                    return true;

                return false;
            }
        });

        if (miner == undefined)
            return;

        creep.memory.miner = miner.id;
        miner.memory.helpers.push(creep.id);
    },

    /**
     * @TODO: Make helpers smarter about avoiding miners, instead of just waiting till they're 5 tiles away
     * @TODO: When spawns are at .25, and extensions have >= 200, help builders before filling shit up
     */
    action: function () {
        var creep = this.creep;

        if (creep.memory.courier !== undefined && creep.memory.courier == true) {
            creep.memory.courier = false;
            return;
        }

        //If this helper isn't assigned to a miner, find one and assign him to it. If it is assigned to a miner,
        //then find that miner by his id
        if (creep.memory.miner == undefined)
            this.assignMiner();

        var miner = Game.getObjectById(creep.memory.miner);

        if (miner == null) {
            creep.suicide();
            return;
        }
        //console.log("i'm here1");
        //If we can still pick up energy, let's do that
        //console.log("miner: " + miner);
        //console.log("creep:" + creep);
        //console.log("creep.carry: (" + _.sum(creep.carry) + ") < creep.carryCapacity (" + creep.carryCapacity + ")");
        //console.log(_.sum(creep.carry) < creep.carryCapacity);
        if (_.sum(creep.carry) < creep.carryCapacity) {
            //console.log("i'm here");
            if (creep.pos.isNearTo(miner)) {
                var energy = creep.pos.findInRange(FIND_DROPPED_ENERGY, 1)[0];
                //console.log("energy: " + energy);
                creep.pickup(energy);
            }
            else {
                if (miner.memory.isNearSource)
                    creep.moveTo(miner);
            }

            return;
        }

        var target = null;
        //console.log("I'm here");
        //Okay, everything below is for dropping energy off

        if (!target) {
            //console.log("I'm heree");
            //var spawn = creep.pos.findClosestByPath(FIND_MY_SPAWNS);
            var energyStructures = creep.room.find(FIND_STRUCTURES, {
                            filter: (structure) => {
                                return (structure.structureType == STRUCTURE_EXTENSION ||
                                structure.structureType == STRUCTURE_SPAWN) &&
                //            structure.structureType == STRUCTURE_TOWER) &&
                                (structure.energy < structure.energyCapacity);
                            }
            })

            var energyStructure = creep.room.findClosestByPath(energyStructures);
            console.log("energyStructure: " + energyStructure);
            //If we found it, set it as our target
            if (energyStructure)
                target = energyStructure;
        }
        console.log("I'm here!");
        console.log(energyStructures);
        console.log(energyStructure);
        console.log(target);
        //console.log(" creep.pos.findPathTo: " + creep.pos.findPathTo(target));
        //Let's get the direction we want to go in
        var targetDirection = creep.pos.findPathTo(target, { ignoreCreeps: true })[0].direction;
        //console.log("I'm here 3");
        //Let's look for a courier in that direction. We'll check on making sure they're the right
        //role, if they can hold any energy, if they're in range and if they're in the same direction
        var leftDir = targetDirection - 1;
        var rightDir = targetDirection + 1;

        if (leftDir < 1)
            leftDir += 8;
        if (leftDir > 8)
            leftDir -= 8;

        if (rightDir < 1)
            rightDir += 8;
        if (rightDir > 8)
            rightDir -= 8;
        console.log("I'm here 2");
        var courier = creep.pos.findClosestByPath(FIND_MY_CREEPS, {
            filter: function (possibleTarget) {
                return (
                    possibleTarget.memory.role == creep.memory.role
//					&& possibleTarget.memory.miner == creep.memory.miner
                    && _.sum(possibleTarget.carry) < possibleTarget.carryCapacity
                    && creep.pos.inRangeTo(possibleTarget, 1)
                    && (
                        creep.pos.getDirectionTo(possibleTarget) == targetDirection
                        || creep.pos.getDirectionTo(possibleTarget) == leftDir
                        || creep.pos.getDirectionTo(possibleTarget) == rightDir
                    )
                );
            }
        });
        console.log("im here");
        //If we found a courier, make that courier our new target
        if (courier !== null && !creep.pos.isNearTo(target)) {
            target = courier;
            target.memory.courier = true;
        }
        //console.log("target: " + target);
        //If we're near to the target, either give it our energy or drop it
        if (creep.pos.isNearTo(target)) {
            if (_.sum(target.carry) < target.carryCapacity) {
                creep.transfer(target, RESOURCE_ENERGY);
            }
            else
                creep.drop(RESOURCE_ENERGY);
        }
        //Let's do the moving
        else {
            creep.moveTo(target);
        }
    }
};

module.exports = helper;<|endoftext|>


<commit_before>;(function() {  // IFEE
  'use strict';

  angular
    .module('brewKeeper')
    .controller('RecipeListController', RecipeListController);

  RecipeListController.$inject =
    ['$location', '$rootScope', '$routeParams', 'dataService', 'recipeService'];

  function RecipeListController(
      $location,
      $rootScope,
      $routeParams,
      dataService,
      recipeService
  ) {
    var vm = this;
    vm.isPublic = ($location.path().indexOf('/public') === 0);
    vm.listBrewIt = listBrewIt;
    vm.newRating = newRating;
    vm.rateRecipe = rateRecipe;
    vm.ratingOrderBy = ratingOrderBy;
    vm.ratings = [{max: $rootScope.maxStars}];
    vm.recipes = [];
    vm.search = search;
    vm.updateRating = updateRating;

    var localUser = vm.isPublic ? 'public' : $rootScope.username;
    var publicUrl = '/api/users/public/recipes/';
    var recipesUrl = null;

    activate();

    ////////////////////////////////////////////////////////////////////////////
    // FUNCTIONS //////////////////////////////////////////////////////////////
    //////////////////////////////////////////////////////////////////////////

    /**
     * Prepare the page.
     */
    function activate() {
      if (vm.isPublic) {
        recipesUrl = publicUrl;
        if ($routeParams.username) {
          // If provided, show the public recipes for the specified user
          vm.search($routeParams.username);
          return;
        }
      } else {
        recipesUrl = '/api/users/' + $rootScope.username + '/recipes/';
      }
      // Attempt to get the recipes for this user from the cache
      vm.recipes = recipeService.getRecipes(localUser);
      // If full set of orders not in the cache, get them from the API
      if (vm.recipes.length <= 1) {
        dataService.get(recipesUrl)
          .then(function(response) {
            vm.recipes = recipeService.cacheRecipes(response.data);
          });
      }
    }

    /**
     * Brew a recipe in the list.
     */
    function listBrewIt(id) {
      $location.path("/" + localUser + "/" + id + "/brewit");
    }

    /**
     * Submit a rating for a public recipe.
     */
    function newRating(rating, recipeId) {
      // Ensure that we only take this action on public recipes
      if (!vm.isPublic) {
        return;
      }
      var providedRating = {"public_rating": rating};
      dataService.post(publicUrl + recipeId + '/ratings/', providedRating)
        // Now that we have posted, update the rating to reflect the change
        .then(function() {
          dataService.get(publicUrl + recipeId + '/')
            .then(function(response) {
              recipeService.cacheRecipes(response.data);
              vm.recipes = recipeService.getRecipes('public');
            });
        });
    }

    /**
     * Rate a recipe in the list.
     */
    function rateRecipe(rating, id) {
      // Ensure that we only take this action on private recipes
      if (vm.isPublic) {
        return;
      }
      var newRating = {"rating": rating};
      dataService.patch(recipesUrl + id + '/', newRating);
    }

    /**
     * Depending on whether this is a public page or not, supply the correct
     * rating orderBy.
     */
    function ratingOrderBy() {
      if (vm.isPublic) {
        return '-combined_rating';
      }

      return '-rating';
    }

    /**
     * Display all of the user's recipes matching the given string. If no
     * string is given, get all of the recipes at the recipes url.
     */
    function search(searchString) {
      var searchParams = '';
      if (searchString !== undefined) {
        searchParams = '?search=' + searchString;
      }
      dataService.get(recipesUrl + searchParams)
        .then(function(response) {
          vm.recipes = recipeService.cacheRecipes(response.data);
        });
    }

    /**
     * Update an existing public rating.
     */
    function updateRating(rating, ratingId, recipeId) {
      // Ensure that we only take this action on public recipes
      if (!vm.isPublic) {
        return;
      }
      var providedRating = {"public_rating": rating};
      dataService.patch(
        publicUrl + recipeId + '/ratings/' + ratingId + '/',
        providedRating);
    }
  }
})();
<commit_msg>If empty search, show all recipes for 'user'<commit_after>;(function() {  // IFEE
  'use strict';

  angular
    .module('brewKeeper')
    .controller('RecipeListController', RecipeListController);

  RecipeListController.$inject =
    ['$location', '$rootScope', '$routeParams', 'dataService', 'recipeService'];

  function RecipeListController(
      $location,
      $rootScope,
      $routeParams,
      dataService,
      recipeService
  ) {
    var vm = this;
    vm.isPublic = ($location.path().indexOf('/public') === 0);
    vm.listBrewIt = listBrewIt;
    vm.newRating = newRating;
    vm.rateRecipe = rateRecipe;
    vm.ratingOrderBy = ratingOrderBy;
    vm.ratings = [{max: $rootScope.maxStars}];
    vm.recipes = [];
    vm.search = search;
    vm.updateRating = updateRating;

    var localUser = vm.isPublic ? 'public' : $rootScope.username;
    var publicUrl = '/api/users/public/recipes/';
    var recipesUrl = null;

    activate();

    ////////////////////////////////////////////////////////////////////////////
    // FUNCTIONS //////////////////////////////////////////////////////////////
    //////////////////////////////////////////////////////////////////////////

    /**
     * Prepare the page.
     */
    function activate() {
      if (vm.isPublic) {
        recipesUrl = publicUrl;
        if ($routeParams.username) {
          // If provided, show the public recipes for the specified user
          vm.search($routeParams.username);
          return;
        }
      } else {
        recipesUrl = '/api/users/' + $rootScope.username + '/recipes/';
      }
      // Attempt to get the recipes for this user from the cache
      vm.recipes = recipeService.getRecipes(localUser);
      // If full set of orders not in the cache, get them from the API
      if (vm.recipes.length <= 1) {
        dataService.get(recipesUrl)
          .then(function(response) {
            vm.recipes = recipeService.cacheRecipes(response.data);
          });
      }
    }

    /**
     * Brew a recipe in the list.
     */
    function listBrewIt(id) {
      $location.path("/" + localUser + "/" + id + "/brewit");
    }

    /**
     * Submit a rating for a public recipe.
     */
    function newRating(rating, recipeId) {
      // Ensure that we only take this action on public recipes
      if (!vm.isPublic) {
        return;
      }
      var providedRating = {"public_rating": rating};
      dataService.post(publicUrl + recipeId + '/ratings/', providedRating)
        // Now that we have posted, update the rating to reflect the change
        .then(function() {
          dataService.get(publicUrl + recipeId + '/')
            .then(function(response) {
              recipeService.cacheRecipes(response.data);
              vm.recipes = recipeService.getRecipes('public');
            });
        });
    }

    /**
     * Rate a recipe in the list.
     */
    function rateRecipe(rating, id) {
      // Ensure that we only take this action on private recipes
      if (vm.isPublic) {
        return;
      }
      var newRating = {"rating": rating};
      dataService.patch(recipesUrl + id + '/', newRating);
    }

    /**
     * Depending on whether this is a public page or not, supply the correct
     * rating orderBy.
     */
    function ratingOrderBy() {
      if (vm.isPublic) {
        return '-combined_rating';
      }

      return '-rating';
    }

    /**
     * Display all of the user's recipes matching the given string. If no
     * string is given, get all of the recipes at the recipes url.
     */
    function search(searchString) {
      var searchParams = '';
      if (searchString !== undefined) {
        searchParams = '?search=' + searchString;
      } else {
        vm.recipes = $rootScope.getRecipes(localUser);
        return;
      }
      dataService.get(recipesUrl + searchParams)
        .then(function(response) {
          vm.recipes = recipeService.cacheRecipes(response.data);
        });
    }

    /**
     * Update an existing public rating.
     */
    function updateRating(rating, ratingId, recipeId) {
      // Ensure that we only take this action on public recipes
      if (!vm.isPublic) {
        return;
      }
      var providedRating = {"public_rating": rating};
      dataService.patch(
        publicUrl + recipeId + '/ratings/' + ratingId + '/',
        providedRating);
    }
  }
})();
<|endoftext|>


<commit_before>const celsiusUnits = {
    metric: {
        label: '°C',
        convert: value => (value - 32) / 1.8,  // Convert to celsius
        convertTransfer: value => value / 1.8  // Convert difference to celsuis
    },
    imperial: {
        label: '°F',
        convert: value => value * 1.8 + 32,  // Convert to fahrenheit
        convertTransfer: value => value * 1.8 // Convert difference to fahrenheit
    }
}

const mmUnits = {
    metric: {
        label: 'mm',
        convert: value => value * 25.4 // Convert to millimeters
    },
    imperial: {
        label: 'in',
        convert: value => value / 25.4 // Convert to inches
    }
}

const daysUnits = {
    metric: {label: 'days', convert: null},
    imperial: {label: 'days', convert: null}
}

const degreeDaysUnits = {
    metric: {label: 'dd', convert: null},
    imperial: {label: 'dd', convert: null}
}

const nullUnits = {
    metric: {label: '', convert: null},
    imperial: {label: '', convert: null}
}

export const variables = [
    {
        name: 'MAT',
        label: 'Mean annual temperature',
        multiplier: 10,
        units: celsiusUnits
    },
    {
        name: 'MWMT',
        label: 'Mean warmest month temperature',
        multiplier: 10,
        units: celsiusUnits
    },
    {
        name: 'MCMT',
        label: 'Mean coldest month temperature',
        multiplier: 10,
        units: celsiusUnits
    },
    {
        name: 'TD',
        label: 'Temperature difference between MWMT and MCMT, or continentality',
        multiplier: 10,
        units: {
            metric: {
                label: '°C',
                convert: value => value / 1.8  // Convert temp difference to C
            },
            imperial: {
                label: '°F',
                convert: value => value * 1.8 // Convert temp difference to F
            }
        }
    },
    {
        name: 'MAP',
        label: 'Mean annual precipitation',
        multiplier: 1,
        units: mmUnits
    },
    {
        name: 'MSP',
        label: 'Mean summer precipitation, May to September',
        multiplier: 1,
        units: mmUnits
    },
    {
        name: 'AHM',
        label: 'Annual heat-moisture index',
        multiplier: 10,
        units: nullUnits
    },
    {
        name: 'SHM',
        label: 'Summer heat-moisture index',
        multiplier: 10,
        units: nullUnits
    },
    {
        name: 'DD_0',
        label: 'Degree-days below 0°C',
        multiplier: 1,
        units: degreeDaysUnits
    },
    {
        name: 'DD5',
        label: 'Degree-days above 5°C',
        multiplier: 1,
        units: degreeDaysUnits
    },
    {
        name: 'FFP',
        label: 'Frost-free period',
        multiplier: 1,
        units: daysUnits
    },
    {
        name: 'PAS',
        label: 'Precipitation as snow, August to July',
        multiplier: 1,
        units: mmUnits
    },
    {
        name: 'EMT',
        label: 'Extreme minimum temperature over 30 years',
        multiplier: 10,
        units: celsiusUnits
    },
    {
        name: 'EXT',
        label: 'Extreme maximum temperature over 30 years',
        multiplier: 10,
        units: celsiusUnits
    },
    {
        name: 'Eref',
        label: 'Hargreaves reference evaporation',
        multiplier: 1,
        units: mmUnits
    },
    {
        name: 'CMD',
        label: 'Hargreaves climatic moisture deficit',
        multiplier: 1,
        units: mmUnits
    }
];

export const species = [
    {
        name: 'psme',
        label: 'Douglas-fir',
        transfers: {
            MAT: 20,
            MWMT: 20,
            MCMT: 20,
            TD: 20,
            EMT: 20,
            EXT: 20,
            MAP: 200,
            MSP: 50,
            FFP: 20,
            AHM: 30,
            SHM: 20
        }
    },
    {
        name: 'pico',
        label: 'Lodgepole pine',
        transfers: {
            MAT: 20,
            MWMT: 20,
            MCMT: 20,
            TD: 20,
            EMT: 20,
            EXT: 20,
            MAP: 200,
            MSP: 50,
            FFP: 20,
            AHM: 30,
            SHM: 20
        }
    },
    {
        name: 'pipo',
        label: 'Ponderosa pine',
        transfers: {
            MAT: 25,
            MWMT: 25,
            MCMT: 25,
            TD: 25,
            EMT: 25,
            EXT: 25,
            MAP: 200,
            MSP: 50,
            FFP: 30,
            AHM: 30,
            SHM: 20
        }
    },
    {
        name: 'thpl',
        label: 'Western red cedar',
        transfers: {
            MAT: 30,
            MWMT: 30,
            MCMT: 30,
            TD: 30,
            EMT: 30,
            EXT: 30,
            MAP: 200,
            MSP: 50,
            FFP: 50,
            AHM: 30,
            SHM: 20
        }
    },
    {
        name: 'pimo',
        label: 'Western white pine',
        transfers: {
            MAT: 30,
            MWMT: 30,
            MCMT: 30,
            TD: 30,
            EMT: 30,
            EXT: 30,
            MAP: 200,
            MSP: 50,
            FFP: 50,
            AHM: 30,
            SHM: 20
        }
    }
]
<commit_msg>Fix unit conversion error<commit_after>const celsiusUnits = {
    metric: {
        label: '°C',
        convert: value => (value - 32) / 1.8,  // Convert to celsius
        convertTransfer: value => value / 1.8  // Convert difference to celsuis
    },
    imperial: {
        label: '°F',
        convert: value => value * 1.8 + 32,  // Convert to fahrenheit
        convertTransfer: value => value * 1.8 // Convert difference to fahrenheit
    }
}

const mmUnits = {
    metric: {
        label: 'mm',
        convert: value => value * 25.4 // Convert to millimeters
    },
    imperial: {
        label: 'in',
        convert: value => value / 25.4 // Convert to inches
    }
}

const daysUnits = {
    metric: {label: 'days', convert: value => value},
    imperial: {label: 'days', convert: value => value}
}

const degreeDaysUnits = {
    metric: {label: 'dd', convert: value => value},
    imperial: {label: 'dd', convert: value => value}
}

const nullUnits = {
    metric: {label: '', convert: value => value},
    imperial: {label: '', convert: value => value}
}

export const variables = [
    {
        name: 'MAT',
        label: 'Mean annual temperature',
        multiplier: 10,
        units: celsiusUnits
    },
    {
        name: 'MWMT',
        label: 'Mean warmest month temperature',
        multiplier: 10,
        units: celsiusUnits
    },
    {
        name: 'MCMT',
        label: 'Mean coldest month temperature',
        multiplier: 10,
        units: celsiusUnits
    },
    {
        name: 'TD',
        label: 'Temperature difference between MWMT and MCMT, or continentality',
        multiplier: 10,
        units: {
            metric: {
                label: '°C',
                convert: value => value / 1.8  // Convert temp difference to C
            },
            imperial: {
                label: '°F',
                convert: value => value * 1.8 // Convert temp difference to F
            }
        }
    },
    {
        name: 'MAP',
        label: 'Mean annual precipitation',
        multiplier: 1,
        units: mmUnits
    },
    {
        name: 'MSP',
        label: 'Mean summer precipitation, May to September',
        multiplier: 1,
        units: mmUnits
    },
    {
        name: 'AHM',
        label: 'Annual heat-moisture index',
        multiplier: 10,
        units: nullUnits
    },
    {
        name: 'SHM',
        label: 'Summer heat-moisture index',
        multiplier: 10,
        units: nullUnits
    },
    {
        name: 'DD_0',
        label: 'Degree-days below 0°C',
        multiplier: 1,
        units: degreeDaysUnits
    },
    {
        name: 'DD5',
        label: 'Degree-days above 5°C',
        multiplier: 1,
        units: degreeDaysUnits
    },
    {
        name: 'FFP',
        label: 'Frost-free period',
        multiplier: 1,
        units: daysUnits
    },
    {
        name: 'PAS',
        label: 'Precipitation as snow, August to July',
        multiplier: 1,
        units: mmUnits
    },
    {
        name: 'EMT',
        label: 'Extreme minimum temperature over 30 years',
        multiplier: 10,
        units: celsiusUnits
    },
    {
        name: 'EXT',
        label: 'Extreme maximum temperature over 30 years',
        multiplier: 10,
        units: celsiusUnits
    },
    {
        name: 'Eref',
        label: 'Hargreaves reference evaporation',
        multiplier: 1,
        units: mmUnits
    },
    {
        name: 'CMD',
        label: 'Hargreaves climatic moisture deficit',
        multiplier: 1,
        units: mmUnits
    }
];

export const species = [
    {
        name: 'psme',
        label: 'Douglas-fir',
        transfers: {
            MAT: 20,
            MWMT: 20,
            MCMT: 20,
            TD: 20,
            EMT: 20,
            EXT: 20,
            MAP: 200,
            MSP: 50,
            FFP: 20,
            AHM: 30,
            SHM: 20
        }
    },
    {
        name: 'pico',
        label: 'Lodgepole pine',
        transfers: {
            MAT: 20,
            MWMT: 20,
            MCMT: 20,
            TD: 20,
            EMT: 20,
            EXT: 20,
            MAP: 200,
            MSP: 50,
            FFP: 20,
            AHM: 30,
            SHM: 20
        }
    },
    {
        name: 'pipo',
        label: 'Ponderosa pine',
        transfers: {
            MAT: 25,
            MWMT: 25,
            MCMT: 25,
            TD: 25,
            EMT: 25,
            EXT: 25,
            MAP: 200,
            MSP: 50,
            FFP: 30,
            AHM: 30,
            SHM: 20
        }
    },
    {
        name: 'thpl',
        label: 'Western red cedar',
        transfers: {
            MAT: 30,
            MWMT: 30,
            MCMT: 30,
            TD: 30,
            EMT: 30,
            EXT: 30,
            MAP: 200,
            MSP: 50,
            FFP: 50,
            AHM: 30,
            SHM: 20
        }
    },
    {
        name: 'pimo',
        label: 'Western white pine',
        transfers: {
            MAT: 30,
            MWMT: 30,
            MCMT: 30,
            TD: 30,
            EMT: 30,
            EXT: 30,
            MAP: 200,
            MSP: 50,
            FFP: 50,
            AHM: 30,
            SHM: 20
        }
    }
]
<|endoftext|>


<commit_before>PseudoFile = function(){
    this.arr = [];
}
PseudoFile.prototype = {
    write: function(text){
        this.arr = text.split("\n");
    },
    append: function(line){
        this.arr.push(line);
    },
    read: function(){
        return this.arr.join("\n");
    },
    readLnAt: function(indice){
        return this.arr[indice];
    },
    readLnFrom: function(indice){
        return this.arr.slice(indice)
    },
    get length(){
        return this.arr.length;
    },
};

File = function(name){
    this.name = name
}
File.prototype = {
    write: function(text){
        localStorage.setItem(this.name, text);
    },
    append: function(text){
        this.write(this.read() + text);
    },
    read: function(){
        return localStorage.getItem(this.name);
    },
    readLnAt: function(indice){
        return this.read().split("\n")[indice];
    },
    readLnFrom: function(indice){
        return this.read().split("\n").slice(indice);
    },
    get length(){
        return (this.read().match(/\n/g) || []).length
    },
};
function In(stream, end){
    this.stream = stream;
    this.index = 0;
    this.depth = 0;
    this.end = end
    this.killer = null;
}
In.prototype = {
    wrap: function(callback){
        var self = this;
        return function(line){
            if(self.end){
                try{
                    callback(line);
                }catch(e){
                    self.end(e);
                }
            }else{
                callback(line)
            }
        }
    },
    readln: function(callback){
        if(this.killer){
            throw this.killer
        }
        if(this.index < this.stream.lines.length){
            this.index ++;
            this.wrap(callback)(this.stream.lines.readLnAt(this.index-1));
        }
        else{
            this.index ++;
            this.stream.line_listener.push(this.wrap(callback));
        }
    },
    read: function(callback){
        if(this.killer){
            throw this.killer
        }
        if(this.index < this.stream.lines.length || this.depth < this.stream.line.length ){
            prevind = this.index;
            prevdepth = this.depth;
            this.index = this.stream.lines.length;
            this.depth = this.stream.line.length;
            this.wrap(callback)(this.stream.lines.readLnFrom(prevind).join("\n") + "\n" + this.stream.line.slice(prevdepth));
        }
        else{
            this.index = this.stream.lines.length;
            this.depth = this.stream.line.length;
            this.stream.listener.push(this.wrap(callback));
        }
    },
    kill: function(error){
        this.killer = error;
    },
};
function Stream(){
    this.lines = new PseudoFile();
    this.line = "";
    this.line_listener = [];
    this.listener = [];

};
Stream.prototype = {
    write: function(text){
        var lines = text.split("\n")
        for(var i = 0; i < lines.length-1; i++){
            this.line += lines[i]
            this.endln()
        }
        this.line += lines[lines.length-1]
        var callbacks = this.listener;
        this.listener = [];
        for(var i = 0; i < callbacks.length; i++){
            callbacks[i](text)
        }
    },
    writeln: function(text){
        this.write(text+"\n")
    },
    endln: function(){
        var line_listener = this.line_listener;
        this.line_listener = [];
        for(var i = 0; i < line_listener.length; i++){
            line_listener[i](this.line);
        }
        this.lines.append(this.line)
        this.line = "";
    },
    reader: function(end){
        return new In(this, end);
    },
};
function FileStream(filename){
    Stream.call(this);
    this.lines = new File(filename);
}
FileStream.prototype = Object.create(Stream.prototype)
<commit_msg>simple file system<commit_after>File = function(name){
    this.name = name
}
File.prototype = {
    write: function(text){
        localStorage.setItem(this.name, text);
    },
    append: function(text){
        var old = this.read();
        this.write((old?old:"") + text);
    },
    read: function(){
        return localStorage.getItem(this.name);
    },
    readLnAt: function(indice){
        return this.read().split("\n")[indice];
    },
    readLnFrom: function(indice){
        return this.read().split("\n").slice(indice);
    },
    get length(){
        return (this.read().match(/\n/g) || []).length
    },
};
dirs = {
    valid: function(path){
        return path[0] === "/" && localStorage.getItem(path) !== null
    },
    validDir: function(path){
        return this.valid(path) && path[path.length-1] === "/"
    },
    validFile: function(path){
        return this.valid(path) && path[path.length-1] !== "/"
    },
    parent: function(path){
        if(path[path.length-1] === "/")
            path = path.slice(0, -1);
        return path.slice(0, path.lastIndexOf("/"))
    },
    get: function(path){
        if(valid(path)){
            return new File(path)
        }else{
            throw new Error("File or Directory at '"+path+"' does not exist");
        }
    },
    _add: function(parent, name){
        if(parent[parent.length-1] === "/" && this.valid(parent)){
            (new File(parent)).append("\n"+name);
            var f = new File(parent + name);
            f.append("");
            return f;
        }else{
            throw new Error("Directory '"+parent+"' does not exist");
        }
    },
    addDir: function(parent, name){
        if(name.indexOf("/") === name.length-1){
            return this._add(parent, name);
        }else{
            throw new Error("Invalid directory name '"+ name + "'");
        }
    },
    addFile: function(parent, name){
        if(name.indexOf("/") === -1){
            return this._add(parent, name);
        }else{
            throw new Error("Invalid file name '"+ name + "'");
        }
    },
    navigate(orig, path){
        var final;
        if(path[0] === "/")
            final = path;
        else if(path[0] !== ".")
            final = orig + path;
        else if(path === ".")
            final = orig;
        else if(path.slice(0, 2) === "./")
            final = orig + path.slice(2);
        else if(path === "..")
            final = this.parent(orig);
        else if(path.slice(0, 3) === "../")
            final = this.navigate(this.parent(orig), path.slice(3))
        if(this.valid(final)){
            return final;
        }
        throw Error("invalid path '" + final + "' from '"+orig+"'+'"+path+"'");
    },
}
new File("/").append("");
window.process = window.process?window.process:{};
window.environment = window.environment?window.environment:{};
environment.CWD = "/" // no user folders or other files, no need for home directory.
process.cd = function(args, io){
    var path = "/";
    if(args[1]){
        path = dirs.navigate(environment.CWD, args[1]);
    }
    environment.CWD = path;
}
PseudoFile = function(){
    this.arr = [];
}
PseudoFile.prototype = {
    write: function(text){
        this.arr = text.split("\n");
    },
    append: function(line){
        this.arr.push(line);
    },
    read: function(){
        return this.arr.join("\n");
    },
    readLnAt: function(indice){
        return this.arr[indice];
    },
    readLnFrom: function(indice){
        return this.arr.slice(indice)
    },
    get length(){
        return this.arr.length;
    },
};

function In(stream, end){
    this.stream = stream;
    this.index = 0;
    this.depth = 0;
    this.end = end
    this.killer = null;
}
In.prototype = {
    wrap: function(callback){
        var self = this;
        return function(line){
            if(self.end){
                try{
                    callback(line);
                }catch(e){
                    self.end(e);
                }
            }else{
                callback(line)
            }
        }
    },
    readln: function(callback){
        if(this.killer){
            throw this.killer
        }
        if(this.index < this.stream.lines.length){
            this.index ++;
            this.wrap(callback)(this.stream.lines.readLnAt(this.index-1));
        }
        else{
            this.index ++;
            this.stream.line_listener.push(this.wrap(callback));
        }
    },
    read: function(callback){
        if(this.killer){
            throw this.killer
        }
        if(this.index < this.stream.lines.length || this.depth < this.stream.line.length ){
            prevind = this.index;
            prevdepth = this.depth;
            this.index = this.stream.lines.length;
            this.depth = this.stream.line.length;
            this.wrap(callback)(this.stream.lines.readLnFrom(prevind).join("\n") + "\n" + this.stream.line.slice(prevdepth));
        }
        else{
            this.index = this.stream.lines.length;
            this.depth = this.stream.line.length;
            this.stream.listener.push(this.wrap(callback));
        }
    },
    kill: function(error){
        this.killer = error;
    },
};
function Stream(){
    this.lines = new PseudoFile();
    this.line = "";
    this.line_listener = [];
    this.listener = [];

};
Stream.prototype = {
    write: function(text){
        var lines = text.split("\n")
        for(var i = 0; i < lines.length-1; i++){
            this.line += lines[i]
            this.endln()
        }
        this.line += lines[lines.length-1]
        var callbacks = this.listener;
        this.listener = [];
        for(var i = 0; i < callbacks.length; i++){
            callbacks[i](text)
        }
    },
    writeln: function(text){
        this.write(text+"\n")
    },
    endln: function(){
        var line_listener = this.line_listener;
        this.line_listener = [];
        for(var i = 0; i < line_listener.length; i++){
            line_listener[i](this.line);
        }
        this.lines.append(this.line)
        this.line = "";
    },
    reader: function(end){
        return new In(this, end);
    },
};
function FileStream(filename){
    Stream.call(this);
    this.lines = new File(filename);
}
FileStream.prototype = Object.create(Stream.prototype)
<|endoftext|>


<commit_before>var io;
var rooms = {};
var sockets = {};

function RoomManager (server) {
	var that = this;
	io = require('socket.io')(server);

	var lobbyCon = io.of('/lobby');
	lobbyCon.on('connection', function (socket) {
		socket.emit('lobby.state', rooms);
	});

	var that = this;
	this.connections = {};
	var playerId = 0;

	var roomCon = io.of('/game');
	roomCon.on('connection', function (socket) {
		var Player = require('./player');
		var player = null;
		var roomId;
		var thisPlayerId = playerId;

		socket.on('player.join', function (data) {
			roomId = data.roomId;
			socket.join(roomId);
			if (!rooms[roomId]) {
				rooms[roomId] = {};
			}
			player = new Player(data.name, roomId, thisPlayerId, socket, socket.id);
			rooms[roomId][thisPlayerId] = player.getState();
			sockets[thisPlayerId] = socket;
			socket.emit('player.connected.self', player.getState());
			socket.broadcast.to(roomId).emit('player.connected.new', player.getState());
			lobbyCon.emit('lobby.state', rooms);
		});

		socket.on('disconnect', function () {
			socket.broadcast.to(roomId).emit('player.disconnected', player.getState());
			var room = rooms[player.roomId];
			delete room[player.playerId];
			delete sockets[player.playerId];
			if (Object.keys(room).length === 0) {
				delete rooms[player.roomId];
			}
			lobbyCon.emit('lobby.state', rooms);
		});

		socket.on('player.update', function (data) {
			/*// Update the server game state
			var room = rooms[roomId];
			var myId = data.playerId;
			if (room[myId] != undefined) {
				room[myId].gameState = data;
			}

			for (playerId in room) {
				if (playerId != myId) {
					var forward = false;

					// Simple distance calculation
					var distance = 0;
					if (room[myId].gameState != null && room[playerId].gameState != null) {
						Math.abs (room[myId].gameState.x - room[playerId].gameState.x) + Math.abs (room[myId].gameState.y - room[playerId].gameState.y);
					}

					if (distance < 5 * 1000) {
						// Close enough! Send everything
						forward = true;

					} else if (distance < 10 * 1000) {
						// Quite far away, not interested
						// But might still be visible in large screen

						// 30% chance to discard all optional fields
						// Effectively reduce package size
						var discardChance = Math.random () < 0.3;
						if (discardChance) {
							delete data.vx;
							delete data.vy;
							delete data.landed;
							delete data.onLadder;
							delete data.ducked;
						}

						// Only forward 70% of the package
						var forwardChance = Math.random () < 0.7;
						forward = true;

					} else {
						// Super far away, definitely not interested

						// Don't even bother sending optional fields
						delete data.vx;
						delete data.vy;
						delete data.landed;
						delete data.onLadder;
						delete data.ducked;

						// Only forward 40% of the package
						var forwardChance = Math.random () < 0.4;
						forward = true;
					}

					// Forward the package to the recipient
					if (true) {
						sockets[playerId].emit ('player.updated', data);
					}
				}
			}*/

			// Boardcast to all player in room
			/*socket.broadcast.to(roomId).emit('player.updated', data);*/

			var room = rooms[roomId];
			for (playerId in room) {
				if (playerId != data.playerId) {
					console.log (data.playerId + " move event to " + playerId);
					sockets[playerId].emit('player.updated', data);
				}
			}
		});

		socket.on('player.shoot', function (data) {
			data.latency = player.latency;
			/*socket.broadcast.to(roomId).emit('player.shoot', data);*/

			var room = rooms[roomId];
			for (playerId in room) {
				if (playerId != data.playerId) {
					console.log (data.playerId + " shoot event to " + playerId);
					sockets[playerId].emit('player.shoot', data);
				}
			}
		});

		playerId++;
	});
}

module.exports = RoomManager;
<commit_msg>boardcast in player.updated but multi multicast in player.shoot<commit_after>var io;
var rooms = {};
var sockets = {};

function RoomManager (server) {
	var that = this;
	io = require('socket.io')(server);

	var lobbyCon = io.of('/lobby');
	lobbyCon.on('connection', function (socket) {
		socket.emit('lobby.state', rooms);
	});

	var that = this;
	this.connections = {};
	var playerId = 0;

	var roomCon = io.of('/game');
	roomCon.on('connection', function (socket) {
		var Player = require('./player');
		var player = null;
		var roomId;
		var thisPlayerId = playerId;

		socket.on('player.join', function (data) {
			roomId = data.roomId;
			socket.join(roomId);
			if (!rooms[roomId]) {
				rooms[roomId] = {};
			}
			player = new Player(data.name, roomId, thisPlayerId, socket, socket.id);
			rooms[roomId][thisPlayerId] = player.getState();
			sockets[thisPlayerId] = socket;
			socket.emit('player.connected.self', player.getState());
			socket.broadcast.to(roomId).emit('player.connected.new', player.getState());
			lobbyCon.emit('lobby.state', rooms);
		});

		socket.on('disconnect', function () {
			socket.broadcast.to(roomId).emit('player.disconnected', player.getState());
			var room = rooms[player.roomId];
			delete room[player.playerId];
			delete sockets[player.playerId];
			if (Object.keys(room).length === 0) {
				delete rooms[player.roomId];
			}
			lobbyCon.emit('lobby.state', rooms);
		});

		socket.on('player.update', function (data) {
			/*// Update the server game state
			var room = rooms[roomId];
			var myId = data.playerId;
			if (room[myId] != undefined) {
				room[myId].gameState = data;
			}

			for (playerId in room) {
				if (playerId != myId) {
					var forward = false;

					// Simple distance calculation
					var distance = 0;
					if (room[myId].gameState != null && room[playerId].gameState != null) {
						Math.abs (room[myId].gameState.x - room[playerId].gameState.x) + Math.abs (room[myId].gameState.y - room[playerId].gameState.y);
					}

					if (distance < 5 * 1000) {
						// Close enough! Send everything
						forward = true;

					} else if (distance < 10 * 1000) {
						// Quite far away, not interested
						// But might still be visible in large screen

						// 30% chance to discard all optional fields
						// Effectively reduce package size
						var discardChance = Math.random () < 0.3;
						if (discardChance) {
							delete data.vx;
							delete data.vy;
							delete data.landed;
							delete data.onLadder;
							delete data.ducked;
						}

						// Only forward 70% of the package
						var forwardChance = Math.random () < 0.7;
						forward = true;

					} else {
						// Super far away, definitely not interested

						// Don't even bother sending optional fields
						delete data.vx;
						delete data.vy;
						delete data.landed;
						delete data.onLadder;
						delete data.ducked;

						// Only forward 40% of the package
						var forwardChance = Math.random () < 0.4;
						forward = true;
					}

					// Forward the package to the recipient
					if (true) {
						sockets[playerId].emit ('player.updated', data);
					}
				}
			}*/

			// Boardcast to all player in room
			socket.broadcast.to(roomId).emit('player.updated', data);
		});

		socket.on('player.shoot', function (data) {
			data.latency = player.latency;
			/*socket.broadcast.to(roomId).emit('player.shoot', data);*/

			var room = rooms[roomId];
			for (playerId in room) {
				if (playerId != data.playerId) {
					console.log (data.playerId + " shoot event to " + playerId);
					sockets[playerId].emit('player.shoot', data);
				}
			}
		});

		playerId++;
	});
}

module.exports = RoomManager;
<|endoftext|>


<commit_before>function deleteRow(row)
{
// Delete selected row
    var i=row.parentNode.parentNode.rowIndex;
    document.getElementById('irisTable').deleteRow(i);
}

function checkTime(i)
{
    if (i < 10){
        i = "0"+i;
    }
    return i;
}

function findend(row)
{
//Used start time, exp time and number of exps to find the approximate end time for the observation
    var i = row.parentNode.id.split('-')[1]

//grab values from the HTML file
    var statime = document.getElementById("1-"+i+"-statimerow").children[0].value;//document.getElementById('1-'+i+'-statimebox').value;
    var exptime = parseFloat(document.getElementById('1-'+i+'-exptimerow').children[0].value);
    var repeats = parseFloat(document.getElementById('1-'+i+'-repeatsrow').children[0].value);

//break the start time into HH,MM,SS
    var arstime = statime.split(":")

//Just use current date to set up a day to operate on
//really just a dummy variable
    var currentDate = new Date();
    currentDate.setDate(currentDate.getDate() + 1);
    var dd = currentDate.getDate();
    var mm = currentDate.getMonth()+1;
    var yy = currentDate.getYear();

    mm = checkTime(mm)
    dd = checkTime(dd)

    var date = new Date(yy,mm,dd,arstime[0],arstime[1],arstime[2])

    var addsec = exptime*repeats
// Add exposure time to start time
    date.setSeconds(date.getSeconds()+addsec);
// Add slew time (Assume slow)
    var addslew = 11 //min
    date.setMinutes(date.getMinutes()+addslew)

//split endtime into a string variable
    var endHour = checkTime(date.getHours()) + ':' + checkTime(date.getMinutes())+ ":" + checkTime(date.getSeconds());

// update endtime
    document.getElementById('1-'+i+'-endtimebox').innerHTML = endHour;

}

//fixes issue with wrong ids for rows
var idInit = 1;

function duplicateRow(row){

//copy based of  the row clicked
	var j = row.parentNode.id.split('-')[1]
//Create a duplicated of the last row created
    var table = document.getElementById("irisTable"); // find table to append to
    var row   = document.getElementById('1-'+j+'-samplerow');
    var newRow = row.cloneNode(true); // Clone the row

    incrementId(newRow); // Increment the row's ID
    var cells = newRow.cells;
    for(var i = 0; i < cells.length; i++){
        incrementId(cells[i]); // Increment the cells' IDs
    }
    insertAfter(row, newRow); // Insert the row at the right position
    idInit++;

}

function incrementId(elem){

//Change ids of cell to increment by 1
    idParts = elem.id.split('-'); // Cut up the element's ID to get the second part.

    idInit ? idParts[1] = idInit + 1 : idInit = idParts[1]++;  // Increment the ID, and set a temp variable to keep track of the id's.

    elem.id = idParts.join('-'); // Set the new id to the element.
// change id of input box (does not work)
    elem.children.id = elem.id.replace('row','box')

}

function insertAfter(after, newNode){
//Insert new row at bottom
    after.parentNode.insertBefore(newNode, after.nextSibling);
}
<commit_msg>Updated slew time to 8 minutes instead of 11<commit_after>function deleteRow(row)
{
// Delete selected row
    var i=row.parentNode.parentNode.rowIndex;
    document.getElementById('irisTable').deleteRow(i);
}

function checkTime(i)
{
    if (i < 10){
        i = "0"+i;
    }
    return i;
}

function findend(row)
{
//Used start time, exp time and number of exps to find the approximate end time for the observation
    var i = row.parentNode.id.split('-')[1]

//grab values from the HTML file
    var statime = document.getElementById("1-"+i+"-statimerow").children[0].value;//document.getElementById('1-'+i+'-statimebox').value;
    var exptime = parseFloat(document.getElementById('1-'+i+'-exptimerow').children[0].value);
    var repeats = parseFloat(document.getElementById('1-'+i+'-repeatsrow').children[0].value);

//break the start time into HH,MM,SS
    var arstime = statime.split(":")

//Just use current date to set up a day to operate on
//really just a dummy variable
    var currentDate = new Date();
    currentDate.setDate(currentDate.getDate() + 1);
    var dd = currentDate.getDate();
    var mm = currentDate.getMonth()+1;
    var yy = currentDate.getYear();

    mm = checkTime(mm)
    dd = checkTime(dd)

    var date = new Date(yy,mm,dd,arstime[0],arstime[1],arstime[2])

    var addsec = exptime*repeats
// Add exposure time to start time
    date.setSeconds(date.getSeconds()+addsec);
// Add slew time (Assume slow)
    var addslew = 8 //min
    date.setMinutes(date.getMinutes()+addslew)

//split endtime into a string variable
    var endHour = checkTime(date.getHours()) + ':' + checkTime(date.getMinutes())+ ":" + checkTime(date.getSeconds());

// update endtime
    document.getElementById('1-'+i+'-endtimebox').innerHTML = endHour;

}

//fixes issue with wrong ids for rows
var idInit = 1;

function duplicateRow(row){

//copy based of  the row clicked
	var j = row.parentNode.id.split('-')[1]
//Create a duplicated of the last row created
    var table = document.getElementById("irisTable"); // find table to append to
    var row   = document.getElementById('1-'+j+'-samplerow');
    var newRow = row.cloneNode(true); // Clone the row

    incrementId(newRow); // Increment the row's ID
    var cells = newRow.cells;
    for(var i = 0; i < cells.length; i++){
        incrementId(cells[i]); // Increment the cells' IDs
    }
    insertAfter(row, newRow); // Insert the row at the right position
    idInit++;

}

function incrementId(elem){

//Change ids of cell to increment by 1
    idParts = elem.id.split('-'); // Cut up the element's ID to get the second part.

    idInit ? idParts[1] = idInit + 1 : idInit = idParts[1]++;  // Increment the ID, and set a temp variable to keep track of the id's.

    elem.id = idParts.join('-'); // Set the new id to the element.
// change id of input box (does not work)
    elem.children.id = elem.id.replace('row','box')

}

function insertAfter(after, newNode){
//Insert new row at bottom
    after.parentNode.insertBefore(newNode, after.nextSibling);
}
<|endoftext|>


<commit_before>const Result = require('../results/Result.js');
const PermissionUtil = require('../utility/PermissionUtil.js');
const CommandError = require('../enums/CommandError.js');

class Constants {
  constructor() {
    this.config = {
      maxMatches: 5
    };

    this.conversions = {
      secondInMs: 1000,
      minuteInMs: 60000,
      hourInMs: 3600000,
      dayInMs: 86400000,
      weekInMs: 604800000,
      monthInMs: 2592000000,
      yearInMs: 31536000000,
      decadeInMs: 315360000000,
      centuryInMs: 3153600000000
    };

    this.errors = {
      bannedUserNotFound: 'Banned user not found.',
      channelNotFound: 'Channel not found.',
      emojiNotFound: 'Emoji not found.',
      dmChannelNotFound: 'DM channel not found.',
      guildChannelNotFound: 'Guild channel not found.',
      guildEmojiNotFound: 'Guild emoji not found.',
      guildNotFound: 'Guild not found.',
      groupChannelNotFound: 'Group channel not found.',
      invalidArg: (argument) => 'You have provided an invalid ' + argument.name + '.',
      memberNotFound: 'Member not found.',
      messageNotFound: 'Message not found.',
      multipleMatches: (matches) => 'Multiple matches found: ' + matches + '.',
      roleNotFound: 'Role not found.',
      textChannelNotFound: 'Text channel not found.',
      tooManyMatches: 'Multiple matches found, please be more specific.',
      userNotFound: 'User not found.',
      voiceChannelNotFound: 'Voice channel not found.'
    };

    this.numbers = {
      thousand: 1000,
      million: 1000000,
      billion: 1000000000
    };

    this.regexes = {
      argument: /"[\S\s]+?"|[\S\n]+/g,
      billion: /b\$?$/i,
      centuries: /^(\d+(\.\d+)?|\.\d+)\s*(cen(tur(y|ies))?)$/i,
      days: /^(\d+(\.\d+)?|\.\d+)\s*(days?|d)$/i,
      decades: /^(\d+(\.\d+)?|\.\d+)\s*(dec(ade)?s?)$/i,
      emoji: /^<:.+:\d+>/,
      excludeDir: /^\./,
      filter: /^([^.].*)\.js(on)?$/,
      hours: /^(\d+(\.\d+)?|\.\d+)\s*(hours?|h)$/i,
      id: /^\d{17,19}/,
      million: /m\$?$/i,
      milliseconds: /^(\d+(\.\d+)?|\.\d+)\s*(milliseconds?|ms)$/i,
      minutes: /^(\d+(\.\d+)?|\.\d+)\s*(min(ute)?s?|m)$/i,
      months: /^(\d+(\.\d+)?|\.\d+)\s*months?$/i,
      findId: /\d{17,19}/,
      quotes: /^"|"$/g,
      quotesMatch: /^"[\S\s]+"$/,
      roleMention: /^<@&\d+>/,
      seconds: /^(\d+(\.\d+)?|\.\d+)\s*(sec(onds)?s?|s)$/i,
      textChannelMention: /^<#\d+>/,
      thousand: /k\$?$/i,
      usernameAndDiscrim: /.+#\d{4}/,
      userMention: /^<@!?\d+>/,
      weeks: /^(\d+(\.\d+)?|\.\d+)\s*(weeks?|w)$/i,
      whiteSpace: /\s/,
      years: /^(\d+(\.\d+)?|\.\d+)\s*(years?|y)$/i
    };

    this.results = {
      botPermissions: (client, command, permissions) => new Result({ success: false, command: command, commandError: CommandError.botPermission, errorReason: client.user.username + ' cannot execute this command without the ' + PermissionUtil.format(permissions) + ' permission' + (permissions.length > 1 ? 's' : '') + '.' }),
      commandNotFound: (commandName) => new Result({ success: false, commandName: commandName, commandError: CommandError.CommandNotFound, errorReason: 'This command does not exist.' }),
      dmOnly: (command) => new Result({ success: false, command: command, commandError: CommandError.DmOnly, errorReason: 'This command may only be used in direct messages.' }),
      guildOnly: (command) => new Result({ success: false, command: command, commandError: CommandError.GuildOnly, errorReason: 'This command may only be used inside a server.' }),
      invalidArgCount: (command) => new Result({ success: false, command: command, commandError: CommandError.InvalidArgCount, errorReason: 'You have provided an invalid number of arguments.' }),
      memberPermissions: (command, permissions) => new Result({ success: false, command: command, commandError: CommandError.memberPermission, errorReason: 'This command may only be used by members with the ' + permissions + ' permission' + (permissions.length > 1 ? 's' : '') + '.' }),
      success: (command) => new Result({ success: true, command: command })
    };

    this.trueValues = [
      'y',
      'yes',
      'yup',
      'yea',
      'yeah',
      'true'
    ];

    this.falseValues = [
      'n',
      'no',
      'nope',
      'na',
      'nah',
      'false'
    ];

    this.libraries = [
      'discord.js',
      'eris'
    ];
  }
}

module.exports = new Constants();
<commit_msg>#eljaythebugcatcher ammirite WUBBA LUBBA DUB DUB<commit_after>const Result = require('../results/Result.js');
const PermissionUtil = require('../utility/PermissionUtil.js');
const CommandError = require('../enums/CommandError.js');

class Constants {
  constructor() {
    this.config = {
      maxMatches: 5
    };

    this.conversions = {
      secondInMs: 1000,
      minuteInMs: 60000,
      hourInMs: 3600000,
      dayInMs: 86400000,
      weekInMs: 604800000,
      monthInMs: 2592000000,
      yearInMs: 31536000000,
      decadeInMs: 315360000000,
      centuryInMs: 3153600000000
    };

    this.errors = {
      bannedUserNotFound: 'Banned user not found.',
      channelNotFound: 'Channel not found.',
      emojiNotFound: 'Emoji not found.',
      dmChannelNotFound: 'DM channel not found.',
      guildChannelNotFound: 'Guild channel not found.',
      guildEmojiNotFound: 'Guild emoji not found.',
      guildNotFound: 'Guild not found.',
      groupChannelNotFound: 'Group channel not found.',
      invalidArg: (argument) => 'You have provided an invalid ' + argument.name + '.',
      memberNotFound: 'Member not found.',
      messageNotFound: 'Message not found.',
      multipleMatches: (matches) => 'Multiple matches found: ' + matches + '.',
      roleNotFound: 'Role not found.',
      textChannelNotFound: 'Text channel not found.',
      tooManyMatches: 'Multiple matches found, please be more specific.',
      userNotFound: 'User not found.',
      voiceChannelNotFound: 'Voice channel not found.'
    };

    this.numbers = {
      thousand: 1000,
      million: 1000000,
      billion: 1000000000
    };

    this.regexes = {
      argument: /"[\S\s]+?"|[\S\n]+/g,
      billion: /b\$?$/i,
      centuries: /^(\d+(\.\d+)?|\.\d+)\s*(cen(tur(y|ies))?)$/i,
      days: /^(\d+(\.\d+)?|\.\d+)\s*(days?|d)$/i,
      decades: /^(\d+(\.\d+)?|\.\d+)\s*(dec(ade)?s?)$/i,
      emoji: /^<:.+:\d+>/,
      excludeDir: /^\./,
      filter: /^([^.].*)\.js(on)?$/,
      hours: /^(\d+(\.\d+)?|\.\d+)\s*(hours?|h)$/i,
      id: /^\d{17,19}/,
      million: /m\$?$/i,
      milliseconds: /^(\d+(\.\d+)?|\.\d+)\s*(milliseconds?|ms)$/i,
      minutes: /^(\d+(\.\d+)?|\.\d+)\s*(min(ute)?s?|m)$/i,
      months: /^(\d+(\.\d+)?|\.\d+)\s*months?$/i,
      findId: /\d{17,19}/,
      quotes: /^"|"$/g,
      quotesMatch: /^"[\S\s]+"$/,
      roleMention: /^<@&\d+>/,
      seconds: /^(\d+(\.\d+)?|\.\d+)\s*(sec(onds)?s?|s)$/i,
      textChannelMention: /^<#\d+>/,
      thousand: /k\$?$/i,
      usernameAndDiscrim: /.+#\d{4}/,
      userMention: /^<@!?\d+>/,
      weeks: /^(\d+(\.\d+)?|\.\d+)\s*(weeks?|w)$/i,
      whiteSpace: /\s/,
      years: /^(\d+(\.\d+)?|\.\d+)\s*(years?|y)$/i
    };

    this.results = {
      botPermissions: (client, command, permissions) => new Result({ success: false, command: command, commandError: CommandError.BotPermission, errorReason: client.user.username + ' cannot execute this command without the ' + PermissionUtil.format(permissions) + ' permission' + (permissions.length > 1 ? 's' : '') + '.' }),
      commandNotFound: (commandName) => new Result({ success: false, commandName: commandName, commandError: CommandError.CommandNotFound, errorReason: 'This command does not exist.' }),
      dmOnly: (command) => new Result({ success: false, command: command, commandError: CommandError.DmOnly, errorReason: 'This command may only be used in direct messages.' }),
      guildOnly: (command) => new Result({ success: false, command: command, commandError: CommandError.GuildOnly, errorReason: 'This command may only be used inside a server.' }),
      invalidArgCount: (command) => new Result({ success: false, command: command, commandError: CommandError.InvalidArgCount, errorReason: 'You have provided an invalid number of arguments.' }),
      memberPermissions: (command, permissions) => new Result({ success: false, command: command, commandError: CommandError.MemberPermission, errorReason: 'This command may only be used by members with the ' + permissions + ' permission' + (permissions.length > 1 ? 's' : '') + '.' }),
      success: (command) => new Result({ success: true, command: command })
    };

    this.trueValues = [
      'y',
      'yes',
      'yup',
      'yea',
      'yeah',
      'true'
    ];

    this.falseValues = [
      'n',
      'no',
      'nope',
      'na',
      'nah',
      'false'
    ];

    this.libraries = [
      'discord.js',
      'eris'
    ];
  }
}

module.exports = new Constants();
<|endoftext|>


<commit_before>// test/queryController.tests.js
var assert = require('assert'),
    express = require('express'),
    app = express(),
    request = require('supertest'),
    proxyquire = require('proxyquire'),
    eventStoreStub = {},
    controller = proxyquire('../../api/queryController', { 'eventStore': eventStoreStub });

controller.init(app);

describe('queryController', function() {
    describe('when I issue a workitem query for an asset that has no associated commits', function() {
        eventStoreStub.getLastAssets = function(args, callback) {
            callback(null, undefined);
        };

        it('returns a 200 OK response with an empty commits array', function(done) {
            //exercise our api
            request(app)
                .get('/api/query?workitem=123&pageSize=5')
                .end(function(err, res) {
                    assert.equal(err, null);
                    assert.equal(res.statusCode, 200);
                    assert.deepEqual(res.body.commits, []);
                    done();
                });
        });
    });
    describe('when I issue a query without a wrokitem as a parameter', function () {
        it('returns a 400 Bad Request response with a error message', function (done){
            request(app)
            .get('/api/query')
            .end(function (err, res) {
                    assert.equal(err, null);
                    assert.equal(res.statusCode, 400);
                    assert.equal(res.body.error, 'Parameter workitem is required');
                    done();
            });
        });
    });
});<commit_msg>D-08835 miss typed<commit_after>// test/queryController.tests.js
var assert = require('assert'),
    express = require('express'),
    app = express(),
    request = require('supertest'),
    proxyquire = require('proxyquire'),
    eventStoreStub = {},
    controller = proxyquire('../../api/queryController', { 'eventStore': eventStoreStub });

controller.init(app);

describe('queryController', function() {
    describe('when I issue a workitem query for an asset that has no associated commits', function() {
        eventStoreStub.getLastAssets = function(args, callback) {
            callback(null, undefined);
        };

        it('returns a 200 OK response with an empty commits array', function(done) {
            //exercise our api
            request(app)
                .get('/api/query?workitem=123&pageSize=5')
                .end(function(err, res) {
                    assert.equal(err, null);
                    assert.equal(res.statusCode, 200);
                    assert.deepEqual(res.body.commits, []);
                    done();
                });
        });
    });
    describe('when I issue a query without a workitem as a parameter', function () {
        it('returns a 400 Bad Request response with a error message', function (done){
            request(app)
            .get('/api/query')
            .end(function (err, res) {
                    assert.equal(err, null);
                    assert.equal(res.statusCode, 400);
                    assert.equal(res.body.error, 'Parameter workitem is required');
                    done();
            });
        });
    });
});<|endoftext|>


<commit_before>var exec = require('child_process').exec;
var fs = require('fs');
var status = require('./status');

function sendImage(response, filename){
  console.log(filename);
  fs.stat(filename, function(error, stat) {
    var rs;
    response.writeHead(200, {
      'Content-Type' : 'image/jpeg',
      'Content-Length' : stat.size
    });
    rs = fs.createReadStream(filename);
    console.log('about to pump file');
    rs.pipe(response);
  });
};

function takeStill(response){
  // take a still photo and send it back in the response
  var date = new Date()
  var filename = (date.getMonth() + 1) + '-' + date.getDate() + '-' + date.getFullYear() + '-' + date.getTime() + '.jpg';
  exec('raspistill -vf -t 0 -e jpg -q 75 -n -o ' + filename, function (error, stdout, stderr) {
    if (error === null) {
      fs.exists(filename, function(exists){
        if (exists) {
          console.log('about to send image');
          sendImage(response, filename);
        } else {
          status.notFound(response);
        }
      });
    } else {
      status.serverError(response);
    }
  });
};

function staticImage(response){
  var filename = 'testimg.jpg';
  fs.exists(filename, function(exists){
    if (exists) {
      console.log('about to send image');
      sendImage(response, filename);
    } else {
      status.notFound(response);
    }
  });
};

module.exports.takeStill = takeStill;
module.exports.staticImage = staticImage;
<commit_msg>removed -n option cause it breaks stuff<commit_after>var exec = require('child_process').exec;
var fs = require('fs');
var status = require('./status');

function sendImage(response, filename){
  console.log(filename);
  fs.stat(filename, function(error, stat) {
    var rs;
    response.writeHead(200, {
      'Content-Type' : 'image/jpeg',
      'Content-Length' : stat.size
    });
    rs = fs.createReadStream(filename);
    console.log('about to pump file');
    rs.pipe(response);
  });
};

function takeStill(response){
  // take a still photo and send it back in the response
  var date = new Date()
  var filename = (date.getMonth() + 1) + '-' + date.getDate() + '-' + date.getFullYear() + '-' + date.getTime() + '.jpg';
  exec('raspistill -vf -t 0 -e jpg -q 75 -o ' + filename, function (error, stdout, stderr) {
    if (error === null) {
      fs.exists(filename, function(exists){
        if (exists) {
          console.log('about to send image');
          sendImage(response, filename);
        } else {
          status.notFound(response);
        }
      });
    } else {
      status.serverError(response);
    }
  });
};

function staticImage(response){
  var filename = 'testimg.jpg';
  fs.exists(filename, function(exists){
    if (exists) {
      console.log('about to send image');
      sendImage(response, filename);
    } else {
      status.notFound(response);
    }
  });
};

module.exports.takeStill = takeStill;
module.exports.staticImage = staticImage;
<|endoftext|>


<commit_before>/*
 * grunt-dev-prod-switch
 * https://github.com/sanusart/grunt-dev-prod-switch
 *
 * Copyright (c) 2013 Sasha Khamkov
 * Licensed under the MIT license.
 */

'use strict';

module.exports = function (grunt) {

    // Please see the Grunt documentation for more information regarding task
    // creation: http://gruntjs.com/creating-tasks

    grunt.registerMultiTask('dev_prod_switch', 'Use to switch between previously defined HTML comment blocks in project files to change environment from development to production and back.', function () {

        // Merge task-specific and/or target-specific options with these defaults.
        var options = this.options();
        var blocking_char = ((options.env_char) ? options.env_char : '#');
        var env_prod = (options.env_block_prod) ? options.env_block_prod : 'env:prod';
        var env_dev = (options.env_block_dev) ? options.env_block_dev : 'env:dev';
        var env_test = (options.env_block_test) ? options.env_block_test : 'env:test';

        // Iterate over all specified files.
        this.files.forEach(function (f) {
            var out = f.src.map(function (src) {
                if (options.environment === 'prod') {
                    var result = grunt.file.read(src, "utf8")
                        .replace(new RegExp("<\!-- " + env_prod + " --" + blocking_char + ">","gi"), "<!-- " + env_prod + " -->")
                        .replace(new RegExp("<\!-- " + env_dev + " -->","gi"), "<!-- " + env_dev + " --" + blocking_char + ">")
                        .replace(new RegExp("<\!-- " + env_test + " -->","gi"), "<!-- " + env_test + " --" + blocking_char + ">")
                        .replace("/* " + env_prod + " *" + blocking_char+"/", "/* " + env_prod + " */")
                        .replace("/* " + env_dev + " */", "/* " + env_dev + " *" + blocking_char+"/")
                        .replace("/* " + env_test + " */", "/* " + env_test + " *" + blocking_char+"/");
                } else if (options.environment === "dev") {
                    var result = grunt.file.read(src, "utf8")
                        .replace(new RegExp("<\!-- " + env_dev + " --" + blocking_char + ">","gi"), "<!-- " + env_dev + " -->")
                        .replace(new RegExp("<\!-- " + env_prod + " -->","gi"), "<!-- " + env_prod + " --" + blocking_char + ">")
                        .replace(new RegExp("<\!-- " + env_test + " -->","gi"), "<!-- " + env_test + " --" + blocking_char + ">")
                        .replace("/* " + env_dev + " *" + blocking_char+"/", "/* " + env_dev + " */")
                        .replace("/* " + env_prod + " */", "/* " + env_prod + " *" + blocking_char + "/")
                        .replace("/* " + env_test + " */", "/* " + env_test + " *" + blocking_char + "/");
                } else if (options.environment === "test") {
                    var result = grunt.file.read(src, "utf8")
                        .replace(new RegExp("<\!-- " + env_test + " --" + blocking_char + ">","gi"), "<!-- " + env_test + " -->")
                        .replace(new RegExp("<\!-- " + env_prod + " -->","gi"), "<!-- " + env_prod + " --" + blocking_char + ">")
                        .replace(new RegExp("<\!-- " + env_dev + " -->","gi"), "<!-- " + env_dev + " --" + blocking_char + ">")
                        .replace("/* " + env_test + " *" + blocking_char+"/", "/* " + env_test + " */")
                        .replace("/* " + env_prod + " */", "/* " + env_prod + " *" + blocking_char + "/")
                        .replace("/* " + env_dev + " */", "/* " + env_dev + " *" + blocking_char + "/");
                } else {
                    grunt.log.writeln('Please set "environment" in options object.');
                }
                return result;
            });

            var env = (options.environment === 'prod') ? 'Production' : (options.environment === 'dev') ? 'Development' : 'Test';
            grunt.log.writeln('Data in file "' + f.dest + '" switched to "' + env + '".');

            grunt.file.write(f.dest, out);
        });

    });
};<commit_msg>fix replacing all occurrences env_block in javascript file reference: http://stackoverflow.com/questions/1144783<commit_after>/*
 * grunt-dev-prod-switch
 * https://github.com/sanusart/grunt-dev-prod-switch
 *
 * Copyright (c) 2013 Sasha Khamkov
 * Licensed under the MIT license.
 */

'use strict';

module.exports = function (grunt) {

    // Please see the Grunt documentation for more information regarding task
    // creation: http://gruntjs.com/creating-tasks

    grunt.registerMultiTask('dev_prod_switch', 'Use to switch between previously defined HTML comment blocks in project files to change environment from development to production and back.', function () {

        // Merge task-specific and/or target-specific options with these defaults.
        var options = this.options();
        var blocking_char = ((options.env_char) ? options.env_char : '#');
        var env_prod = (options.env_block_prod) ? options.env_block_prod : 'env:prod';
        var env_dev = (options.env_block_dev) ? options.env_block_dev : 'env:dev';
        var env_test = (options.env_block_test) ? options.env_block_test : 'env:test';

        // Iterate over all specified files.
        this.files.forEach(function (f) {
            var out = f.src.map(function (src) {
                if (options.environment === 'prod') {
                    var result = grunt.file.read(src, "utf8")
                        .replace(new RegExp("<\!-- " + env_prod + " --" + blocking_char + ">","gi"), "<!-- " + env_prod + " -->")
                        .replace(new RegExp("<\!-- " + env_dev + " -->","gi"), "<!-- " + env_dev + " --" + blocking_char + ">")
                        .replace(new RegExp("<\!-- " + env_test + " -->","gi"), "<!-- " + env_test + " --" + blocking_char + ">")
                        .split("/* " + env_prod + " *" + blocking_char+"/").join("/* " + env_prod + " */")
                        .split("/* " + env_dev + " */").join("/* " + env_dev + " *" + blocking_char+"/")
                        .split("/* " + env_test + " */").join("/* " + env_test + " *" + blocking_char+"/");
                } else if (options.environment === "dev") {
                    var result = grunt.file.read(src, "utf8")
                        .replace(new RegExp("<\!-- " + env_dev + " --" + blocking_char + ">","gi"), "<!-- " + env_dev + " -->")
                        .replace(new RegExp("<\!-- " + env_prod + " -->","gi"), "<!-- " + env_prod + " --" + blocking_char + ">")
                        .replace(new RegExp("<\!-- " + env_test + " -->","gi"), "<!-- " + env_test + " --" + blocking_char + ">")
                        .split("/* " + env_dev + " *" + blocking_char+"/").join("/* " + env_dev + " */")
                        .split("/* " + env_prod + " */").join("/* " + env_prod + " *" + blocking_char + "/")
                        .split("/* " + env_test + " */").join("/* " + env_test + " *" + blocking_char + "/");
                } else if (options.environment === "test") {
                    var result = grunt.file.read(src, "utf8")
                        .replace(new RegExp("<\!-- " + env_test + " --" + blocking_char + ">","gi"), "<!-- " + env_test + " -->")
                        .replace(new RegExp("<\!-- " + env_prod + " -->","gi"), "<!-- " + env_prod + " --" + blocking_char + ">")
                        .replace(new RegExp("<\!-- " + env_dev + " -->","gi"), "<!-- " + env_dev + " --" + blocking_char + ">")
                        .split("/* " + env_test + " *" + blocking_char+"/").join("/* " + env_test + " */")
                        .split("/* " + env_prod + " */").join("/* " + env_prod + " *" + blocking_char + "/")
                        .split("/* " + env_dev + " */").join("/* " + env_dev + " *" + blocking_char + "/");
                } else {
                    grunt.log.writeln('Please set "environment" in options object.');
                }
                return result;
            });

            var env = (options.environment === 'prod') ? 'Production' : (options.environment === 'dev') ? 'Development' : 'Test';
            grunt.log.writeln('Data in file "' + f.dest + '" switched to "' + env + '".');

            grunt.file.write(f.dest, out);
        });

    });
};<|endoftext|>


<commit_before>import assert from 'assert';
import Vue from 'vue';
import EaselSprite from '../resources/assets/js/components/EaselSprite.vue';
import $ from 'jquery';
import _ from 'lodash';
import easeljs from '../resources/assets/js/easel.js';
import mochaX from './mochaX.js';

var garyStart = 32 * 6 + 16;
var eventTypes = ['added', 'click', 'dblclick', 'mousedown', 'mouseout', 'mouseover', 'pressmove', 'pressup', 'removed', 'rollout', 'rollover', 'tick', 'animationend', 'change'];

describe('EaselDisplayObject', function () {

    var eventHandlerCode = eventTypes.map(type => `@${type}="logEvent"`).join(' ');

    var easel = {
        addChild(vueChild) {
            vueChild.added = true;
        },
        removeChild(vueChild) {
            vueChild.removed = true;
        },
    };

    var vm = new Vue({
        template: `

                <easel-sprite ref="sprite"
                    v-if="showSprite"
                    :animation="animation"
                    :x="x"
                    :y="y"
                    :flip="flip"
                    :rotation="rotation"
                    :scale="scale"
                    :alpha="alpha"
                    :shadow="shadow"
                    :align="[hAlign, vAlign]"
                    ${eventHandlerCode}
                >
                </easel-sprite>

        `,
        provide() {
            return {
                spriteSheet: new easeljs.SpriteSheet({
                    images: ['/base/sprites/lastguardian-all.png'],
                    frames: {width: 32, height: 32},
                    animations: {
                        stand: garyStart + 5,
                        run: [garyStart + 6, garyStart + 7],
                    },
                    framerate: 30,
                }),
                easel: easel,
            };
        },
        data() {
            return {
                animation: 'stand',
                x: 1,
                y: 2,
                eventLog: [],
                showSprite: true,
                flip: '',
                rotation: null,
                scale: 1,
                alpha: null,
                shadow: null,
                hAlign: 'left',
                vAlign: 'top',
            };
        },
        components: {
            'easel-sprite': EaselSprite,
        },
        methods: {
            logEvent(event) {
                this.eventLog.push(event);
            },
            clearEventLog() {
                this.eventLog = [];
            },
        },
    }).$mount();

    var sprite = vm.$refs.sprite;

    it('should exist', function () {
        assert(sprite);
    });

    it('should have same easel', function () {
        assert(sprite.easel === easel);
    });

    it('should have component field', function () {
        assert(sprite.component);
    });

    it('should have been added', function () {
        assert(sprite.added);
    });

    it('should have x and y', function () {
        assert(sprite.component.x === 1);
        assert(sprite.component.y === 2);
    });

    it('should change x and y', function (done) {
        vm.x = 3;
        vm.y = 4;
        Vue.nextTick()
            .then(() => {
                assert(sprite.component.x === 3);
                assert(sprite.component.y === 4);
                done();
            });
    });

    _.each(eventTypes, (type) => {
        it(`emits ${type} event`, function () {
            vm.clearEventLog();
            sprite.component.dispatchEvent(type);
            assert(vm.eventLog.length === 1);
        });
    });

    it('should go away when gone', function (done) {
        vm.showSprite = false;
        Vue.nextTick()
            .then(() => {
                assert(easel.stage.children.length === 0);
                vm.showSprite = true;
                return Vue.nextTick();
            })
            .then(() => {
                sprite = vm.$refs.sprite; // make sure others get the new var
                done();
            });
    });

    it('should not flip', function (done) {
        vm.flip = '';
        Vue.nextTick()
            .then(() => {
                assert(sprite.component.scaleX === 1);
                assert(sprite.component.scaleY === 1);
                done();
            });
    });

    it('should flip horizontal', function (done) {
        vm.flip = 'horizontal';
        Vue.nextTick()
            .then(() => {
                assert(sprite.component.scaleX === -1);
                assert(sprite.component.scaleY === 1);
                done();
            });
    });

    it('should flip vertical', function (done) {
        vm.flip = 'vertical';
        Vue.nextTick()
            .then(() => {
                assert(sprite.component.scaleX === 1);
                assert(sprite.component.scaleY === -1);
                done();
            });
    });

    it('should flip both', function (done) {
        vm.flip = 'both';
        Vue.nextTick()
            .then(() => {
                assert(sprite.component.scaleX === -1);
                assert(sprite.component.scaleY === -1);
                done();
            });
    });

    it('should not rotate', function () {
        assert(!sprite.component.rotation);
    });

    it('should rotate', function (done) {
        vm.rotation = 15;
        Vue.nextTick()
            .then(() => {
                assert(sprite.component.rotation === 15);
                done();
            });
    });

    it('should not scale', function (done) {
        vm.flip = '';
        Vue.nextTick()
            .then(() => {
                assert(sprite.component.scaleX === 1);
                assert(sprite.component.scaleY === 1);
                done();
            });
    });

    it('should scale to double', function (done) {
        vm.scale = 2;
        Vue.nextTick()
            .then(() => {
                assert(sprite.component.scaleX === 2);
                assert(sprite.component.scaleY === 2);
                done();
            });
    });

    it('should scale and flip', function (done) {
        vm.scale = 2;
        vm.flip = "both";
        Vue.nextTick()
            .then(() => {
                assert(sprite.component.scaleX === -2);
                assert(sprite.component.scaleY === -2);
                done();
            });
    });

    it('should be 100% opaque', function () {
        assert(sprite.component.alpha === 1, "Wrong alpha: " + sprite.component.alpha);
    });

    it('should become 50% opaque', function (done) {
        vm.alpha = .5;
        Vue.nextTick()
            .then(mochaX(() => {
                assert(sprite.component.alpha === .5, "Wrong alpha: " + sprite.component.alpha);
                done();
            }));
    });

    it('should have no shadow', function () {
        assert(sprite.component.shadow === null, "Component: " + sprite.component);
    });

    it('should have shadow', function (done) {
        vm.shadow = ["black", 5, 7, 10];
        Vue.nextTick(mochaX(() => {
            assert(sprite.component.shadow.color === 'black', 'Shadow color: ' + sprite.component.shadow.color);
            assert(sprite.component.shadow.offsetX === 5, 'Shadow offsetX: ' + sprite.component.shadow.offsetX);
            assert(sprite.component.shadow.offsetY === 7, 'Shadow offsetY: ' + sprite.component.shadow.offsetY);
            assert(sprite.component.shadow.blur === 10, 'Shadow blur: ' + sprite.component.shadow.blur);
            done();
        }));
    });

    it('should have no shadow again', function (done) {
        vm.shadow = null;
        Vue.nextTick(mochaX(() => {
            assert(sprite.component.shadow === null, "Component: " + sprite.component);
            done();
        }));
    });

    it('should have the right hAlign', function () {
        assert(sprite.component.regX === 0, 'Wrong regX: ' + sprite.component.regX);
    });

    it('should be able to change the hAlign', function (done) {
        vm.hAlign = 'right';
        Vue.nextTick()
            .then(mochaX(() => {
                assert(sprite.component.regX === 32, 'Wrong regX in: ' + sprite.component.regX);
                done();
            }));
    });

    it('should default hAlign to center', function (done) {
        vm.hAlign = '';
        Vue.nextTick()
            .then(mochaX(() => {
                assert(sprite.component.regX === 16, 'Wrong default regX in: ' + sprite.component.regX);
                done();
            }));
    });

    it('should have the right vAlign', function () {
        assert(sprite.component.regY === 0, 'Wrong regY: ' + sprite.component.regY);
    });

    it('should be able to change the vAlign', function (done) {
        vm.vAlign = 'center';
        Vue.nextTick()
            .then(mochaX(() => {
                assert(sprite.component.regY === 16, 'Wrong regY in: ' + sprite.component.regY);
                done();
            }));
    });

    it('should default vAlign to bottom', function (done) {
        vm.vAlign = '';
        Vue.nextTick()
            .then(mochaX(() => {
                assert(sprite.component.regY === 32, 'Wrong default regY in: ' + sprite.component.regY);
                done();
            }));
    });
});
<commit_msg>This fixed all of the failing tests.<commit_after>import assert from 'assert';
import Vue from 'vue';
import EaselSprite from '../resources/assets/js/components/EaselSprite.vue';
import $ from 'jquery';
import _ from 'lodash';
import easeljs from '../resources/assets/js/easel.js';
import mochaX from './mochaX.js';

var garyStart = 32 * 6 + 16;
var eventTypes = ['added', 'click', 'dblclick', 'mousedown', 'mouseout', 'mouseover', 'pressmove', 'pressup', 'removed', 'rollout', 'rollover', 'tick', 'animationend', 'change'];

describe('EaselDisplayObject', function () {

    var eventHandlerCode = eventTypes.map(type => `@${type}="logEvent"`).join(' ');

    var easel = {
        addChild(vueChild) {
            vueChild.added = true;
        },
        removeChild(vueChild) {
            vueChild.removed = true;
        },
    };

    var vm = new Vue({
        template: `

                <easel-sprite ref="sprite"
                    v-if="showSprite"
                    :animation="animation"
                    :x="x"
                    :y="y"
                    :flip="flip"
                    :rotation="rotation"
                    :scale="scale"
                    :alpha="alpha"
                    :shadow="shadow"
                    :align="[hAlign, vAlign]"
                    ${eventHandlerCode}
                >
                </easel-sprite>

        `,
        provide() {
            return {
                spriteSheet: new easeljs.SpriteSheet({
                    images: ['/base/sprites/lastguardian-all.png'],
                    frames: {width: 32, height: 32},
                    animations: {
                        stand: garyStart + 5,
                        run: [garyStart + 6, garyStart + 7],
                    },
                    framerate: 30,
                }),
                easel: easel,
            };
        },
        data() {
            return {
                animation: 'stand',
                x: 1,
                y: 2,
                eventLog: [],
                showSprite: true,
                flip: '',
                rotation: null,
                scale: 1,
                alpha: null,
                shadow: null,
                hAlign: 'left',
                vAlign: 'top',
            };
        },
        components: {
            'easel-sprite': EaselSprite,
        },
        methods: {
            logEvent(event) {
                this.eventLog.push(event);
            },
            clearEventLog() {
                this.eventLog = [];
            },
        },
    }).$mount();

    var sprite = vm.$refs.sprite;

    it('should exist', function () {
        assert(sprite);
    });

    it('should have same easel', function () {
        assert(sprite.easel === easel);
    });

    it('should have component field', function () {
        assert(sprite.component);
    });

    it('should have been added', function () {
        assert(sprite.added);
    });

    it('should have x and y', function () {
        assert(sprite.component.x === 1);
        assert(sprite.component.y === 2);
    });

    it('should change x and y', function (done) {
        vm.x = 3;
        vm.y = 4;
        Vue.nextTick()
            .then(() => {
                assert(sprite.component.x === 3);
                assert(sprite.component.y === 4);
                done();
            });
    });

    _.each(eventTypes, (type) => {
        it(`emits ${type} event`, function () {
            vm.clearEventLog();
            sprite.component.dispatchEvent(type);
            assert(vm.eventLog.length === 1);
        });
    });

    it('should go away when gone', function (done) {
        vm.showSprite = false;
        Vue.nextTick()
            .then(() => {
                assert(sprite.removed);
                vm.showSprite = true;
                return Vue.nextTick();
            })
            .then(() => {
                sprite = vm.$refs.sprite; // make sure others get the new var
                done();
            });
    });

    it('should not flip', function (done) {
        vm.flip = '';
        Vue.nextTick()
            .then(() => {
                assert(sprite.component.scaleX === 1);
                assert(sprite.component.scaleY === 1);
                done();
            });
    });

    it('should flip horizontal', function (done) {
        vm.flip = 'horizontal';
        Vue.nextTick()
            .then(() => {
                assert(sprite.component.scaleX === -1);
                assert(sprite.component.scaleY === 1);
                done();
            });
    });

    it('should flip vertical', function (done) {
        vm.flip = 'vertical';
        Vue.nextTick()
            .then(() => {
                assert(sprite.component.scaleX === 1);
                assert(sprite.component.scaleY === -1);
                done();
            });
    });

    it('should flip both', function (done) {
        vm.flip = 'both';
        Vue.nextTick()
            .then(() => {
                assert(sprite.component.scaleX === -1);
                assert(sprite.component.scaleY === -1);
                done();
            });
    });

    it('should not rotate', function () {
        assert(!sprite.component.rotation);
    });

    it('should rotate', function (done) {
        vm.rotation = 15;
        Vue.nextTick()
            .then(() => {
                assert(sprite.component.rotation === 15);
                done();
            });
    });

    it('should not scale', function (done) {
        vm.flip = '';
        Vue.nextTick()
            .then(() => {
                assert(sprite.component.scaleX === 1);
                assert(sprite.component.scaleY === 1);
                done();
            });
    });

    it('should scale to double', function (done) {
        vm.scale = 2;
        Vue.nextTick()
            .then(() => {
                assert(sprite.component.scaleX === 2);
                assert(sprite.component.scaleY === 2);
                done();
            });
    });

    it('should scale and flip', function (done) {
        vm.scale = 2;
        vm.flip = "both";
        Vue.nextTick()
            .then(() => {
                assert(sprite.component.scaleX === -2);
                assert(sprite.component.scaleY === -2);
                done();
            });
    });

    it('should be 100% opaque', function () {
        assert(sprite.component.alpha === 1, "Wrong alpha: " + sprite.component.alpha);
    });

    it('should become 50% opaque', function (done) {
        vm.alpha = .5;
        Vue.nextTick()
            .then(mochaX(() => {
                assert(sprite.component.alpha === .5, "Wrong alpha: " + sprite.component.alpha);
                done();
            }));
    });

    it('should have no shadow', function () {
        assert(sprite.component.shadow === null, "Component: " + sprite.component);
    });

    it('should have shadow', function (done) {
        vm.shadow = ["black", 5, 7, 10];
        Vue.nextTick(mochaX(() => {
            assert(sprite.component.shadow.color === 'black', 'Shadow color: ' + sprite.component.shadow.color);
            assert(sprite.component.shadow.offsetX === 5, 'Shadow offsetX: ' + sprite.component.shadow.offsetX);
            assert(sprite.component.shadow.offsetY === 7, 'Shadow offsetY: ' + sprite.component.shadow.offsetY);
            assert(sprite.component.shadow.blur === 10, 'Shadow blur: ' + sprite.component.shadow.blur);
            done();
        }));
    });

    it('should have no shadow again', function (done) {
        vm.shadow = null;
        Vue.nextTick(mochaX(() => {
            assert(sprite.component.shadow === null, "Component: " + sprite.component);
            done();
        }));
    });

    it('should have the right hAlign', function () {
        assert(sprite.component.regX === 0, 'Wrong regX: ' + sprite.component.regX);
    });

    it('should be able to change the hAlign', function (done) {
        vm.hAlign = 'right';
        Vue.nextTick()
            .then(mochaX(() => {
                assert(sprite.component.regX === 32, 'Wrong regX in: ' + sprite.component.regX);
                done();
            }));
    });

    it('should default hAlign to center', function (done) {
        vm.hAlign = '';
        Vue.nextTick()
            .then(mochaX(() => {
                assert(sprite.component.regX === 16, 'Wrong default regX in: ' + sprite.component.regX);
                done();
            }));
    });

    it('should have the right vAlign', function () {
        assert(sprite.component.regY === 0, 'Wrong regY: ' + sprite.component.regY);
    });

    it('should be able to change the vAlign', function (done) {
        vm.vAlign = 'center';
        Vue.nextTick()
            .then(mochaX(() => {
                assert(sprite.component.regY === 16, 'Wrong regY in: ' + sprite.component.regY);
                done();
            }));
    });

    it('should default vAlign to bottom', function (done) {
        vm.vAlign = '';
        Vue.nextTick()
            .then(mochaX(() => {
                assert(sprite.component.regY === 32, 'Wrong default regY in: ' + sprite.component.regY);
                done();
            }));
    });
});
<|endoftext|>