<commit_before>const bot = require('./bot');
const functions = require('./functions');
const music = require('./music');
const bf2 = require('./bf2');
const bf2142 = require('./bf2142');
const Discord = require('discord.js')
const rank = require('./rank');
const request = require('request');

bot.on('message', message => {
    if (!message.content.startsWith('~')) {
        return;
    } //base case
    var cmd = message.content.split(' ')[0].substring(1).toLowerCase();
    commands[cmd].exec(message);
});
var commands = {
    'pong': {
        description: 'reply with a pong',
        syntax: '~ping',
        exec: function(message) {
            message.reply('pong');
        }
    },
    'yo': {
        description: 'reply with a yo bro',
        syntax: '~yo',
        exec: function(message) {
            message.reply('yo bro');
        }
    },
    'link': {
        description: 'link revive account to this discord account',
        syntax: '~link',
        exec: function(message) {
            functions.integrate(message.author);
        }
    },
    'refresh': {
        description: 'refresh a user discord link status',
        syntax: '~refresh',
        exec: function(message) {
            if (message.content.substring(9).trim() == 'all' &&
                message.guild.name == 'Revive Netowrk Dev') {
                functions.refreshAll(bot.guilds.get('184536578654339072').members.array())
            } else {
                functions.refreshUser(message.author);
            }
        }
    },
    'bf2': {
        description: 'finds a bf2 player',
        syntax: '~bf2 <PlayerName>',
        exec: function(message) {
            var nick = message.content.substring(5).trim();
			bf2.getPlayers(nick,function(plist){
            console.log("BF2 in index.js gets executed");
            if (plist == null) {
                message.channel.sendMessage("API Down or invalid search");
                return;
            }
            if (plist.length >= 1) {
                //checking for exact matches
                var exact = plist.find(o => o.nick.toUpperCase().trim() === nick.toUpperCase());
                console.log(exact);
                var res = "**S.no.\tName \t PID \t Score**";
            }
			    if (plist.length == 0) {
                message.channel.sendMessage("Player not found"); return;
            }
            var start = 0;
            var past = 0;
            if (exact != null) {
			res = res + "\n" + (1) + "\t" + "\t" +  bf2.str(exact);
                start++;
            }
            for (var i = start; i < plist.length; i++) {
                if (exact != null && i == plist.indexOf(exact)) {
                    past++;
                    continue;
                }
                if (i == 26) {
                    res = res + "\n" + (plist.length - 25) +
                        " more players found to Get a full list of players \n" +
                        "<https://battlelog.co/player_search.php?q=" + nick + ">";
                    break;
                } else {
                    res = res + " \n" + (i + 1 - past) +
                        "\t" + "\t" + bf2.str(plist[i]);
                }
            }
			message.channel.sendMessage(res);
			console.log(res);
			});
        }
    },
    'bf2142': {
        description: 'finds a bf2142 player',
        syntax: '~bf2142 <PlayerName>',
        exec: function(message) {

            var nick = message.content.substring(7).trim();
            bf2142.getPlayers(nick,function(plist){
            console.log("BF2142 in index.js gets executed");
            if (plist == null) {
                message.channel.sendMessage("API Down or invalid search");
                return;
            }
            if (plist.length >= 1) {
                //checking for exact matches
                var exact = plist.find(o => o.nick.toUpperCase().trim() === nick.toUpperCase());
                console.log(exact);
                var res = "**S.no.\tName \t PID**";
            }
			if (plist.length == 0) {
                message.channel.sendMessage("Player not found");return;
            }
            var start = 0;
            var past = 0;
            if (exact != null) {
                res = res + "\n" + (1) + "\t" + "\t" + bf2142.str(exact);
                start++;
            }
            for (var i = start; i < plist.length; i++) {
                if (exact != null && i == plist.indexOf(exact)) {
                    past++;
                    continue;
                }
                if (i == 26) {
                    res = res + "\n" + (plist.length - 25) +
                        " more players found to Get a full list of players \n" +
                        "<https://battlelog.co/player_search.php?q=" + nick + ">";
                    break;
                } else {
                    res = res + " \n" + (i + 1 - past) +
                        "\t" + "\t" + bf2142.str(plist[i]);
                }
            }
			message.channel.sendMessage(res);
			console.log(res);
			});
        }
    },
    'cookie': {
        description: 'eats a cookie',
        syntax: '~cookie',
        exec: function(message) {
            message.reply('crunch crunch');
        }
    },
    'add': {
        description: 'adds a person to a role',
        syntax: '~add <UserMention> to <roleName>',
        exec: function(message) {
            if (!message.member.hasPermission("MANAGE_ROLES_OR_PERMISSIONS")) {
                message.channel.sendMessage("You aren't Worthy");
                return;
            }
            var member = message.guild.member(message.mentions.users.first());
            var msg = message.content.split("to ");
            member.addRole(message.guild.roles.find("name", msg[msg.length - 1]));
            message.reply('done');
        }
    },
    'remove': {
        description: 'removes a person to a role',
        syntax: '~remove <UserMention> from <roleName>',
        exec: function(message) {
            if (!message.member.hasPermission("MANAGE_ROLES_OR_PERMISSIONS")) {
                message.channel.sendMessage("You aren't Worthy");
                return;
            }
            var member = message.guild.member(message.mentions.users.first());
            var msg = message.content.split("to ");
            member.removeRole(message.guild.roles.find("name", msg[msg.length - 1]));
            message.reply('done');
        }
    },
    'help': {
        description: 'displays help',
        syntax: '~help',
        exec: function(message) {
			var embed = new Discord.RichEmbed().setTitle('HELP').setColor("#FF7F50");
            for (cmd in commands) {
                embed.addField(cmd,"Description: " + commands[cmd].description + "\n"+ "Syntax: " + commands[cmd].syntax);
			}
			//embed.addField('Music',"Description: Access the music bot using - as the prefix" + "\n"+ "Syntax: -help");
            message.channel.sendEmbed(embed);
        }
    },
	'play': {
        description: 'plays the youtube url specified',
        syntax: '~play <youtube_url>',
        exec: function(message) {
			url = message.content.substring(6).trim();
			music.play(url,message);
        }
    },
	'pause': {
        description: 'pauses the voice stream',
        syntax: '~pause',
        exec: function(message) {
			music.pause(message);
        }
    },
	'resume': {
        description: 'resumes the voice stream',
        syntax: '~resume',
        exec: function(message) {
			music.resume(message);
        }
    },
	'clear': {
        description: 'clears the playlist',
        syntax: '~clear',
        exec: function(message) {
			music.clear(message);
        }
    },
	'playnext': {
        description: 'plays the next song',
        syntax: '~playnext',
        exec: function(message) {
			music.playNext(message);
        }
    },
	'setvol': {
        description: 'sets the play volume',
        syntax: '~setVol',
        exec: function(message) {
			music.setVol(message.content.substring(7).trim());
        }
    },
	'queue': {
        description: 'views the queue',
        syntax: '~queue',
        exec: function(message) {
			music.queue(message);
        }
    },
	'info': {
        description: 'Gives the Battlelog Profile of a Verified User',
        syntax: '~info @usermention',
        exec: function(message){rank.rank(message);}
    },
	'get':{
        description: 'does a http get on the url given and sends it to log',
	syntax:'~get <url>',
	exec: function(message){
	 if (message.guild != bot.guilds.get('256299642180861953')) { return;  }
         request(message.content.substring(5),function (error, response, body)
	 {
         if(error)
	 {
		 message.reply(error);
	 }
	 else
	 {
	 console.log(body)
	 if(body.length<2000)
	 message.channel.sendMessage("```Javascript\n"+body+'```');
	 }
	 });
	}
	}
}
<commit_msg>added support for post too<commit_after>const bot = require('./bot');
const functions = require('./functions');
const music = require('./music');
const bf2 = require('./bf2');
const bf2142 = require('./bf2142');
const Discord = require('discord.js')
const rank = require('./rank');
const request = require('request');

bot.on('message', message => {
    if (!message.content.startsWith('~')) {
        return;
    } //base case
    var cmd = message.content.split(' ')[0].substring(1).toLowerCase();
    commands[cmd].exec(message);
});
var commands = {
    'pong': {
        description: 'reply with a pong',
        syntax: '~ping',
        exec: function(message) {
            message.reply('pong');
        }
    },
    'yo': {
        description: 'reply with a yo bro',
        syntax: '~yo',
        exec: function(message) {
            message.reply('yo bro');
        }
    },
    'link': {
        description: 'link revive account to this discord account',
        syntax: '~link',
        exec: function(message) {
            functions.integrate(message.author);
        }
    },
    'refresh': {
        description: 'refresh a user discord link status',
        syntax: '~refresh',
        exec: function(message) {
            if (message.content.substring(9).trim() == 'all' &&
                message.guild.name == 'Revive Netowrk Dev') {
                functions.refreshAll(bot.guilds.get('184536578654339072').members.array())
            } else {
                functions.refreshUser(message.author);
            }
        }
    },
    'bf2': {
        description: 'finds a bf2 player',
        syntax: '~bf2 <PlayerName>',
        exec: function(message) {
            var nick = message.content.substring(5).trim();
			bf2.getPlayers(nick,function(plist){
            console.log("BF2 in index.js gets executed");
            if (plist == null) {
                message.channel.sendMessage("API Down or invalid search");
                return;
            }
            if (plist.length >= 1) {
                //checking for exact matches
                var exact = plist.find(o => o.nick.toUpperCase().trim() === nick.toUpperCase());
                console.log(exact);
                var res = "**S.no.\tName \t PID \t Score**";
            }
			    if (plist.length == 0) {
                message.channel.sendMessage("Player not found"); return;
            }
            var start = 0;
            var past = 0;
            if (exact != null) {
			res = res + "\n" + (1) + "\t" + "\t" +  bf2.str(exact);
                start++;
            }
            for (var i = start; i < plist.length; i++) {
                if (exact != null && i == plist.indexOf(exact)) {
                    past++;
                    continue;
                }
                if (i == 26) {
                    res = res + "\n" + (plist.length - 25) +
                        " more players found to Get a full list of players \n" +
                        "<https://battlelog.co/player_search.php?q=" + nick + ">";
                    break;
                } else {
                    res = res + " \n" + (i + 1 - past) +
                        "\t" + "\t" + bf2.str(plist[i]);
                }
            }
			message.channel.sendMessage(res);
			console.log(res);
			});
        }
    },
    'bf2142': {
        description: 'finds a bf2142 player',
        syntax: '~bf2142 <PlayerName>',
        exec: function(message) {

            var nick = message.content.substring(7).trim();
            bf2142.getPlayers(nick,function(plist){
            console.log("BF2142 in index.js gets executed");
            if (plist == null) {
                message.channel.sendMessage("API Down or invalid search");
                return;
            }
            if (plist.length >= 1) {
                //checking for exact matches
                var exact = plist.find(o => o.nick.toUpperCase().trim() === nick.toUpperCase());
                console.log(exact);
                var res = "**S.no.\tName \t PID**";
            }
			if (plist.length == 0) {
                message.channel.sendMessage("Player not found");return;
            }
            var start = 0;
            var past = 0;
            if (exact != null) {
                res = res + "\n" + (1) + "\t" + "\t" + bf2142.str(exact);
                start++;
            }
            for (var i = start; i < plist.length; i++) {
                if (exact != null && i == plist.indexOf(exact)) {
                    past++;
                    continue;
                }
                if (i == 26) {
                    res = res + "\n" + (plist.length - 25) +
                        " more players found to Get a full list of players \n" +
                        "<https://battlelog.co/player_search.php?q=" + nick + ">";
                    break;
                } else {
                    res = res + " \n" + (i + 1 - past) +
                        "\t" + "\t" + bf2142.str(plist[i]);
                }
            }
			message.channel.sendMessage(res);
			console.log(res);
			});
        }
    },
    'cookie': {
        description: 'eats a cookie',
        syntax: '~cookie',
        exec: function(message) {
            message.reply('crunch crunch');
        }
    },
    'add': {
        description: 'adds a person to a role',
        syntax: '~add <UserMention> to <roleName>',
        exec: function(message) {
            if (!message.member.hasPermission("MANAGE_ROLES_OR_PERMISSIONS")) {
                message.channel.sendMessage("You aren't Worthy");
                return;
            }
            var member = message.guild.member(message.mentions.users.first());
            var msg = message.content.split("to ");
            member.addRole(message.guild.roles.find("name", msg[msg.length - 1]));
            message.reply('done');
        }
    },
    'remove': {
        description: 'removes a person to a role',
        syntax: '~remove <UserMention> from <roleName>',
        exec: function(message) {
            if (!message.member.hasPermission("MANAGE_ROLES_OR_PERMISSIONS")) {
                message.channel.sendMessage("You aren't Worthy");
                return;
            }
            var member = message.guild.member(message.mentions.users.first());
            var msg = message.content.split("to ");
            member.removeRole(message.guild.roles.find("name", msg[msg.length - 1]));
            message.reply('done');
        }
    },
    'help': {
        description: 'displays help',
        syntax: '~help',
        exec: function(message) {
			var embed = new Discord.RichEmbed().setTitle('HELP').setColor("#FF7F50");
            for (cmd in commands) {
                embed.addField(cmd,"Description: " + commands[cmd].description + "\n"+ "Syntax: " + commands[cmd].syntax);
			}
			//embed.addField('Music',"Description: Access the music bot using - as the prefix" + "\n"+ "Syntax: -help");
            message.channel.sendEmbed(embed);
        }
    },
	'play': {
        description: 'plays the youtube url specified',
        syntax: '~play <youtube_url>',
        exec: function(message) {
			url = message.content.substring(6).trim();
			music.play(url,message);
        }
    },
	'pause': {
        description: 'pauses the voice stream',
        syntax: '~pause',
        exec: function(message) {
			music.pause(message);
        }
    },
	'resume': {
        description: 'resumes the voice stream',
        syntax: '~resume',
        exec: function(message) {
			music.resume(message);
        }
    },
	'clear': {
        description: 'clears the playlist',
        syntax: '~clear',
        exec: function(message) {
			music.clear(message);
        }
    },
	'playnext': {
        description: 'plays the next song',
        syntax: '~playnext',
        exec: function(message) {
			music.playNext(message);
        }
    },
	'setvol': {
        description: 'sets the play volume',
        syntax: '~setVol',
        exec: function(message) {
			music.setVol(message.content.substring(7).trim());
        }
    },
	'queue': {
        description: 'views the queue',
        syntax: '~queue',
        exec: function(message) {
			music.queue(message);
        }
    },
	'info': {
        description: 'Gives the Battlelog Profile of a Verified User',
        syntax: '~info @usermention',
        exec: function(message){rank.rank(message);}
    },
	'request':{
        description: 'does a http get on the url given and sends it to log',
	syntax:'~request <method> <url> <body>',
	exec: function(message){
	 if (message.guild != bot.guilds.get('256299642180861953')) { return;  }
	var msg = message.content.toUpperCase().substring(5).trim().split(" ");
	var call = function (error, response, body)
	 {
         if(error)
	 {
		 message.reply(error);
	 }
	 else
	 {
	 console.log(body)
	 if(body.length<2000)
	 message.channel.sendMessage("```Javascript\n"+body+'```');
	 }
	 };
	if(msg[0] === 'GET')
        request(msg[1],call);
	else
	request({uri:msg[1],method:msg[0],json:msg.slice(2)},call);
	}
	}
}
<|endoftext|>


<commit_before>define([
    "use!backbone",
    "use!handlebars",
    "text!search/advanced_search.handlebars",
    "search/Search",
    "datum/DatumFields",
    "datum/DatumFieldView",
    "app/UpdatingCollectionView",
    "libs/Utils"
], function(
    Backbone,
    Handlebars,
    advanced_searchTemplate,
    Search,
    DatumFields,
    DatumFieldView,
    UpdatingCollectionView
) {
  var AdvancedSearchView = Backbone.View.extend(
  /** @lends AdvancedSearchView.prototype */
  {
    /**
     * @class Search View handles the render of the global search in the corner,
     *        and the advanced power search, as well as their events.\
     *
     * @description Starts the Search.
     *
     * @extends Backbone.View
     * @constructs
     */
    initialize : function() {
      Utils.debug("SEARCH init: " + this.el);

      this.model.bind('change', this.render, this);

      //grabbing datumFields from datum and session in the corpus
      this.advancedSearchDatumView = new UpdatingCollectionView({
        collection           : window.app.get("corpus").get("datumFields"),
        childViewConstructor : DatumFieldView,
        childViewTagName     : 'li'
      });
      this.advancedSearchSessionView = new UpdatingCollectionView({
        collection           : window.app.get("corpus").get("sessionFields"),
        childViewConstructor : DatumFieldView,
        childViewTagName     : 'li'
      });
    },

    /**
     * The underlying model of the SearchView is a Search.
     */
    model : Search,

    /**
     * Events that the SearchView is listening to and their handlers.
     */
    events : {
      "click .btn-search-union" : "searchUnion",
      "click .btn-search-intersection" : "searchIntersection"
    },

    /**
     * The Handlebars template rendered as the SearchView.
     */
    template : Handlebars.compile(advanced_searchTemplate),
    advancedSearchDatumView : UpdatingCollectionView,
    advancedSearchSessionView : UpdatingCollectionView,

    /**
     * Renders the SearchView.
     */
    render : function() {
      Utils.debug("SEARCH render: " + this.el);
      if (this.model != undefined) {
        // Display the SearchView
        this.setElement($("#fullscreen-search-view"));
        $(this.el).html(this.template(this.model.toJSON()));

        this.advancedSearchDatumView.el = this.$('.advanced_search_datum');
        this.advancedSearchDatumView.render();

        this.advancedSearchSessionView.el = this.$('.advanced_search_session');
        this.advancedSearchSessionView.render();

        Utils.debug("\trendering search: "+ this.model.get("searchKeywords"));
      } else {
        Utils.debug("\tSearch model was undefined");
      }

      return this;
    },

    /**
     * Perform a search that finds the union of all the criteria.
     */
    searchUnion : function() {
      Utils.debug("In searchUnion");
      // TODO Display the search results
    },

    /**
     * Perform a search that finds the intersection of all the criteria.
     */
    searchIntersection : function() {
      Utils.debug("In searchIntersection");
    },

    /**
     * Initialize the sample Search.
     */
    loadSample : function() {
      this.model.set({
        searchKeywords : "naya"
      });
    }
  });

  return AdvancedSearchView;
});<commit_msg>Union search works over the required Datum fields. #76<commit_after>define([
    "use!backbone",
    "use!handlebars",
    "text!search/advanced_search.handlebars",
    "datum/Datum",
    "datum/DatumFields",
    "datum/DatumFieldView",
    "search/Search",
    "app/UpdatingCollectionView",
    "libs/Utils"
], function(
    Backbone,
    Handlebars,
    advanced_searchTemplate,
    Datum,
    DatumFields,
    DatumFieldView,
    Search,
    UpdatingCollectionView
) {
  var AdvancedSearchView = Backbone.View.extend(
  /** @lends AdvancedSearchView.prototype */
  {
    /**
     * @class Search View handles the render of the global search in the corner,
     *        and the advanced power search, as well as their events.\
     *
     * @description Starts the Search.
     *
     * @extends Backbone.View
     * @constructs
     */
    initialize : function() {
      Utils.debug("SEARCH init: " + this.el);

      this.model.bind('change', this.render, this);

      //grabbing datumFields from datum and session in the corpus
      this.advancedSearchDatumView = new UpdatingCollectionView({
        collection           : window.app.get("corpus").get("datumFields"),
        childViewConstructor : DatumFieldView,
        childViewTagName     : 'li'
      });
      this.advancedSearchSessionView = new UpdatingCollectionView({
        collection           : window.app.get("corpus").get("sessionFields"),
        childViewConstructor : DatumFieldView,
        childViewTagName     : 'li'
      });
    },

    /**
     * The underlying model of the SearchView is a Search.
     */
    model : Search,

    /**
     * Events that the SearchView is listening to and their handlers.
     */
    events : {
      "click .btn-search-union" : "searchUnion",
      "click .btn-search-intersection" : "searchIntersection"
    },

    /**
     * The Handlebars template rendered as the SearchView.
     */
    template : Handlebars.compile(advanced_searchTemplate),
    advancedSearchDatumView : UpdatingCollectionView,
    advancedSearchSessionView : UpdatingCollectionView,

    /**
     * Renders the SearchView.
     */
    render : function() {
      Utils.debug("SEARCH render: " + this.el);
      if (this.model != undefined) {
        // Display the SearchView
        this.setElement($("#fullscreen-search-view"));
        $(this.el).html(this.template(this.model.toJSON()));

        this.advancedSearchDatumView.el = this.$('.advanced_search_datum');
        this.advancedSearchDatumView.render();

        this.advancedSearchSessionView.el = this.$('.advanced_search_session');
        this.advancedSearchSessionView.render();

        Utils.debug("\trendering search: "+ this.model.get("searchKeywords"));
      } else {
        Utils.debug("\tSearch model was undefined");
      }

      return this;
    },

    /**
     * Perform a search that finds the union of all the criteria.
     */
    searchUnion : function() {
      Utils.debug("In searchUnion");

      // All the search fields related to Datum
      var datumFieldsViews = this.advancedSearchDatumView.collection;

      // All the resulting Datum ids
      var allDatumIds = [];

      // Use these to determine when all the mini-searches are complete and
      // we can display the results
      var numDatumFields = this.advancedSearchDatumView.collection.length;
      var numDatumFieldsProcessed = 0;

      datumFieldsViews.each(function(datumField) {
        var value = datumField.get("value");
        if (value && value != "") {
          (new Datum()).searchByDatumField(datumField.get("label"), value, function(datumIds) {
            numDatumFieldsProcessed++;

            // Add this DatumFields' results to any other results
            allDatumIds = allDatumIds.concat(datumIds);

            // If we have all the results, display them in the DataListView
            if (numDatumFieldsProcessed == numDatumFields) {
              appView.dataListView.model.set("datumIds", _.uniq(allDatumIds));
              appView.dataListView.renderNewModel();
            }
          });
        } else {
          numDatumFieldsProcessed++;
        }
      });
    },

    /**
     * Perform a search that finds the intersection of all the criteria.
     */
    searchIntersection : function() {
      Utils.debug("In searchIntersection");
    },

    /**
     * Initialize the sample Search.
     */
    loadSample : function() {
      this.model.set({
        searchKeywords : "naya"
      });
    }
  });

  return AdvancedSearchView;
});<|endoftext|>


<commit_before>// This file is just a base configuration for karma and not directly usable
// Use karma.conf.local.js for local tests
// Use karma.conf.saucelabs.js for saucelabs tests

const cloneDeep = require('lodash/cloneDeep')
const webpackConfig = cloneDeep(require('./webpack.config.js')[1])
delete webpackConfig.entry
delete webpackConfig.output
webpackConfig.devtool = 'inline-source-map'

// https://webpack.github.io/docs/configuration.html#node
// https://rmurphey.com/blog/2015/07/20/karma-webpack-tape-code-coverage
webpackConfig.node = {
  fs: 'empty'
}

webpackConfig.module.loaders = webpackConfig.module.loaders.map((loader) => {
  if (loader.loader === 'babel-loader') {
    loader.options.forceEnv = 'test'
  }
  return loader
})

console.log('Karma webpack config:')
console.log(JSON.stringify(webpackConfig, null, 2))

module.exports = {
  plugins: [
    require('karma-tap'),
    require('karma-webpack')
  ],

  basePath: '',
  frameworks: [ 'tap' ],
  files: [
    'test/runner-browser.js'
  ],

  preprocessors: {
    'test/runner-browser.js': ['webpack'],
    'test/unit/**/*.js': ['webpack']
  },

  webpack: webpackConfig,
  browserDisconnectTolerance: 5,
  browserNoActivityTimeout: 4 * 60 * 1000,
  browserDisconnectTimeout: 10000,
  captureTimeout: 4 * 60 * 1000,
  reporters: [ 'dots' ],
  port: 9876,
  colors: true,
  autoWatch: false,
  singleRun: true
}
<commit_msg>test(e2e): fix karma webpack config alteration<commit_after>// This file is just a base configuration for karma and not directly usable
// Use karma.conf.local.js for local tests
// Use karma.conf.saucelabs.js for saucelabs tests

const cloneDeep = require('lodash/cloneDeep')
const webpackConfig = cloneDeep(require('./webpack.config.js')[1])
delete webpackConfig.entry
delete webpackConfig.output
webpackConfig.devtool = 'inline-source-map'

// https://webpack.github.io/docs/configuration.html#node
// https://rmurphey.com/blog/2015/07/20/karma-webpack-tape-code-coverage
webpackConfig.node = {
  fs: 'empty'
}

webpackConfig.module.rules = webpackConfig.module.rules.map((rule) => {
  if (rule.loader === 'babel-loader') {
    rule.options.forceEnv = 'test'
  }
  return rule
})

console.log('Karma webpack config:')
console.log(JSON.stringify(webpackConfig, null, 2))

module.exports = {
  plugins: [
    require('karma-tap'),
    require('karma-webpack')
  ],

  basePath: '',
  frameworks: [ 'tap' ],
  files: [
    'test/runner-browser.js'
  ],

  preprocessors: {
    'test/runner-browser.js': ['webpack'],
    'test/unit/**/*.js': ['webpack']
  },

  webpack: webpackConfig,
  browserDisconnectTolerance: 5,
  browserNoActivityTimeout: 4 * 60 * 1000,
  browserDisconnectTimeout: 10000,
  captureTimeout: 4 * 60 * 1000,
  reporters: [ 'dots' ],
  port: 9876,
  colors: true,
  autoWatch: false,
  singleRun: true
}
<|endoftext|>


<commit_before>if (typeof Meteor === "undefined") Meteor = {};

(function () {
  var collections = {}; // name -> Collection-type object

  var subs = new Collection();
  // keyed by subs._id. value is unset or an array. if set, sub is not
  // yet ready.
  var sub_ready_callbacks = {};
  // list of subscription tokens outstanding during a
  // captureDependencies run. only set when we're doing a run. The fact
  // that this is a singleton means we can't do recursive
  // Meteor.subscriptions(). But who wants that? What does that even mean?
  var capture_subs;

  Meteor._stream.on('published', function (data) {
    _.each(data, function (changes, collection_name) {
      var coll = collections[collection_name];
      if (!coll) {
        Meteor._debug(
          "discarding data received for unknown collection " +
            JSON.stringify(collection_name));
        return;
      }

      // XXX this is all a little whack. Need to think about how we handle
      // removes, etc.
      _.each(changes.inserted || [], function (elt) {
        if (!coll.findOne(elt._id)) {
          coll._collection.insert(elt);
        } else {
          // we already added it locally! this is the case after an insert
          // handler.
          coll._collection.update({_id: elt._id}, elt);
        }
      });
      _.each(changes.updated || [], function (elt) {
        coll._collection.update({_id: elt._id}, elt);
      });
      _.each(changes.removed || [], function (id) {
        coll._collection.remove({_id: id});
      });
    });
  });

  Meteor._stream.on('subscription_ready', function (id) {
    var arr = sub_ready_callbacks[id];
    if (arr) _.each(arr, function (c) { c(); });
    delete sub_ready_callbacks[id];
  });

  Meteor._stream.reset(function (msg_list) {
    // remove existing subscribe and unsubscribe
    msg_list = _.reject(msg_list, function (elem) {
      return (!elem || elem[0] === "subscribe" || elem[0] === "unsubscribe");
    });

    // add new subscriptions at the end. this way they take effect after
    // the handlers and we don't see flicker.
    subs.find().forEach(function (sub) {
      msg_list.push(
        ['subscribe', {
          _id: sub._id, name: sub.name, args: sub.args}]);
    });

    // clear out the local database!
    _.each(collections, function (col) {
      col._collection.remove({});
    });

    return msg_list;
  });

  var subsToken = subs.find({}).observe({
    added: function (sub) {
      Meteor._stream.emit('subscribe', {
        _id: sub._id, name: sub.name, args: sub.args});
    },
    changed: function (sub) {
      if (sub.count <= 0) {
        // minimongo not re-entrant.
        _.defer(function () { subs.remove({_id: sub._id}); });
      }
    },
    removed: function (id) {
      Meteor._stream.emit('unsubscribe', {_id: id});
    }
  });

  // XXX let it take a second argument, the URL of the domain that
  // hosts the collection :)
  Meteor.Collection = function (name) {
    if (name && (name in collections))
      // maybe should just return collections[name]?
      throw new Error("There is already a remote collection '" + name + "'");

    var ret = {
      _name: name,
      _collection: new Collection(),

      find: function (selector, options) {
        return this._collection.find(selector, options);
      },

      findOne: function (selector) {
        return this._collection.findOne(selector);
      },

      insert: function (obj) {
        // Generate an id for the object.
        // XXX mutates the object passed in. that is not cool.
        if (obj._id)
          Meteor._debug("WARNING: trying to insert object w/ _id set");
        var _id = Collection.uuid();
        obj._id = _id;

        if (this._name)
          Meteor._stream.emit('handle', {
            collection: this._name, type: 'insert', args: obj});
        this._collection.insert(obj);

        return obj;
      },

      update: function (selector, mutator, options) {
        if (typeof(selector) === "string")
          selector = {_id: selector};

        if (this._name)
          Meteor._stream.emit('handle', {
            collection: this._name, type: 'update',
            selector: selector, mutator: mutator, options: options});
        this._collection.update(selector, mutator, options);
      },

      remove: function (selector) {
        if (typeof(selector) === "string")
          selector = {_id: selector};

        if (this._name)
          Meteor._stream.emit('handle', {
            collection: this._name, type: 'remove', selector: selector});
        this._collection.remove(selector);
      },

      schema: function  () {
        // XXX not implemented yet
      },

      api: function (methods) {
        _.each(methods, function (func, method) {
          this[method] = function (/* arguments */) {
            // (must turn 'arguments' into a plain array so as not to
            // confuse stringify)
            var args = [].slice.call(arguments);

            // run the handler ourselves
            methods[method].apply(null, args);

            // tell the server to run the handler
            if (this._name)
              Meteor._stream.emit('handle', {
                collection: this._name, type: 'method',
                method: method, args: args});
          };
        }, this);
      }
    };

    if (name)
      collections[name] = ret;

    return ret;
  };

  _.extend(Meteor, {
    is_server: false,
    is_client: true,

    publish: function() {
      // ignored on the client
    },

    subscribe: function (name, args, callback) {
      var id;
      var existing = subs.find({name: name, args: args}, {reactive: false});

      if (existing && existing[0]) {
        // already subbed, inc count.
        id = existing[0]._id;
        subs.update({_id: id}, {$inc: {count: 1}});

        if (callback) {
          if (sub_ready_callbacks[id])
            sub_ready_callbacks[id].push(callback);
          else
            callback(); // XXX maybe _.defer?
        }
      } else {
        // new sub, add object.
        // generate our own id so we can know it w/ a find afterwards.
        id = Collection.uuid();
        subs.insert({_id: id, name: name, args: args, count: 1});

        sub_ready_callbacks[id] = [];

        if (callback)
          sub_ready_callbacks[id].push(callback);
      }

      // return an object with a stop method.
      var token = {stop: function () {
        if (!id) return; // must have an id (local from above).
        // just update the database. observe takes care of the rest.
        subs.update({_id: id}, {$inc: {count: -1}});
      }};

      if (capture_subs) capture_subs.push(token);

      return token;
    },

    autosubscribe: function (sub_func) {
      var local_subs = [];
      var context = new Meteor.deps.Context();

      context.on_invalidate(function () {
        // recurse.
        Meteor.autosubscribe(sub_func);
        // unsub after re-subbing, to avoid bouncing.
        _.each(local_subs, function (x) { x.stop() });
      });

      context.run(function () {
        if (capture_subs)
          throw new Error("Meteor.autosubscribe may not be called recursively");

        capture_subs = [];
        try {
          sub_func();
        } finally {
          local_subs = capture_subs;
          capture_subs = undefined;
        }
      });
    }
  });
})();
<commit_msg>fix Collection.find() callsite in subscribe<commit_after>if (typeof Meteor === "undefined") Meteor = {};

(function () {
  var collections = {}; // name -> Collection-type object

  var subs = new Collection();
  // keyed by subs._id. value is unset or an array. if set, sub is not
  // yet ready.
  var sub_ready_callbacks = {};
  // list of subscription tokens outstanding during a
  // captureDependencies run. only set when we're doing a run. The fact
  // that this is a singleton means we can't do recursive
  // Meteor.subscriptions(). But who wants that? What does that even mean?
  var capture_subs;

  Meteor._stream.on('published', function (data) {
    _.each(data, function (changes, collection_name) {
      var coll = collections[collection_name];
      if (!coll) {
        Meteor._debug(
          "discarding data received for unknown collection " +
            JSON.stringify(collection_name));
        return;
      }

      // XXX this is all a little whack. Need to think about how we handle
      // removes, etc.
      _.each(changes.inserted || [], function (elt) {
        if (!coll.findOne(elt._id)) {
          coll._collection.insert(elt);
        } else {
          // we already added it locally! this is the case after an insert
          // handler.
          coll._collection.update({_id: elt._id}, elt);
        }
      });
      _.each(changes.updated || [], function (elt) {
        coll._collection.update({_id: elt._id}, elt);
      });
      _.each(changes.removed || [], function (id) {
        coll._collection.remove({_id: id});
      });
    });
  });

  Meteor._stream.on('subscription_ready', function (id) {
    var arr = sub_ready_callbacks[id];
    if (arr) _.each(arr, function (c) { c(); });
    delete sub_ready_callbacks[id];
  });

  Meteor._stream.reset(function (msg_list) {
    // remove existing subscribe and unsubscribe
    msg_list = _.reject(msg_list, function (elem) {
      return (!elem || elem[0] === "subscribe" || elem[0] === "unsubscribe");
    });

    // add new subscriptions at the end. this way they take effect after
    // the handlers and we don't see flicker.
    subs.find().forEach(function (sub) {
      msg_list.push(
        ['subscribe', {
          _id: sub._id, name: sub.name, args: sub.args}]);
    });

    // clear out the local database!
    _.each(collections, function (col) {
      col._collection.remove({});
    });

    return msg_list;
  });

  var subsToken = subs.find({}).observe({
    added: function (sub) {
      Meteor._stream.emit('subscribe', {
        _id: sub._id, name: sub.name, args: sub.args});
    },
    changed: function (sub) {
      if (sub.count <= 0) {
        // minimongo not re-entrant.
        _.defer(function () { subs.remove({_id: sub._id}); });
      }
    },
    removed: function (id) {
      Meteor._stream.emit('unsubscribe', {_id: id});
    }
  });

  // XXX let it take a second argument, the URL of the domain that
  // hosts the collection :)
  Meteor.Collection = function (name) {
    if (name && (name in collections))
      // maybe should just return collections[name]?
      throw new Error("There is already a remote collection '" + name + "'");

    var ret = {
      _name: name,
      _collection: new Collection(),

      find: function (selector, options) {
        return this._collection.find(selector, options);
      },

      findOne: function (selector) {
        return this._collection.findOne(selector);
      },

      insert: function (obj) {
        // Generate an id for the object.
        // XXX mutates the object passed in. that is not cool.
        if (obj._id)
          Meteor._debug("WARNING: trying to insert object w/ _id set");
        var _id = Collection.uuid();
        obj._id = _id;

        if (this._name)
          Meteor._stream.emit('handle', {
            collection: this._name, type: 'insert', args: obj});
        this._collection.insert(obj);

        return obj;
      },

      update: function (selector, mutator, options) {
        if (typeof(selector) === "string")
          selector = {_id: selector};

        if (this._name)
          Meteor._stream.emit('handle', {
            collection: this._name, type: 'update',
            selector: selector, mutator: mutator, options: options});
        this._collection.update(selector, mutator, options);
      },

      remove: function (selector) {
        if (typeof(selector) === "string")
          selector = {_id: selector};

        if (this._name)
          Meteor._stream.emit('handle', {
            collection: this._name, type: 'remove', selector: selector});
        this._collection.remove(selector);
      },

      schema: function  () {
        // XXX not implemented yet
      },

      api: function (methods) {
        _.each(methods, function (func, method) {
          this[method] = function (/* arguments */) {
            // (must turn 'arguments' into a plain array so as not to
            // confuse stringify)
            var args = [].slice.call(arguments);

            // run the handler ourselves
            methods[method].apply(null, args);

            // tell the server to run the handler
            if (this._name)
              Meteor._stream.emit('handle', {
                collection: this._name, type: 'method',
                method: method, args: args});
          };
        }, this);
      }
    };

    if (name)
      collections[name] = ret;

    return ret;
  };

  _.extend(Meteor, {
    is_server: false,
    is_client: true,

    publish: function() {
      // ignored on the client
    },

    subscribe: function (name, args, callback) {
      var id;
      var existing = subs.find({name: name, args: args}, {reactive: false}).fetch();

      if (existing && existing[0]) {
        // already subbed, inc count.
        id = existing[0]._id;
        subs.update({_id: id}, {$inc: {count: 1}});

        if (callback) {
          if (sub_ready_callbacks[id])
            sub_ready_callbacks[id].push(callback);
          else
            callback(); // XXX maybe _.defer?
        }
      } else {
        // new sub, add object.
        // generate our own id so we can know it w/ a find afterwards.
        id = Collection.uuid();
        subs.insert({_id: id, name: name, args: args, count: 1});

        sub_ready_callbacks[id] = [];

        if (callback)
          sub_ready_callbacks[id].push(callback);
      }

      // return an object with a stop method.
      var token = {stop: function () {
        if (!id) return; // must have an id (local from above).
        // just update the database. observe takes care of the rest.
        subs.update({_id: id}, {$inc: {count: -1}});
      }};

      if (capture_subs) capture_subs.push(token);

      return token;
    },

    autosubscribe: function (sub_func) {
      var local_subs = [];
      var context = new Meteor.deps.Context();

      context.on_invalidate(function () {
        // recurse.
        Meteor.autosubscribe(sub_func);
        // unsub after re-subbing, to avoid bouncing.
        _.each(local_subs, function (x) { x.stop() });
      });

      context.run(function () {
        if (capture_subs)
          throw new Error("Meteor.autosubscribe may not be called recursively");

        capture_subs = [];
        try {
          sub_func();
        } finally {
          local_subs = capture_subs;
          capture_subs = undefined;
        }
      });
    }
  });
})();
<|endoftext|>


<commit_before>'use strict';

var Promise = require('bluebird');
var browserify = require('browserify');
var path = require('path');
var titaniumResolve = require('titanium-resolve');

var fs = require('./util/fs');

var BUILTINS = require('./builtins');
var GLOBAL_VARS = require('./globals');
var PRELUDE_PATH = path.resolve(__dirname, 'util', '_prelude.js');
var PRELUDE_SRC = require('fs').readFileSync(PRELUDE_PATH, 'utf8');

var has = Object.prototype.hasOwnProperty;

module.exports = pack;
module.exports.getBundle = getBundle;

function getPackage(entryfile) {
  return fs.isFile(entryfile).then(function (isFile) {
    if (isFile) return entryfile;
    else return path.resolve(entryfile, 'package.json');
  })
  .then(function (entry) {
    return fs
    .readFile(entry, 'utf8')
    .then(JSON.parse)
    .then(function (pkg) {
      return {
        path: entry,
        pkg: pkg
      };
    });
  });
}

function addDeps(to, deps) {
  if (Array.isArray(deps)) {
    deps.forEach(function (dep) {
      to.push(dep);
    });
  }
  else if (typeof deps === 'string') {
    to.push(deps);
  }
  else if (deps) {
    addDeps(to, Object.keys(deps));
  }
}

// cfg = {
//   noDependencies // do not pack dependencies with it
//   useTitaniumPlatformResolve // TODO
//   debug // build source maps
// }

function getBundle(entry, cfg) {
  return getPackage(entry).then(function (data) {

    var entry = path.dirname(data.path);
    var pkg = data.pkg;
    var titaniumManifest = pkg.titaniumManifest || {};

    var moduleid = titaniumManifest.moduleid || pkg.name;

    var opts = pkg.titaniumifier || pkg.npmifier || pkg.browserify || {};

    opts.extensions || (opts.extensions = [ '.js', '.json' ]);
    opts.transforms || (opts.transforms = []);
    opts.ignores || (opts.ignores = []);
    opts.externals || (opts.externals = []);

    var addExternals = addDeps.bind(null, opts.externals);

    addExternals(pkg.peerDependencies);
    addExternals(pkg.nativeDependencies);

    if (cfg.noDependencies) {
      addExternals(pkg.dependencies);
      addExternals(pkg.devDependencies);
      addExternals(pkg.optionalDependencies);
    }

    opts.ignoreMissing = !!opts.ignoreMissing;

    var b = browserify({
      builtins: BUILTINS,
      debug: cfg.debug,
      extensions: opts.extensions,
      insertGlobalVars: GLOBAL_VARS,
      ignoreMissing: false,
      standalone: (cfg.standalone === false) ? undefined : moduleid,
      prelude: PRELUDE_SRC,
      preludePath: PRELUDE_PATH
    });

    b.plugin(fixResolver, {
      resolve: titaniumResolve
    });

    if (Array.isArray(opts.transforms)) {
      opts.transforms.forEach(function (transform) {
        b.transform(transform);
      });
    }
    else {
      Object.keys(opts.transforms).forEach(function (transform) {
        b.transform(transform, opts.transforms[ transform ]);
      });
    }

    opts.ignores.forEach(function (ignore) {
      b.ignore(ignore);
    });

    opts.externals.forEach(function (external) {
      b.exclude(external);
    });

    if (cfg.useTitaniumPlatformResolve) {
      TODO;
      /*b.transform(titaniumPlatformResolve.createTransform({
        platforms: [ build.platformName ],
        extensions: opts.extensions
      }));*/
    }

    return {
      entry: entry,
      pkg: pkg,
      opts: opts,
      bundle: b
    };
  });
}

function pack(entry, cfg, callback) {
  cfg || (cfg = {});
  var promise = getBundle(entry, cfg).then(function (data) {

    var entry = data.entry;
    var pkg = data.pkg;
    var b = data.bundle;
    var opts = data.opts;

    var entrypoint = path.resolve(entry, pkg.main || 'index.js');

    var passedPackages = {};
    var nativeDependencies = clone(pkg.nativeDependencies);

    b.on('package', function (pkg) {
      // consider only interesting packages
      if (!pkg.nativeDependencies) return;
      // pass only once per package
      if (has.call(passedPackages, pkg.__dirname)) return;
      passedPackages[ pkg.__dirname ] = true;
      // merge dependencies
      Object.keys(pkg.nativeDependencies).forEach(function (key) {
        // TODO better error/collision check
        if (has.call(nativeDependencies, key)) return;
        nativeDependencies[ key ] = pkg.nativeDependencies[ key ];
      });
    });

    return new Promise(function (resolve, reject) {
      titaniumResolve(entrypoint, {
        paths: b._mdeps.paths,
        modules: b._mdeps.options.modules,
        filename: path.resolve(entry, 'package.json'),
        extensions: opts.extensions
      }, function (err, result) {
        if (err) return reject(err);

        b.add(result);

        b.bundle(function (err, result) {
          if (err) return reject(err);
          resolve(result);
        });
      });
    })
    .then(function (result) {
      return {
        source: result,
        nativeDependencies: nativeDependencies
      };
    });
  });

  if (callback) {
    promise.done(callback.bind(null, null), callback.bind(null));
  }

  return promise;
}

function clone(obj) {
  return (obj == null) ? {} : Object.keys(obj).reduce(function (memo, key) {
    memo[ key ] = obj[ key ];
    return memo;
  }, {});
}

function fixResolver(b, opts) {
  b._mdeps.resolver = (opts.resolve || b._mdeps.resolver);
}
<commit_msg>You can now export `require` as the module<commit_after>'use strict';

var Promise = require('bluebird');
var browserify = require('browserify');
var path = require('path');
var titaniumResolve = require('titanium-resolve');

var fs = require('./util/fs');

var BUILTINS = require('./builtins');
var GLOBAL_VARS = require('./globals');
var PRELUDE_PATH = path.resolve(__dirname, 'util', '_prelude.js');
var PRELUDE_SRC = require('fs').readFileSync(PRELUDE_PATH, 'utf8');

var has = Object.prototype.hasOwnProperty;

module.exports = pack;
module.exports.getBundle = getBundle;

function getPackage(entryfile) {
  return fs.isFile(entryfile).then(function (isFile) {
    if (isFile) return entryfile;
    else return path.resolve(entryfile, 'package.json');
  })
  .then(function (entry) {
    return fs
    .readFile(entry, 'utf8')
    .then(JSON.parse)
    .then(function (pkg) {
      return {
        path: entry,
        pkg: pkg
      };
    });
  });
}

function addDeps(to, deps) {
  if (Array.isArray(deps)) {
    deps.forEach(function (dep) {
      to.push(dep);
    });
  }
  else if (typeof deps === 'string') {
    to.push(deps);
  }
  else if (deps) {
    addDeps(to, Object.keys(deps));
  }
}

// cfg = {
//   noDependencies // do not pack dependencies with it
//   useTitaniumPlatformResolve // TODO
//   debug // build source maps
//   standalone //
//   exportRequire //
// }

function getBundle(entry, cfg) {
  return getPackage(entry).then(function (data) {

    var entry = path.dirname(data.path);
    var pkg = data.pkg;
    var titaniumManifest = pkg.titaniumManifest || {};

    var moduleid = titaniumManifest.moduleid || pkg.name;

    var opts = pkg.titaniumifier || pkg.npmifier || pkg.browserify || {};

    opts.extensions || (opts.extensions = [ '.js', '.json' ]);
    opts.transforms || (opts.transforms = []);
    opts.ignores || (opts.ignores = []);
    opts.externals || (opts.externals = []);

    var addExternals = addDeps.bind(null, opts.externals);

    addExternals(pkg.peerDependencies);
    addExternals(pkg.nativeDependencies);

    if (cfg.noDependencies) {
      addExternals(pkg.dependencies);
      addExternals(pkg.devDependencies);
      addExternals(pkg.optionalDependencies);
    }

    opts.ignoreMissing = !!opts.ignoreMissing;

    var b = browserify({
      builtins: BUILTINS,
      debug: cfg.debug,
      extensions: opts.extensions,
      externalRequireName: cfg.exportRequire ? 'module.exports' : undefined,
      insertGlobalVars: GLOBAL_VARS,
      ignoreMissing: false,
      standalone: (cfg.standalone === false) ? undefined : moduleid,
      prelude: PRELUDE_SRC,
      preludePath: PRELUDE_PATH
    });

    b.plugin(fixResolver, {
      resolve: titaniumResolve
    });

    if (Array.isArray(opts.transforms)) {
      opts.transforms.forEach(function (transform) {
        b.transform(transform);
      });
    }
    else {
      Object.keys(opts.transforms).forEach(function (transform) {
        b.transform(transform, opts.transforms[ transform ]);
      });
    }

    opts.ignores.forEach(function (ignore) {
      b.ignore(ignore);
    });

    opts.externals.forEach(function (external) {
      b.exclude(external);
    });

    if (cfg.useTitaniumPlatformResolve) {
      TODO;
      /*b.transform(titaniumPlatformResolve.createTransform({
        platforms: [ build.platformName ],
        extensions: opts.extensions
      }));*/
    }

    return {
      entry: entry,
      pkg: pkg,
      opts: opts,
      bundle: b
    };
  });
}

function pack(entry, cfg, callback) {
  cfg || (cfg = {});
  var promise = getBundle(entry, cfg).then(function (data) {

    var entry = data.entry;
    var pkg = data.pkg;
    var b = data.bundle;
    var opts = data.opts;

    var entrypoint = path.resolve(entry, pkg.main || 'index.js');

    var passedPackages = {};
    var nativeDependencies = clone(pkg.nativeDependencies);

    b.on('package', function (pkg) {
      // consider only interesting packages
      if (!pkg.nativeDependencies) return;
      // pass only once per package
      if (has.call(passedPackages, pkg.__dirname)) return;
      passedPackages[ pkg.__dirname ] = true;
      // merge dependencies
      Object.keys(pkg.nativeDependencies).forEach(function (key) {
        // TODO better error/collision check
        if (has.call(nativeDependencies, key)) return;
        nativeDependencies[ key ] = pkg.nativeDependencies[ key ];
      });
    });

    return new Promise(function (resolve, reject) {
      titaniumResolve(entrypoint, {
        paths: b._mdeps.paths,
        modules: b._mdeps.options.modules,
        filename: path.resolve(entry, 'package.json'),
        extensions: opts.extensions
      }, function (err, result) {
        if (err) return reject(err);

        b.add(result);

        b.bundle(function (err, result) {
          if (err) return reject(err);
          resolve(result);
        });
      });
    })
    .then(function (result) {
      return {
        source: result,
        nativeDependencies: nativeDependencies
      };
    });
  });

  if (callback) {
    promise.done(callback.bind(null, null), callback.bind(null));
  }

  return promise;
}

function clone(obj) {
  return (obj == null) ? {} : Object.keys(obj).reduce(function (memo, key) {
    memo[ key ] = obj[ key ];
    return memo;
  }, {});
}

function fixResolver(b, opts) {
  b._mdeps.resolver = (opts.resolve || b._mdeps.resolver);
}
<|endoftext|>


<commit_before>var creep_work5 = {

    /** @param {Creep} creep **/
    run: function(creep, thisSpawn) {

        //wew lad
        /*if (!creep.room.controller.sign) {
            if(creep.pos.isNearTo(creep.room.controller)) {
                creep.signController(creep.room.controller, 'This is, by far, the most kupo room I\'ve ever seen!');
            }
        }*/
        if (creep.carry.energy > 0) {
            //All creeps check for road under them and repair if needed.
            var someStructure = creep.pos.lookFor(LOOK_STRUCTURES);
            if (someStructure.length && (someStructure[0].hitsMax - someStructure[0].hits >= 600)) {
                creep.repair(someStructure[0]);
            }
        }

        if (creep.memory.priority == 'miner' || creep.memory.priority == 'minerNearDeath') {
            if (creep.ticksToLive <= 60) {
                creep.memory.priority = 'minerNearDeath';
                creep.memory.jobSpecific = creep.memory.jobSpecific + 'NearDeath';
            }
            //Creep will immediately harvest and store mined materials
            var storageTarget = Game.getObjectById(creep.memory.linkSource);
            var mineTarget = Game.getObjectById(creep.memory.mineSource);
            if (mineTarget && storageTarget) {
                if (creep.harvest(mineTarget) == ERR_NOT_IN_RANGE) {
                    creep.moveTo(mineTarget, {
                        reusePath: 20
                    });
                } else {
                    if (creep.transfer(storageTarget, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                        creep.moveTo(storageTarget, {
                            reusePath: 20
                        });
                    }
                }
            }
        } else if (creep.memory.priority == 'upgrader' || creep.memory.priority == 'upgraderNearDeath') {
            if (creep.ticksToLive <= 60) {
                creep.memory.priority = 'upgraderNearDeath';
            }

            if (creep.upgradeController(creep.room.controller) == ERR_NOT_IN_RANGE) {
                creep.moveTo(creep.room.controller, {
                    reusePath: 20
                });
            }

            var linkTarget = Game.getObjectById(creep.memory.linkSource);
            if (linkTarget) {
                if (linkTarget.energy > 0) {
                    if (creep.withdraw(linkTarget, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                        creep.moveTo(linkTarget, {
                            reusePath: 20
                        });
                    }
                } else if (creep.carry.energy == 0) {
                    //Get from storage instead
                    var storageTarget = Game.getObjectById(creep.memory.storageSource);
                    if (storageTarget) {
                        if (storageTarget.store[RESOURCE_ENERGY] >= 150) {
                            if (creep.withdraw(storageTarget, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                                creep.moveTo(storageTarget, {
                                    reusePath: 20
                                });
                            }
                        }
                    }
                }
            } else if (creep.carry.energy == 0) {
                var storageTarget = Game.getObjectById(creep.memory.storageSource);
                if (storageTarget) {
                    if (storageTarget.store[RESOURCE_ENERGY] >= 150) {
                        if (creep.withdraw(storageTarget, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                            creep.moveTo(storageTarget, {
                                reusePath: 20
                            });
                        }
                    }
                }
            }
        } else if (creep.memory.priority == 'mule' || creep.memory.priority == 'muleNearDeath') {
            if (creep.ticksToLive <= 60) {
                creep.memory.priority = 'muleNearDeath';
            }
            if (_.sum(creep.carry) == 0) {
                creep.memory.structureTarget = undefined;
                var storageTarget = Game.getObjectById(creep.memory.storageSource);
                if (storageTarget) {
                    if (storageTarget.store[RESOURCE_ENERGY] >= 50) {
                        //Get from container
                        if (creep.withdraw(storageTarget, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                            creep.moveTo(storageTarget, {
                                reusePath: 20
                            });
                        }
                    } else {
                        if (!creep.pos.isNearTo(storageTarget)) {
                            creep.moveTo(storageTarget, {
                                reusePath: 20
                            });
                        }

                    }
                }
            } else if (_.sum(creep.carry) > 0) {
                var savedTarget = Game.getObjectById(creep.memory.structureTarget)

                if (savedTarget) {
                    if (creep.build(savedTarget) == ERR_INVALID_TARGET) {
                        if (creep.memory.lookForNewRampart) {
                            creep.memory.structureTarget = undefined;
                            creep.memory.lookForNewRampart = undefined;
                            var newRampart = creep.pos.findClosestByRange(FIND_STRUCTURES, {
                                filter: (structure) => (structure.structureType == STRUCTURE_RAMPART) && (structure.hits == 1)
                            });
                            if (newRampart) {
                                creep.memory.structureTarget = newRampart.id;
                                if (creep.repair(newRampart) == ERR_NOT_IN_RANGE) {
                                    creep.moveTo(newRampart, {
                                        reusePath: 20
                                    });
                                }
                            }
                        } else if (savedTarget.structureType != STRUCTURE_CONTAINER && savedTarget.structureType != STRUCTURE_STORAGE && savedTarget.structureType != STRUCTURE_CONTROLLER) {
                            //Storing in spawn/extension/tower
                            if (creep.transfer(savedTarget, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                                creep.moveTo(savedTarget, {
                                    reusePath: 20
                                });
                            } else {
                                //assumed OK, drop target
                                creep.memory.structureTarget = undefined;
                            }
                        } else {
                            //Do repair for new ramparts
                            if (creep.repair(savedTarget) == ERR_INVALID_TARGET) {
                                //Upgrading controller
                                if (creep.upgradeController(creep.room.controller) == ERR_NOT_IN_RANGE) {
                                    creep.moveTo(creep.room.controller, {
                                        reusePath: 20
                                    });
                                }
                            } else if (creep.repair(savedTarget) != OK) {
                                creep.memory.structureTarget = undefined;
                            }
                        }
                    } else {
                        if (creep.build(savedTarget) == ERR_NOT_IN_RANGE) {
                            creep.moveTo(savedTarget, {
                                reusePath: 20
                            });
                        } else if (creep.build(savedTarget) != OK) {
                            creep.memory.structureTarget = undefined;
                        }
                    }
                } else {
                    creep.memory.structureTarget = undefined;
                }
                //Immediately find a new target if previous transfer worked
                if (!creep.memory.structureTarget) {
                    var targets = creep.pos.findClosestByRange(FIND_STRUCTURES, {
                        filter: (structure) => {
                            return (structure.structureType == STRUCTURE_EXTENSION ||
                                structure.structureType == STRUCTURE_SPAWN) && structure.energy < structure.energyCapacity;
                        }
                    });
                    if (targets) {
                        creep.memory.structureTarget = targets.id;
                        if (creep.transfer(targets, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                            creep.moveTo(targets);
                        } else {
                            creep.memory.structureTarget = undefined;
                        }
                    } else {
                        targets3 = creep.pos.findClosestByRange(FIND_STRUCTURES, {
                            filter: (structure) => {
                                return (structure.structureType == STRUCTURE_TOWER) && (structure.energy < structure.energyCapacity);
                            }
                        });
                        if (targets3) {
                            creep.memory.structureTarget = targets3.id;
                            if (creep.transfer(targets3, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                                creep.moveTo(targets3);
                            } else {
                                creep.memory.structureTarget = undefined;
                            }
                        } else {
                            //Store in terminal
                            terminalTarget = Game.getObjectById(creep.memory.terminalID)
                            if (terminalTarget) {
                                if (terminalTarget.store[RESOURCE_ENERGY] < 50000) {
                                    creep.memory.structureTarget = terminalTarget.id;
                                    if (creep.transfer(terminalTarget, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                                        creep.moveTo(terminalTarget, {
                                            reusePath: 20
                                        });
                                    }
                                } else {
                                    terminalTarget = undefined;
                                }
                            }
                            if (!terminalTarget) {
                                //Build
                                var targets2 = creep.pos.findClosestByRange(FIND_CONSTRUCTION_SITES);
                                if (targets2) {
                                    creep.memory.structureTarget = targets2.id;
                                    if (targets2.structureType == STRUCTURE_RAMPART) {
                                        creep.memory.lookForNewRampart = true;
                                    }

                                    if (creep.build(targets2) == ERR_NOT_IN_RANGE) {
                                        creep.moveTo(targets2, {
                                            reusePath: 20
                                        });
                                    }
                                } else {
                                    //Upgrade
                                    creep.memory.structureTarget = creep.room.controller.id;
                                    if (creep.upgradeController(creep.room.controller) == ERR_NOT_IN_RANGE) {
                                        creep.moveTo(creep.room.controller, {
                                            reusePath: 20
                                        });
                                    }
                                }
                            }
                        }
                    }
                }
            }
        } else if (creep.memory.priority == 'repair' || creep.memory.priority == 'repairNearDeath') {
            if (creep.ticksToLive <= 60) {
                creep.memory.priority = 'repairNearDeath';
            }

            if (_.sum(creep.carry) == 0) {
                creep.memory.structureTarget = undefined;
                //Get from storage
                var storageTarget = Game.getObjectById(creep.memory.storageSource);
                if (storageTarget) {
                    if (storageTarget.store[RESOURCE_ENERGY] >= 120) {
                        if (creep.withdraw(storageTarget, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                            creep.moveTo(storageTarget, {
                                reusePath: 20
                            });
                        }
                    } else {
                        if (!creep.pos.isNearTo(storageTarget)) {
                            creep.moveTo(storageTarget, {
                                reusePath: 20
                            });
                        }
                    }
                }
            } else if (creep.memory.structureTarget) {
                var thisStructure = Game.getObjectById(creep.memory.structureTarget);
                if (thisStructure) {
                    if (thisStructure.hits == thisStructure.hitsMax) {
                        creep.memory.structureTarget = undefined;
                    } else {
                        if (creep.repair(thisStructure) == ERR_NOT_IN_RANGE) {
                            creep.moveTo(thisStructure, {
                                reusePath: 20
                            });
                        }
                    }
                }
            } else {
                var closestDamagedStructure = creep.room.find(FIND_STRUCTURES, {
                    filter: (structure) => (structure.structureType != STRUCTURE_ROAD) && (structure.hitsMax - structure.hits >= 200)
                });
                if (closestDamagedStructure.length > 0) {
                    closestDamagedStructure.sort(repairCompare);
                    creep.memory.structureTarget = closestDamagedStructure[0].id;
                    if (creep.repair(closestDamagedStructure[0]) == ERR_NOT_IN_RANGE) {
                        creep.moveTo(closestDamagedStructure[0], {
                            reusePath: 20
                        });
                    }
                }
            }

        } else if (creep.memory.priority == 'mineralMiner') {
            var thisMineral = Game.getObjectById(creep.memory.mineralID);
            if (thisMineral.mineralAmount == 0) {
                //Nothing left to do
                creep.suicide();
            } else {
                //Creep will immediately harvest and store mined materials
                var storageTarget = Game.getObjectById(creep.memory.terminalID);
                var thisExtractor = Game.getObjectById(creep.memory.extractorID);
                if (thisExtractor.cooldown == 0) {
                    if (creep.harvest(thisMineral) == ERR_NOT_IN_RANGE) {
                        creep.moveTo(thisMineral, {
                            reusePath: 20
                        });
                    }
                }
                if (creep.transfer(storageTarget, thisMineral.mineralType) == ERR_NOT_IN_RANGE) {
                    //This should never actually fire, if ideal.
                    creep.moveTo(storageTarget);
                }
            }
        } else if (creep.memory.priority == 'salvager') {
            var sources = creep.pos.findClosestByRange(FIND_DROPPED_RESOURCES);
            if (!sources && _.sum(creep.carry) == 0) {
                //There's nothing left to do
                creep.suicide();
            } else if (sources && _.sum(creep.carry) < creep.carryCapacity) {
                if (creep.pickup(sources) == ERR_NOT_IN_RANGE) {
                    creep.moveTo(sources);
                }
            }
            if (!sources && _.sum(creep.carry) > 0 || _.sum(creep.carry) == creep.carryCapacity) {
                var storageTarget = Game.getObjectById(creep.memory.storageTarget);
                if (creep.transfer(storageTarget, Object.keys(creep.carry)[0]) == ERR_NOT_IN_RANGE) {
                    creep.moveTo(storageTarget);
                }
            }
        }
    }
};

module.exports = creep_work5;

function repairCompare(a, b) {
    if (a.hits < b.hits)
        return -1;
    if (a.hits > b.hits)
        return 1;
    return 0;
}<commit_msg>Mule lockup<commit_after>var creep_work5 = {

    /** @param {Creep} creep **/
    run: function(creep, thisSpawn) {

        //wew lad
        /*if (!creep.room.controller.sign) {
            if(creep.pos.isNearTo(creep.room.controller)) {
                creep.signController(creep.room.controller, 'This is, by far, the most kupo room I\'ve ever seen!');
            }
        }*/
        if (creep.carry.energy > 0) {
            //All creeps check for road under them and repair if needed.
            var someStructure = creep.pos.lookFor(LOOK_STRUCTURES);
            if (someStructure.length && (someStructure[0].hitsMax - someStructure[0].hits >= 600)) {
                creep.repair(someStructure[0]);
            }
        }

        if (creep.memory.priority == 'miner' || creep.memory.priority == 'minerNearDeath') {
            if (creep.ticksToLive <= 60) {
                creep.memory.priority = 'minerNearDeath';
                creep.memory.jobSpecific = creep.memory.jobSpecific + 'NearDeath';
            }
            //Creep will immediately harvest and store mined materials
            var storageTarget = Game.getObjectById(creep.memory.linkSource);
            var mineTarget = Game.getObjectById(creep.memory.mineSource);
            if (mineTarget && storageTarget) {
                if (creep.harvest(mineTarget) == ERR_NOT_IN_RANGE) {
                    creep.moveTo(mineTarget, {
                        reusePath: 20
                    });
                } else {
                    if (creep.transfer(storageTarget, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                        creep.moveTo(storageTarget, {
                            reusePath: 20
                        });
                    }
                }
            }
        } else if (creep.memory.priority == 'upgrader' || creep.memory.priority == 'upgraderNearDeath') {
            if (creep.ticksToLive <= 60) {
                creep.memory.priority = 'upgraderNearDeath';
            }

            if (creep.upgradeController(creep.room.controller) == ERR_NOT_IN_RANGE) {
                creep.moveTo(creep.room.controller, {
                    reusePath: 20
                });
            }

            var linkTarget = Game.getObjectById(creep.memory.linkSource);
            if (linkTarget) {
                if (linkTarget.energy > 0) {
                    if (creep.withdraw(linkTarget, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                        creep.moveTo(linkTarget, {
                            reusePath: 20
                        });
                    }
                } else if (creep.carry.energy == 0) {
                    //Get from storage instead
                    var storageTarget = Game.getObjectById(creep.memory.storageSource);
                    if (storageTarget) {
                        if (storageTarget.store[RESOURCE_ENERGY] >= 150) {
                            if (creep.withdraw(storageTarget, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                                creep.moveTo(storageTarget, {
                                    reusePath: 20
                                });
                            }
                        }
                    }
                }
            } else if (creep.carry.energy == 0) {
                var storageTarget = Game.getObjectById(creep.memory.storageSource);
                if (storageTarget) {
                    if (storageTarget.store[RESOURCE_ENERGY] >= 150) {
                        if (creep.withdraw(storageTarget, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                            creep.moveTo(storageTarget, {
                                reusePath: 20
                            });
                        }
                    }
                }
            }
        } else if (creep.memory.priority == 'mule' || creep.memory.priority == 'muleNearDeath') {
            if (creep.ticksToLive <= 60) {
                creep.memory.priority = 'muleNearDeath';
            }
            if (_.sum(creep.carry) == 0) {
                creep.memory.structureTarget = undefined;
                var storageTarget = Game.getObjectById(creep.memory.storageSource);
                if (storageTarget) {
                    if (storageTarget.store[RESOURCE_ENERGY] >= 50) {
                        //Get from container
                        if (creep.withdraw(storageTarget, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                            creep.moveTo(storageTarget, {
                                reusePath: 20
                            });
                        }
                    } else {
                        if (!creep.pos.isNearTo(storageTarget)) {
                            creep.moveTo(storageTarget, {
                                reusePath: 20
                            });
                        }

                    }
                }
            } else if (_.sum(creep.carry) > 0) {
                var savedTarget = Game.getObjectById(creep.memory.structureTarget)

                if (savedTarget) {
                    if (creep.build(savedTarget) == ERR_INVALID_TARGET) {
                        if (creep.memory.lookForNewRampart) {
                            creep.memory.structureTarget = undefined;
                            creep.memory.lookForNewRampart = undefined;
                            var newRampart = creep.pos.findClosestByRange(FIND_STRUCTURES, {
                                filter: (structure) => (structure.structureType == STRUCTURE_RAMPART) && (structure.hits == 1)
                            });
                            if (newRampart) {
                                creep.memory.structureTarget = newRampart.id;
                                if (creep.repair(newRampart) == ERR_NOT_IN_RANGE) {
                                    creep.moveTo(newRampart, {
                                        reusePath: 20
                                    });
                                }
                            }
                        } else if (savedTarget.structureType != STRUCTURE_CONTAINER && savedTarget.structureType != STRUCTURE_STORAGE && savedTarget.structureType != STRUCTURE_CONTROLLER) {
                            //Storing in spawn/extension/tower
                            if (creep.transfer(savedTarget, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                                creep.moveTo(savedTarget, {
                                    reusePath: 20
                                });
                            } else {
                                //assumed OK, drop target
                                creep.memory.structureTarget = undefined;
                            }
                        } else {
                            //Upgrading controller
                            if (creep.upgradeController(creep.room.controller) == ERR_NOT_IN_RANGE) {
                                creep.moveTo(creep.room.controller, {
                                    reusePath: 20
                                });
                            }
                            //Do repair for new ramparts
                            creep.repair(savedTarget);
                        }
                    } else {
                        if (creep.build(savedTarget) == ERR_NOT_IN_RANGE) {
                            creep.moveTo(savedTarget, {
                                reusePath: 20
                            });
                        } else if (creep.build(savedTarget) != OK) {
                            creep.memory.structureTarget = undefined;
                        }
                    }
                } else {
                    creep.memory.structureTarget = undefined;
                }
                //Immediately find a new target if previous transfer worked
                if (!creep.memory.structureTarget) {
                    var targets = creep.pos.findClosestByRange(FIND_STRUCTURES, {
                        filter: (structure) => {
                            return (structure.structureType == STRUCTURE_EXTENSION ||
                                structure.structureType == STRUCTURE_SPAWN) && structure.energy < structure.energyCapacity;
                        }
                    });
                    if (targets) {
                        creep.memory.structureTarget = targets.id;
                        if (creep.transfer(targets, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                            creep.moveTo(targets);
                        } else {
                            creep.memory.structureTarget = undefined;
                        }
                    } else {
                        targets3 = creep.pos.findClosestByRange(FIND_STRUCTURES, {
                            filter: (structure) => {
                                return (structure.structureType == STRUCTURE_TOWER) && (structure.energy < structure.energyCapacity);
                            }
                        });
                        if (targets3) {
                            creep.memory.structureTarget = targets3.id;
                            if (creep.transfer(targets3, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                                creep.moveTo(targets3);
                            } else {
                                creep.memory.structureTarget = undefined;
                            }
                        } else {
                            //Store in terminal
                            terminalTarget = Game.getObjectById(creep.memory.terminalID)
                            if (terminalTarget) {
                                if (terminalTarget.store[RESOURCE_ENERGY] < 50000) {
                                    creep.memory.structureTarget = terminalTarget.id;
                                    if (creep.transfer(terminalTarget, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                                        creep.moveTo(terminalTarget, {
                                            reusePath: 20
                                        });
                                    }
                                } else {
                                    terminalTarget = undefined;
                                }
                            }
                            if (!terminalTarget) {
                                //Build
                                var targets2 = creep.pos.findClosestByRange(FIND_CONSTRUCTION_SITES);
                                if (targets2) {
                                    creep.memory.structureTarget = targets2.id;
                                    if (targets2.structureType == STRUCTURE_RAMPART) {
                                        creep.memory.lookForNewRampart = true;
                                    }

                                    if (creep.build(targets2) == ERR_NOT_IN_RANGE) {
                                        creep.moveTo(targets2, {
                                            reusePath: 20
                                        });
                                    }
                                } else {
                                    //Upgrade
                                    creep.memory.structureTarget = creep.room.controller.id;
                                    if (creep.upgradeController(creep.room.controller) == ERR_NOT_IN_RANGE) {
                                        creep.moveTo(creep.room.controller, {
                                            reusePath: 20
                                        });
                                    }
                                }
                            }
                        }
                    }
                }
            }
        } else if (creep.memory.priority == 'repair' || creep.memory.priority == 'repairNearDeath') {
            if (creep.ticksToLive <= 60) {
                creep.memory.priority = 'repairNearDeath';
            }

            if (_.sum(creep.carry) == 0) {
                creep.memory.structureTarget = undefined;
                //Get from storage
                var storageTarget = Game.getObjectById(creep.memory.storageSource);
                if (storageTarget) {
                    if (storageTarget.store[RESOURCE_ENERGY] >= 120) {
                        if (creep.withdraw(storageTarget, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                            creep.moveTo(storageTarget, {
                                reusePath: 20
                            });
                        }
                    } else {
                        if (!creep.pos.isNearTo(storageTarget)) {
                            creep.moveTo(storageTarget, {
                                reusePath: 20
                            });
                        }
                    }
                }
            } else if (creep.memory.structureTarget) {
                var thisStructure = Game.getObjectById(creep.memory.structureTarget);
                if (thisStructure) {
                    if (thisStructure.hits == thisStructure.hitsMax) {
                        creep.memory.structureTarget = undefined;
                    } else {
                        if (creep.repair(thisStructure) == ERR_NOT_IN_RANGE) {
                            creep.moveTo(thisStructure, {
                                reusePath: 20
                            });
                        }
                    }
                }
            } else {
                var closestDamagedStructure = creep.room.find(FIND_STRUCTURES, {
                    filter: (structure) => (structure.structureType != STRUCTURE_ROAD) && (structure.hitsMax - structure.hits >= 200)
                });
                if (closestDamagedStructure.length > 0) {
                    closestDamagedStructure.sort(repairCompare);
                    creep.memory.structureTarget = closestDamagedStructure[0].id;
                    if (creep.repair(closestDamagedStructure[0]) == ERR_NOT_IN_RANGE) {
                        creep.moveTo(closestDamagedStructure[0], {
                            reusePath: 20
                        });
                    }
                }
            }

        } else if (creep.memory.priority == 'mineralMiner') {
            var thisMineral = Game.getObjectById(creep.memory.mineralID);
            if (thisMineral.mineralAmount == 0) {
                //Nothing left to do
                creep.suicide();
            } else {
                //Creep will immediately harvest and store mined materials
                var storageTarget = Game.getObjectById(creep.memory.terminalID);
                var thisExtractor = Game.getObjectById(creep.memory.extractorID);
                if (thisExtractor.cooldown == 0) {
                    if (creep.harvest(thisMineral) == ERR_NOT_IN_RANGE) {
                        creep.moveTo(thisMineral, {
                            reusePath: 20
                        });
                    }
                }
                if (creep.transfer(storageTarget, thisMineral.mineralType) == ERR_NOT_IN_RANGE) {
                    //This should never actually fire, if ideal.
                    creep.moveTo(storageTarget);
                }
            }
        } else if (creep.memory.priority == 'salvager') {
            var sources = creep.pos.findClosestByRange(FIND_DROPPED_RESOURCES);
            if (!sources && _.sum(creep.carry) == 0) {
                //There's nothing left to do
                creep.suicide();
            } else if (sources && _.sum(creep.carry) < creep.carryCapacity) {
                if (creep.pickup(sources) == ERR_NOT_IN_RANGE) {
                    creep.moveTo(sources);
                }
            }
            if (!sources && _.sum(creep.carry) > 0 || _.sum(creep.carry) == creep.carryCapacity) {
                var storageTarget = Game.getObjectById(creep.memory.storageTarget);
                if (creep.transfer(storageTarget, Object.keys(creep.carry)[0]) == ERR_NOT_IN_RANGE) {
                    creep.moveTo(storageTarget);
                }
            }
        }
    }
};

module.exports = creep_work5;

function repairCompare(a, b) {
    if (a.hits < b.hits)
        return -1;
    if (a.hits > b.hits)
        return 1;
    return 0;
}<|endoftext|>


<commit_before>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require dataTables/jquery.dataTables
//= require dataTables/bootstrap/3/jquery.dataTables.bootstrap
//= require chartkick
//= require turbolinks
//= require bootstrap-sprockets
//= require_tree .
<commit_msg>adding gems and assets back after successful heroku deploy<commit_after>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require dataTables/jquery.dataTables
//= require chartkick
//= require turbolinks
//= require bootstrap-sprockets
//= require_tree .
<|endoftext|>


<commit_before>/*
  The following comments are parsed by Gulp include
  (https://www.npmjs.com/package/gulp-include) which uses
  Sprockets-style (https://github.com/sstephenson/sprockets)
  directives to concatenate multiple Javascript files into one.
*/
//= include ../../../node_modules/govuk_frontend_toolkit/javascripts/vendor/polyfills/bind.js
//= include ../../../bower_components/jquery/dist/jquery.js
//= include ../../../bower_components/hogan/web/builds/3.0.2/hogan-3.0.2.js
//= include ../../../bower_components/d3/d3.js
//= include ../../../bower_components/c3/c3.js
//= include ../../../bower_components/digitalmarketplace-frontend-toolkit/toolkit/javascripts/list-entry.js
//= include ../../../bower_components/digitalmarketplace-frontend-toolkit/toolkit/javascripts/word-counter.js
//= include ../../../node_modules/govuk_frontend_toolkit/javascripts/govuk/selection-buttons.js
//= include _selection-buttons.js
//= include _scroll-through-statistics.js
//= include _tables-to-charts.js
//= include ../../../bower_components/digitalmarketplace-frontend-toolkit/toolkit/javascripts/module-loader.js
<commit_msg>Compensate for missing trailing semicolon<commit_after>/*
  The following comments are parsed by Gulp include
  (https://www.npmjs.com/package/gulp-include) which uses
  Sprockets-style (https://github.com/sstephenson/sprockets)
  directives to concatenate multiple Javascript files into one.
*/
//= include ../../../node_modules/govuk_frontend_toolkit/javascripts/vendor/polyfills/bind.js
//= include ../../../bower_components/jquery/dist/jquery.js
//= include ../../../bower_components/hogan/web/builds/3.0.2/hogan-3.0.2.js
//= include ../../../bower_components/d3/d3.js
//= include ../../../bower_components/c3/c3.js
//= include ../../../bower_components/digitalmarketplace-frontend-toolkit/toolkit/javascripts/list-entry.js
//= include ../../../bower_components/digitalmarketplace-frontend-toolkit/toolkit/javascripts/word-counter.js
//= include ../../../node_modules/govuk_frontend_toolkit/javascripts/govuk/selection-buttons.js

; // JavaScript in the govuk_frontend_toolkit doesn't have trailing semicolons

//= include _selection-buttons.js
//= include _scroll-through-statistics.js
//= include _tables-to-charts.js
//= include ../../../bower_components/digitalmarketplace-frontend-toolkit/toolkit/javascripts/module-loader.js
<|endoftext|>