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

import PageHeader from './page_header';
import GuildsTable from './guilds_table';
import {globalState} from '../state';

class DashboardGuildsList extends Component {
  constructor() {
    super();
    this.state = {guilds: null};
  }

  componentWillMount() {
    globalState.getCurrentUser().then((user) => {
      user.getGuilds().then((guilds) => {
        this.setState({guilds});
      });
    });
  }

  render() {
    return (

          Guilds

          <GuildsTable guilds={this.state.guilds}/>

    );
  }
}

class StatsPanel extends Component {
  render () {
    const panelClass = `panel panel-${this.props.color}`;
    const iconClass = `fa fa-${this.props.icon} fa-5x`;

    return (

{this.props.data || 'N/A'}

{this.props.text}

    );
  }
}

class Stats extends Component {
  constructor() {
    super();
  //   this.getStuff();
  // }

  // async getStuff() {
  //   await globalState.getCurrentUser();
  //   await globalState.getStats();
  }

  async statsPromise() {
    await globalState.getStats()
    return true
  }

  render() {
    let statsPanels = [];

    if (globalState.user.admin) {
      if (this.statsPromise()) {
        statsPanels.push(
            <StatsPanel color='primary' icon='comments' data={globalState.stats.messages} text='Messages' key='messages' />
        );
        statsPanels.push(
            <StatsPanel color='green' icon='server' data={globalState.stats.guilds} text='Guilds' key='guilds' />
        );
        statsPanels.push(
            <StatsPanel color='yellow' icon='user' data={globalState.stats.users} text='Users' key='users' />
        );
        statsPanels.push(
            <StatsPanel color='red' icon='hashtag' data={globalState.stats.channels} text='Channels' key='channels' />
        );
      }
    }

    return (

        {statsPanels}

    );
  }
}

class Dashboard extends Component {
  render() {
		return (

        <PageHeader name="Dashboard" />
        <Stats />

            <DashboardGuildsList />

    );
  }
}

export default Dashboard;
<commit_msg>[frontend] oosdfd<commit_after>import React, { Component } from 'react';

import PageHeader from './page_header';
import GuildsTable from './guilds_table';
import {globalState} from '../state';

class DashboardGuildsList extends Component {
  constructor() {
    super();
    this.state = {guilds: null};
  }

  componentWillMount() {
    globalState.getCurrentUser().then((user) => {
      user.getGuilds().then((guilds) => {
        this.setState({guilds});
      });
    });
  }

  render() {
    return (

          Guilds

          <GuildsTable guilds={this.state.guilds}/>

    );
  }
}

class StatsPanel extends Component {
  render () {
    const panelClass = `panel panel-${this.props.color}`;
    const iconClass = `fa fa-${this.props.icon} fa-5x`;

    return (

{this.props.data || 'N/A'}

{this.props.text}

    );
  }
}

class Stats extends Component {
  constructor() {
    super();
  //   this.getStuff();
  // }

  // async getStuff() {
  //   await globalState.getCurrentUser();
  //   await globalState.getStats();
  }

  async stats(type) {
    await globalState.getStats();
    return globalState.stats[type];
  }

  render() {
    let statsPanels = [];

    if (globalState.user.admin) {
      statsPanels.push(
          <StatsPanel color='primary' icon='comments' data={stats(messages)} text='Messages' key='messages' />
      );
      statsPanels.push(
          <StatsPanel color='green' icon='server' data={stats(guilds)} text='Guilds' key='guilds' />
      );
      statsPanels.push(
          <StatsPanel color='yellow' icon='user' data={stats(users)} text='Users' key='users' />
      );
      statsPanels.push(
          <StatsPanel color='red' icon='hashtag' data={stats(channels)} text='Channels' key='channels' />
      );
    }

    return (

        {statsPanels}

    );
  }
}

class Dashboard extends Component {
  render() {
		return (

        <PageHeader name="Dashboard" />
        <Stats />

            <DashboardGuildsList />

    );
  }
}

export default Dashboard;
<|endoftext|>


<commit_before>// @flow
import createSubstyle from './createSubstyle'
import defaultStyle from './defaultStyle'
import EnhancerProvider from './EnhancerProvider'

export { createSubstyle, EnhancerProvider, defaultStyle }

export default defaultStyle()
<commit_msg>export Substyle flow type<commit_after>// @flow
import createSubstyle from './createSubstyle'
import defaultStyle from './defaultStyle'
import EnhancerProvider from './EnhancerProvider'
import type { SubstyleT as Substyle } from './types'

export { createSubstyle, EnhancerProvider, defaultStyle }

export default defaultStyle()
export type { Substyle }
<|endoftext|>


<commit_before>IconEnum = {
	ARROW: 0,
	NUMBER: 1,
	FIRE: 2,
	GIFT: 3
	// Future enhancements - new icons: reveal area, moves, shuffle
};

var Icon = Backbone.Model.extend({});

var Tile = Backbone.Model.extend({

	initialize: function() {

		this.revealed = false;
		this.dead = false;
	}
});

var TileCollection = Backbone.Collection.extend({

	model: Tile
});

var Grid = Backbone.Model.extend({

	grid: new TileCollection(),

	initialize: function() {

		for (var y = 7; y >= 1; y--)
			for (var x = 1; x <= 9; x++)
				this.grid.add(new Tile({ x: x, y: y }));

		this.populateIcons();
	},

	populateIcons: function() {

		var self = this;

		var tiles = this.grid.models.slice();

		var giftTile = addIconToRandomTile(IconEnum.GIFT, tiles);

		for (var i = 0; i < this.get("fires"); i++)
			addIconToRandomTile(IconEnum.FIRE, tiles);

		for (var i = 0; i < this.get("numbers"); i++)
			addNumberIconToRandomSuitableTile(tiles);

		for (var i = 0; i < this.get("arrows"); i++)
			addIconToRandomTile(IconEnum.ARROW, tiles);

		function addNumberIconToRandomSuitableTile(tiles) {

			// Limit the distance from the gift that number tiles can be.
			var suitableTiles = _.filter(tiles, function(tile) { return (self.getDistanceFromGiftTile(tile, giftTile) <= Math.round(Math.sqrt(self.grid.models.length))) });

			var tile = addIconToRandomTile(IconEnum.NUMBER, suitableTiles);

			tiles.splice(tiles.indexOf(tile), 1);
		}

		function addIconToRandomTile(icon, tiles) {

			var randomLocation = Math.floor(Math.random() * (tiles.length - 1));
			var tile = tiles[randomLocation];

			var value;
			switch(icon) {

				case IconEnum.ARROW:  value = self.getDirectionToGift(tile, giftTile); break;
				case IconEnum.NUMBER: value = self.getDistanceFromGiftTile(tile, giftTile); break;
				default:              value = null;
			}

			tile.set("icon", new Icon({ type: icon, value: value }));
			tiles.splice(randomLocation, 1);

			return tile;
		}
	},

	getDirectionToGift: function(tile, giftTile) {

		var useLeftRight;

		// Determine whether this arrow will be left/right or up/down (sometimes there's no choice)
		if (tile.get("x") == giftTile.get("x")) {

			useLeftRight = false;
		}
		else if (tile.get("y") == giftTile.get("y")) {

			useLeftRight = true;
		}
		else {

			useLeftRight = (Math.random() > 0.5);
		}

		if (useLeftRight) {

			return (tile.get("x") > giftTile.get("x") ? "left" : "right");
		}
		else {

			return (tile.get("y") > giftTile.get("y") ? "down" : "up");
		}
	},

	getDistanceFromGiftTile: function(tile, giftTile) {

		return (Math.abs(tile.get("x") - giftTile.get("x")) + Math.abs(tile.get("y") - giftTile.get("y")));
	}
});

var TileView = Backbone.Marionette.ItemView.extend({

	className: "grid-cell",

	events: {
		"click": "tileClicked",
		"tap": "tileClicked"
	},

	render: function() {

		if (this.model.get("revealed")) {

			this.$el.addClass("revealed");
			this.addContent();
		}
		else if (this.model.get("dead")) {

			this.$el.addClass("dead");
		}
		else {

			this.$el.removeClass("revealed");

			// Remove content
			this.$el.removeClass("bad neutral good");
			this.$el.html("");
		}

		return this;
	},

	tileClicked: function() {

		if (!this.model.get("revealed")) {

			this.reveal();
			this.performAction();
			this.trigger("tile:revealed");
		}
	},

	reveal: function() {

		this.model.set("revealed", true);
		this.render();
	},

	hide: function() {

		if (this.model.get("revealed")) {

			this.model.set("revealed", false);
			this.render();
		}
	},

	addContent: function() {},

	performAction: function() {}
});

var EmptyTileView = TileView.extend({

	addContent: function() {

		this.$el.addClass("neutral");
	}
});

var GiftTileView = TileView.extend({

	addContent: function() {

		this.$el.addClass("gift");
		this.$el.html('');
	},

	tileClicked: function() {

		if (!this.model.get("revealed")) {

			this.reveal();
			this.performAction();
		}
	},

	reveal: function() {

		TileView.prototype.reveal.call(this);

		this.trigger("win");
	},

	performAction: function() {

		this.$(".glyphicon").addClass("animated flash");
	}
});

var FireTileView = TileView.extend({

	addContent: function() {

		this.$el.addClass("bad");
		this.$el.html('');
	},

	hide: function() {

		TileView.prototype.hide.call(this);

		this.$el.removeClass("animated pulse");
	},

	performAction: function() {

		var self = this;

		this.$el.addClass("animated pulse");

		this.collection.each(function(tileView) {

			// Hide all tiles except this one
			if (tileView != self) tileView.hide();
		});
	}
});

var ArrowTileView = TileView.extend({

	addContent: function() {

		this.$el.addClass("good");
		this.$el.html('');
	}
});

var NumberTileView = TileView.extend({

	addContent: function() {

		this.$el.addClass("good");
		this.$el.html(this.model.get("icon").get("value"));
	}
});

var GridView = Backbone.Marionette.CollectionView.extend({

	id: "#game-grid",

	className: "grid animated",

	childView: TileView,

	events: {
		"click .grid-cell": "tileClicked"
	},

	onRender: function() {

		// Wrap cells in a .grid-row every 9 cells
		var cells = this.$el.children();

		for(var i = 0; i < cells.length; i += 9)
			cells.slice(i, i + 9).wrapAll('
');
	},

	buildChildView: function(child, ChildViewClass, childViewOptions) {

		var icon = child.get("icon") ? child.get("icon").get("type") : null;

		var options = _.extend({ model: child, collection: this.children }, childViewOptions);

		switch (icon) {

			case IconEnum.FIRE:   return new FireTileView(options);
			case IconEnum.ARROW:  return new ArrowTileView(options);
			case IconEnum.NUMBER: return new NumberTileView(options);
			case IconEnum.GIFT:   return new GiftTileView(options);
			default:              return new EmptyTileView(options);
		}
	},

	show: function() {

		this.$el.removeClass("fadeOut").addClass("fadeIn");
		this.render();
	},

	hide: function() {

		this.$el.removeClass("fadeIn").addClass("fadeOut");
	},

	revealAll: function() {

		var self = this;

		var delay = 0;

		this.children.each(function(tile) {

			setTimeout(function() {

				if(!tile.model.get("revealed"))
					tile.reveal();

				if (tile === self.children.last())
					self.trigger("end");

			}, delay);

			delay += 75;
		});
	},

	onChildviewTileRevealed: function() {

		this.trigger("tile:revealed");
	},

	onChildviewWin: function() {

		this.trigger("win");
	}
});

var StatsView = Backbone.View.extend({

	id: "stats",

	className: "stats-panel animated",

	template: _.template($("#template-stats").html()),

	render: function() {

		this.$el.html(this.template(this.model.attributes));
		return this;
	},

	show: function() {

		this.$el.removeClass("fadeOut").addClass("fadeIn");
		this.render();
	},

	hide: function() {

		this.$el.removeClass("fadeIn").addClass("fadeOut");
	},
});
var App = Backbone.Model.extend({

	initialize: function() {

		var self = this;

		this.set({
			won: false,
			restarting: false,
			moves: 25,
			fires: 4,
			arrows: 5,
			numbers: 5
		});

		this.set({ movesRemaining: self.get("moves") });
	}
});

var EndDialogView = Backbone.View.extend({

	id: "end-dialog",

	className: "animated fadeIn",

	template: _.template($("#template-end-dialog").html()),

	render: function() {

		this.$el.html(this.template(this.model.attributes));
		return this;
	}
});

var AppView = Backbone.View.extend({

	el: "#game-container",

	model: new App(),

	events: {
		"click #restart-button": "restart"
	},

	initialize: function() {

		this.on('restart', this.restart);

		this.start();
	},

	start: function() {

		this.createGrid();
		this.createStats();

		this.stats.render();
		this.grid.show();
		this.stats.show();
	},

	createGrid: function() {

		this.grid = new GridView({ collection: new Grid({ fires: this.model.get("fires"), arrows: this.model.get("arrows"), numbers: this.model.get("numbers") }).grid })

		this.$el.children("#game").append(this.grid.$el);

		this.listenTo(this.grid, "tile:revealed", this.tileRevealed);
		this.listenTo(this.grid, "win", this.win);
	},

	createStats: function() {

		this.stats = new StatsView({ model: this.model });

		this.stats.$el.insertBefore(this.grid.$el);
	},

	tileRevealed: function() {

		this.decrementMoves();

		if (this.model.get("movesRemaining") == 0)
			this.lose();
	},

	decrementMoves: function() {

		// Just in case, prevent moves remaining from ever displaying below 0
		if (this.model.get("movesRemaining") > 0)
			this.model.set("movesRemaining", this.model.get("movesRemaining") - 1);

		this.stats.render();
	},

	restart: function() { // TODO track down and remove all old left-over objects

		var self = this;

		if (!this.model.get("restarting")) {

			this.model.set("restarting", true);

			this.disableBoard();

			this.grid.hide();
			this.stats.hide();

			setTimeout(function() {

				self.grid.remove();
				self.stats.remove();

				self.grid.collection.reset();

				self.model.destroy();
				self.model = new App();

				self.start();

			}, 1000);
		}
	},

	lose: function() {

		this.grid.children.each(function(child) {

			child.model.set("dead", true);
			child.render();
		});

		this.reveal();
	},

	win: function() {

		this.decrementMoves();

		this.model.set("won", true);

		this.reveal();
	},

	reveal: function(result) {

		var self = this;

		this.disableBoard();

		this.listenTo(this.grid, "end", this.showEndDialog);

		setTimeout(function() { self.grid.revealAll() }, 1000);
	},

	disableBoard: function() {

		this.stopListening();
		this.grid.children.each(function(child) { child.undelegateEvents() });
	},

	showEndDialog: function() {

		var self = this;

		setTimeout(function() {

			$(".stats-row, .grid-row").fadeTo("slow", 0.5);

			var end = new EndDialogView({ model: self.model });
			self.grid.$el.append(end.$el);
			end.render();

		}, 1000);
	}
});

new AppView();<commit_msg>random number of moves and special tiles each game<commit_after>function getRandomInt(min, max) {

	return Math.floor(Math.random() * (max - min + 1) + min);
}

IconEnum = {
	ARROW: 0,
	NUMBER: 1,
	FIRE: 2,
	GIFT: 3
	// Future enhancements - new icons: reveal area, moves, shuffle
};

var Icon = Backbone.Model.extend({});

var Tile = Backbone.Model.extend({

	initialize: function() {

		this.revealed = false;
		this.dead = false;
	}
});

var TileCollection = Backbone.Collection.extend({

	model: Tile
});

var Grid = Backbone.Model.extend({

	grid: new TileCollection(),

	initialize: function() {

		for (var y = 7; y >= 1; y--)
			for (var x = 1; x <= 9; x++)
				this.grid.add(new Tile({ x: x, y: y }));

		this.populateIcons();
	},

	populateIcons: function() {

		var self = this;

		var tiles = this.grid.models.slice();

		var giftTile = addIconToRandomTile(IconEnum.GIFT, tiles);

		for (var i = 0; i < this.get("fires"); i++)
			addIconToRandomTile(IconEnum.FIRE, tiles);

		for (var i = 0; i < this.get("numbers"); i++)
			addNumberIconToRandomSuitableTile(tiles);

		for (var i = 0; i < this.get("arrows"); i++)
			addIconToRandomTile(IconEnum.ARROW, tiles);

		function addNumberIconToRandomSuitableTile(tiles) {

			// Limit the distance from the gift that number tiles can be.
			var suitableTiles = _.filter(tiles, function(tile) { return (self.getDistanceFromGiftTile(tile, giftTile) <= Math.round(Math.sqrt(self.grid.models.length))) });

			var tile = addIconToRandomTile(IconEnum.NUMBER, suitableTiles);

			tiles.splice(tiles.indexOf(tile), 1);
		}

		function addIconToRandomTile(icon, tiles) {

			var randomLocation = Math.floor(Math.random() * (tiles.length - 1));
			var tile = tiles[randomLocation];

			var value;
			switch(icon) {

				case IconEnum.ARROW:  value = self.getDirectionToGift(tile, giftTile); break;
				case IconEnum.NUMBER: value = self.getDistanceFromGiftTile(tile, giftTile); break;
				default:              value = null;
			}

			tile.set("icon", new Icon({ type: icon, value: value }));
			tiles.splice(randomLocation, 1);

			return tile;
		}
	},

	getDirectionToGift: function(tile, giftTile) {

		var useLeftRight;

		// Determine whether this arrow will be left/right or up/down (sometimes there's no choice)
		if (tile.get("x") == giftTile.get("x")) {

			useLeftRight = false;
		}
		else if (tile.get("y") == giftTile.get("y")) {

			useLeftRight = true;
		}
		else {

			useLeftRight = (Math.random() > 0.5);
		}

		if (useLeftRight) {

			return (tile.get("x") > giftTile.get("x") ? "left" : "right");
		}
		else {

			return (tile.get("y") > giftTile.get("y") ? "down" : "up");
		}
	},

	getDistanceFromGiftTile: function(tile, giftTile) {

		return (Math.abs(tile.get("x") - giftTile.get("x")) + Math.abs(tile.get("y") - giftTile.get("y")));
	}
});

var TileView = Backbone.Marionette.ItemView.extend({

	className: "grid-cell",

	events: {
		"click": "tileClicked",
		"tap": "tileClicked"
	},

	render: function() {

		if (this.model.get("revealed")) {

			this.$el.addClass("revealed");
			this.addContent();
		}
		else if (this.model.get("dead")) {

			this.$el.addClass("dead");
		}
		else {

			this.$el.removeClass("revealed");

			// Remove content
			this.$el.removeClass("bad neutral good");
			this.$el.html("");
		}

		return this;
	},

	tileClicked: function() {

		if (!this.model.get("revealed")) {

			this.reveal();
			this.performAction();
			this.trigger("tile:revealed");
		}
	},

	reveal: function() {

		this.model.set("revealed", true);
		this.render();
	},

	hide: function() {

		if (this.model.get("revealed")) {

			this.model.set("revealed", false);
			this.render();
		}
	},

	addContent: function() {},

	performAction: function() {}
});

var EmptyTileView = TileView.extend({

	addContent: function() {

		this.$el.addClass("neutral");
	}
});

var GiftTileView = TileView.extend({

	addContent: function() {

		this.$el.addClass("gift");
		this.$el.html('');
	},

	tileClicked: function() {

		if (!this.model.get("revealed")) {

			this.reveal();
			this.performAction();
		}
	},

	reveal: function() {

		TileView.prototype.reveal.call(this);

		this.trigger("win");
	},

	performAction: function() {

		this.$(".glyphicon").addClass("animated flash");
	}
});

var FireTileView = TileView.extend({

	addContent: function() {

		this.$el.addClass("bad");
		this.$el.html('');
	},

	hide: function() {

		TileView.prototype.hide.call(this);

		this.$el.removeClass("animated pulse");
	},

	performAction: function() {

		var self = this;

		this.$el.addClass("animated pulse");

		this.collection.each(function(tileView) {

			// Hide all tiles except this one
			if (tileView != self) tileView.hide();
		});
	}
});

var ArrowTileView = TileView.extend({

	addContent: function() {

		this.$el.addClass("good");
		this.$el.html('');
	}
});

var NumberTileView = TileView.extend({

	addContent: function() {

		this.$el.addClass("good");
		this.$el.html(this.model.get("icon").get("value"));
	}
});

var GridView = Backbone.Marionette.CollectionView.extend({

	id: "#game-grid",

	className: "grid animated",

	childView: TileView,

	events: {
		"click .grid-cell": "tileClicked"
	},

	onRender: function() {

		// Wrap cells in a .grid-row every 9 cells
		var cells = this.$el.children();

		for(var i = 0; i < cells.length; i += 9)
			cells.slice(i, i + 9).wrapAll('
');
	},

	buildChildView: function(child, ChildViewClass, childViewOptions) {

		var icon = child.get("icon") ? child.get("icon").get("type") : null;

		var options = _.extend({ model: child, collection: this.children }, childViewOptions);

		switch (icon) {

			case IconEnum.FIRE:   return new FireTileView(options);
			case IconEnum.ARROW:  return new ArrowTileView(options);
			case IconEnum.NUMBER: return new NumberTileView(options);
			case IconEnum.GIFT:   return new GiftTileView(options);
			default:              return new EmptyTileView(options);
		}
	},

	show: function() {

		this.$el.removeClass("fadeOut").addClass("fadeIn");
		this.render();
	},

	hide: function() {

		this.$el.removeClass("fadeIn").addClass("fadeOut");
	},

	revealAll: function() {

		var self = this;

		var delay = 0;

		this.children.each(function(tile) {

			setTimeout(function() {

				if(!tile.model.get("revealed"))
					tile.reveal();

				if (tile === self.children.last())
					self.trigger("end");

			}, delay);

			delay += 75;
		});
	},

	onChildviewTileRevealed: function() {

		this.trigger("tile:revealed");
	},

	onChildviewWin: function() {

		this.trigger("win");
	}
});

var StatsView = Backbone.View.extend({

	id: "stats",

	className: "stats-panel animated",

	template: _.template($("#template-stats").html()),

	render: function() {

		this.$el.html(this.template(this.model.attributes));
		return this;
	},

	show: function() {

		this.$el.removeClass("fadeOut").addClass("fadeIn");
		this.render();
	},

	hide: function() {

		this.$el.removeClass("fadeIn").addClass("fadeOut");
	},
});
var App = Backbone.Model.extend({

	initialize: function() {

		var self = this;

		this.set({ won: false, restarting: false });

		this.setTileCounts();

		this.set({ movesRemaining: self.get("moves") });
	},

	setTileCounts: function() {

		this.set({
			moves: getRandomInt(20, 25),
			fires: getRandomInt(6, 18),
			arrows: getRandomInt(2, 8),
			numbers: getRandomInt(2, 8)
		});
	},

	decrementMoves: function() {

		this.set("movesRemaining", this.get("movesRemaining") - 1);
	}
});

var EndDialogView = Backbone.View.extend({

	id: "end-dialog",

	className: "animated fadeIn",

	template: _.template($("#template-end-dialog").html()),

	render: function() {

		this.$el.html(this.template(this.model.attributes));
		return this;
	}
});

var AppView = Backbone.View.extend({

	el: "#game-container",

	model: new App(),

	events: {
		"click #restart-button": "restart"
	},

	initialize: function() {

		this.on('restart', this.restart);

		this.start();
	},

	start: function() {

		this.createGrid();
		this.createStats();

		this.stats.render();
		this.grid.show();
		this.stats.show();
	},

	createGrid: function() {

		this.grid = new GridView({ collection: new Grid({ fires: this.model.get("fires"), arrows: this.model.get("arrows"), numbers: this.model.get("numbers") }).grid })

		this.$el.children("#game").append(this.grid.$el);

		this.listenTo(this.grid, "tile:revealed", this.tileRevealed);
		this.listenTo(this.grid, "win", this.win);
	},

	createStats: function() {

		this.stats = new StatsView({ model: this.model });

		this.stats.$el.insertBefore(this.grid.$el);
	},

	tileRevealed: function() {

		this.decrementMoves();

		if (this.model.get("movesRemaining") == 0)
			this.lose();
	},

	decrementMoves: function() {

		// Just in case, prevent moves remaining from ever displaying below 0
		if (this.model.get("movesRemaining") > 0)
			this.model.decrementMoves();

		this.stats.render();
	},

	restart: function() { // TODO track down and remove all old left-over objects

		var self = this;

		if (!this.model.get("restarting")) {

			this.model.set("restarting", true);

			this.disableBoard();

			this.grid.hide();
			this.stats.hide();

			setTimeout(function() {

				self.grid.remove();
				self.stats.remove();

				self.grid.collection.reset();

				self.model.destroy();
				self.model = new App();

				self.start();

			}, 1000);
		}
	},

	lose: function() {

		this.grid.children.each(function(child) {

			child.model.set("dead", true);
			child.render();
		});

		this.reveal();
	},

	win: function() {

		this.decrementMoves();

		this.model.set("won", true);

		this.reveal();
	},

	reveal: function(result) {

		var self = this;

		this.disableBoard();

		this.listenTo(this.grid, "end", this.showEndDialog);

		setTimeout(function() { self.grid.revealAll() }, 1000);
	},

	disableBoard: function() {

		this.stopListening();
		this.grid.children.each(function(child) { child.undelegateEvents() });
	},

	showEndDialog: function() {

		var self = this;

		setTimeout(function() {

			$(".stats-row, .grid-row").fadeTo("slow", 0.5);

			var end = new EndDialogView({ model: self.model });
			self.grid.$el.append(end.$el);
			end.render();

		}, 1000);
	}
});

new AppView();<|endoftext|>


<commit_before>#!/usr/bin/env node

var tinylr = require('tiny-lr');
var chokidar = require('chokidar');

var lr = new tinylr.Server
lr.listen(35729, function (err) { if(err) { throw err } });

var watcher = chokidar.watch(process.argv[2]);
watcher.on('ready', function(){
  watcher.on('all', function() {
    console.log('Reloading browser...')
    lr.changed({body: {files: ['dummy']}})
  });
});
<commit_msg>Pass changed path to livereload<commit_after>#!/usr/bin/env node

var tinylr = require('tiny-lr');
var chokidar = require('chokidar');

var lr = new tinylr.Server
lr.listen(35729, function (err) { if(err) { throw err } });

var watcher = chokidar.watch(process.argv[2]);
watcher.on('ready', function(){
  watcher.on('all', function(event, path) {
    console.log('Reloading browser...')
    lr.changed({body: {files: [path]}})
  });
});
<|endoftext|>


<commit_before>import React from 'react';
import cx from 'classnames';
import { Group } from '@vx/group';
import { arc as d3Arc, pie as d3Pie } from 'd3-shape';
import additionalProps from '../util/additionalProps';

export default function Pie({
  className = '',
  top = 0,
  left = 0,
  data,
  centroid,
  innerRadius = 0,
  outerRadius,
  cornerRadius,
  startAngle = 0,
  endAngle,
  padAngle,
  padRadius,
  pieSort,
  pieSortValues,
  pieValue,
  ...restProps
}) {
  const path = d3Arc();
  path.innerRadius(innerRadius);
  if (outerRadius) path.outerRadius(outerRadius);
  if (cornerRadius) path.cornerRadius(cornerRadius);
  if (padRadius) path.padRadius(padRadius);
  const pie = d3Pie();
  if (pieSort) pie.sort(pieSort);
  if (pieSortValues) pie.sortValues(pieSortValues);
  if (pieValue) pie.value(pieValue);
  if (padAngle) pie.padAngle(padAngle);
  const arcs = pie(data);
  return (
    <Group className="vx-pie-arcs-group" top={top} left={left}>
      {arcs.map((arc, i) => {
        let c;
        if (centroid) c = path.centroid(arc);
        return (
          <g key={`pie-arc-${i}`}>
            <path
              className={cx('vx-pie-arc', className)}
              d={path(arc)}
              {...additionalProps(restProps, {
                ...arc,
                index: i,
                centroid: c
              })}
            />
            {centroid && centroid(c, arc)}
          </g>
        );
      })}
    </Group>
  );
}
<commit_msg>[pie] Pass start/endAngle and use null checks:<commit_after>import React from 'react';
import cx from 'classnames';
import { Group } from '@vx/group';
import { arc as d3Arc, pie as d3Pie } from 'd3-shape';
import additionalProps from '../util/additionalProps';

export default function Pie({
  className = '',
  top = 0,
  left = 0,
  data,
  centroid,
  innerRadius = 0,
  outerRadius,
  cornerRadius,
  startAngle = 0,
  endAngle,
  padAngle,
  padRadius,
  pieSort,
  pieSortValues,
  pieValue,
  ...restProps
}) {
  const path = d3Arc();
  path.innerRadius(innerRadius);
  if (outerRadius) path.outerRadius(outerRadius);
  if (cornerRadius) path.cornerRadius(cornerRadius);
  if (padRadius) path.padRadius(padRadius);
  const pie = d3Pie();
  if (pieSort) pie.sort(pieSort);
  if (pieSortValues) pie.sortValues(pieSortValues);
  if (pieValue) pie.value(pieValue);
  if (padAngle != null) pie.padAngle(padAngle);
  if (startAngle != null) pie.startAngle(startAngle);
  if (endAngle != null) pie.endAngle(endAngle);
  const arcs = pie(data);
  return (
    <Group className="vx-pie-arcs-group" top={top} left={left}>
      {arcs.map((arc, i) => {
        let c;
        if (centroid) c = path.centroid(arc);
        return (
          <g key={`pie-arc-${i}`}>
            <path
              className={cx('vx-pie-arc', className)}
              d={path(arc)}
              {...additionalProps(restProps, {
                ...arc,
                index: i,
                centroid: c
              })}
            />
            {centroid && centroid(c, arc)}
          </g>
        );
      })}
    </Group>
  );
}
<|endoftext|>


<commit_before>/**
 *          .·.·.·.·.·.·.·.·.·.·.·.·.·.·.·.·.·.·.·.
 *          .·' H O M E S C R E E N S F O R A L L'·.  by leandro713
 *          .·.·.·.·.·.·.·.·.·.·.·.·.·.·.·.·.·.·.·.
 *
 * Tilescreen
 * (c) leandro@leandro.org
 * GPL v3 license
 * v. 20160111
 *
 * @author      leandro713 <leandro@leandro.org>
 * @copyright   leandro713 - 2016
 * @link        https://github.com/novia713/tilescreen
 * @license     http://www.gnu.org/licenses/gpl-3.0.en.html
 * @version     1.1
 * @date        20160111
 *
 * @see         https://github.com/mozilla-b2g/gaia/tree/88c8d6b7c6ab65505c4a221b61c91804bbabf891/apps/homescreen
 * @thanks      to @CodingFree for his tireless support and benevolent friendship
 * @todo
 *      - show wifi network name and telephony provider name
 *      - show weather
 *      - show missed calls
 *      - default icon if not found
 */

requirejs.config({
    appDir: ".",
    baseUrl: "js",
    paths: {
        'jQuery': ['jquery-2.1.4.min'],
        'ramdajs': ['ramda.min']
    },
    shim: {
        'ramdajs': {
            exports: 'R'
        }
    }
});

require(["jQuery", 'ramdajs'], (jQuery, R) => {

    const apps_2_exclude = [
        "Downloads", "EmergencyCall", "System", "Legacy", "Ringtones",
        "Legacy Home Screen", "Wallpaper", "Default Theme", "Purchased Media",
        "Built-in Keyboard", "Bluetooth Manager", "Communications",
        "PDF Viewer", "Network Alerts", "WAP Push manager", "Default Home Screen" ];

    var parent = $('#apps');
    var iconMap = new WeakMap();

    //colores
    var get_color = app => {
        var obj_color = {};
        obj_color.Communications = "#B2F2FF"; //green 5F9B0A
        obj_color.Calendar = "#FF4E00"; //orange
        obj_color['E-Mail'] = "#FF4E00"; //orange
        obj_color['FM Radio'] = "#2C393B"; //grey
        obj_color.Camera = "#00AACC"; //blue
        obj_color.Clock = "#333333"; //warm grey
        obj_color.Gallery = "#00AACC"; //blue
        obj_color.Marketplace = "#00AACC"; //blue
        obj_color.Browser = "#00AACC"; //blue
        obj_color.Messages = "#5F9B0A"; //green
        obj_color.Video = "#CD6723"; //brick
        obj_color.Music = "#CD6723"; //brick
        obj_color.Settings = "#EAEAE7"; //ivory

        if (obj_color[app]) {
            return obj_color[app];
        } else {
            //random hex color;
            return '#' + Math.floor(Math.random() * 16777215).toString(16);
        }
    };

    /**
     * Prints set up message
     */
     var print_msg = () => {
        var txt_msg  = "

Please, set this homescreen your default homescreen in Settings / Homescreens / Change Homescreens. This homescreen won't work if you don't do so

";
            txt_msg += "

Ve a Configuración / Homescreens y haz este homescreen tu homescreen por defecto. Si no lo haces, este homescreen no funciona!

";
        parent.html(txt_msg);
     };

    /**
     * Renders the icon to the container.
     */
    var render = icon => {

            if (!icon.manifest.icons) return;

            // guards
            if( R.contains ( icon.manifest.name, apps_2_exclude ))  return;
            if (icon.manifest.role == "homescreen")                 return;
            if (icon.manifest.role == "addon")                      return;
            //end guards

            var icon_image = navigator.mozApps.mgmt.getIcon(icon, 60);

            icon_image.then ( img => {

                var name = icon.manifest.name; console.log(name);
                var wordname = name.split(" ");
                var firstchar = name.charAt(0);

                /* tile generation*/
                var tile = document.createElement('div');
                tile.className = 'tile';
                tile.className += ' icon_' + wordname[0];
                tile.style.background = get_color(name) + ' url(' + window.URL.createObjectURL(  img ) + ') 49% no-repeat';

                $('#apps').append(tile);
                iconMap.set(tile, icon);
                /* end tile generation*/
            });

            if (typeof icon_image == undefined) return;

    }

    /* fires up the painting */
    var start = () => {
            $('.tile').remove();
            /**
             * Fetch all apps and render them.
             */
            var myApps = new Promise((resolve, reject) => {
                    var request = navigator.mozApps.mgmt.getAll();

                    request.onsuccess = (e) => {
                      for (var app of request.result) {
                        render( app );
                      }
                    };

                    request.onerror = (e) => {
                      console.error('Error calling getAll: ' + request.error.name);
                      resolve();
                    };
            });

            myApps.then(
                v => {

                }, v => {
                    print_msg();
                }
            );
    } //end start

    // event listener to launch the app on click.

    window.addEventListener('click', e => {
        var i = iconMap.get(e.target);

        if (i) {
            //$('.' + e.originalTarget.classList[1]).css("-moz-transform", "rotate(320deg)");
            i.launch();
        }
    }); //end window event 'click'

    // 3, 2, 1 ...
    start();

});
<commit_msg>iconos ordenador por frecuencia de uso funcionando<commit_after>/**
 *          .·.·.·.·.·.·.·.·.·.·.·.·.·.·.·.·.·.·.·.
 *          .·' H O M E S C R E E N S F O R A L L'·.  by leandro713
 *          .·.·.·.·.·.·.·.·.·.·.·.·.·.·.·.·.·.·.·.
 *
 * Tilescreen
 * (c) leandro@leandro.org
 * GPL v3 license
 * v. 20160120
 *
 * @author      leandro713 <leandro@leandro.org>
 * @copyright   leandro713 - 2016
 * @link        https://github.com/novia713/tilescreen
 * @license     http://www.gnu.org/licenses/gpl-3.0.en.html
 * @version     1.2b
 * @date        20160120
 *
 * @see         https://github.com/mozilla-b2g/gaia/tree/88c8d6b7c6ab65505c4a221b61c91804bbabf891/apps/homescreen
 * @thanks      to @CodingFree for his tireless support and benevolent friendship
 * @todo
 *      - order icons by use [done]
 *      - show wifi network name and telephony provider name
 *      - show weather
 *      - show missed calls
 *      - default icon if not found
 *
 */

requirejs.config({
    appDir: ".",
    baseUrl: "js",
    paths: {
        'ramdajs': ['ramda.min']
    },
    shim: {
        'ramdajs': {
            exports: 'R'
        }
    }
});

require(['ramdajs'], ( R ) => {

    const apps_2_exclude = [
        "Downloads", "EmergencyCall", "System", "Legacy", "Ringtones",
        "Legacy Home Screen", "Wallpaper", "Default Theme", "Purchased Media",
        "Built-in Keyboard", "Bluetooth Manager", "Communications",
        "PDF Viewer", "Network Alerts", "WAP Push manager", "Default Home Screen" ];

    var parent = document.getElementById('apps');
    var iconMap = new WeakMap();
    var usage = [];
    var i = 0;
    var storage = null;

    //colores
    var get_color = app => {
        var obj_color = {};
        obj_color.Communications = "#B2F2FF"; //green 5F9B0A
        obj_color.Calendar = "#FF4E00"; //orange
        obj_color['E-Mail'] = "#FF4E00"; //orange
        obj_color['FM Radio'] = "#2C393B"; //grey
        obj_color.Camera = "#00AACC"; //blue
        obj_color.Clock = "#333333"; //warm grey
        obj_color.Gallery = "#00AACC"; //blue
        obj_color.Marketplace = "#00AACC"; //blue
        obj_color.Browser = "#00AACC"; //blue
        obj_color.Messages = "#5F9B0A"; //green
        obj_color.Video = "#CD6723"; //brick
        obj_color.Music = "#CD6723"; //brick
        obj_color.Settings = "#EAEAE7"; //ivory

        if (obj_color[app]) {
            return obj_color[app];
        } else {
            //random hex color;
            return '#' + Math.floor(Math.random() * 16777215).toString(16);
        }
    };

    /**
     * Prints set up message
     */
     var print_msg = () => {
        var txt_msg  = "

Please, set this homescreen your default homescreen in Settings / Homescreens / Change Homescreens. This homescreen won't work if you don't do so

";
            txt_msg += "

Ve a Configuración / Homescreens y haz este homescreen tu homescreen por defecto. Si no lo haces, este homescreen no funciona!

";
            parent.innerHTML(txt_msg);
     };

    /**
     * Renders the icon to the container.
     */
    var render = icon => {

            if (!icon.manifest.icons) return;

            // guards
            if( R.contains ( icon.manifest.name, apps_2_exclude ))  return;
            if (icon.manifest.role == "homescreen")                 return;
            if (icon.manifest.role == "addon")                      return;
            //end guards

            var icon_image = navigator.mozApps.mgmt.getIcon(icon, 60);

            icon_image.then ( img => {

                var name = icon.manifest.name;
                var wordname = name.split(" ");
                var firstchar = name.charAt(0);

                /* tile generation*/
                var tile = document.createElement('div');
                tile.className = 'tile';
                tile.className += ' icon_' + wordname[0];
                tile.style.background = get_color(name) + ' url(' + window.URL.createObjectURL(  img ) + ') 49% no-repeat';

                document.getElementById('apps').appendChild(tile);
                iconMap.set(tile, icon);
                /* end tile generation*/

                // array for storing it in JSON for using records
                var item = { "label": wordname[0], "index": i, "order": 0 };
                storage = localStorage.getItem("storage");

                if ( !storage ) {
                    storage = [];
                    storage[i] = item;
                    localStorage.setItem( "storage", JSON.stringify( storage ));
                } else  {
                    var data = JSON.parse(storage);
                    data[i] =  item;
                    localStorage.setItem( "storage", JSON.stringify( data ));
                }

                ++i;
            });

            if (typeof icon_image == undefined) return;

    }

    /* fires up the painting */
    var start = () => {
            //document.getElementsByClassName('tile').remove();

            /**
             * Fetch all apps and render them.
             */
            var myApps = new Promise((resolve, reject) => {
                    var request = navigator.mozApps.mgmt.getAll();

                    request.onsuccess = (e) => {

                      // hic sunt render leones
                      R.forEach( render, request.result );
                    };

                    request.onerror = (e) => {
                      console.error('Error calling getAll: ' + request.error.name);
                      resolve();
                    };
            });

            myApps.then(
                v => {

                }, v => {
                    print_msg();
                }
            );
    } //end start

    window.addEventListener('click', ev => {

        if ( typeof storage == "string" ) storage = JSON.parse( storage );
        var i = iconMap.get(ev.target);

        if (i) {

            var classname = R.replace("icon_", "", R.split( " ", ev.originalTarget.className)[1]);
            var index     = R.keys ( R.filter( R.propEq("label", classname ), storage ));

            // we add 1 to value of that icon ...
            storage[index].order +=1;
            localStorage.setItem( "storage", JSON.stringify( storage ));

            // transpose storage value to DOM elements
            ev.target.dataset.order = storage[index].order;

            // sorting
            var compare = function (a, b) {

              if (a.dataset.order == undefined) a.dataset.order = 0;
              if (b.dataset.order == undefined) a.dataset.order = 0;

              if (a.dataset.order > b.dataset.order)

                    return -1;
                  else if (a.dataset.order  {
                document.getElementById('apps').appendChild( e );
            }

            R.forEach(print_tile, [].slice.call(new_roster));
            // end saving use of icon in localstorage

            i.launch();
        }
    }); //end window event 'click', document.getElementsByClassName('tile'));

    // 3, 2, 1 ...
    start();

});
<|endoftext|>


<commit_before>/* A sample plugin.
 * First we take the irc object from global (there has to be a better
 * way to do that).  Here we use it to access the privmsg function,
 * but you could really pull anything that's attached to it.
 *
 * Then we give the plugin a name, designate a handler and export
 * them back to the 'main' module, where they are stored and processed. */

var irc = global.irc;

var m_handler = function(act) {
  if (act.params.length === 0) {
    irc.privmsg(act.channel, 'test');
  } else {
    irc.privmsg(act.channel, act.params.join(' '));
  }
};

/* This is where the final object is built.  'name' is how the plugin
 * will be referred to in methods that control plugins, and handler
 * is the hnadler that is controlled.
 *
 * For example, this plugin is called 'test'.  Admins can enable/disable
 * plugins by using the !enable or !disable command in a channel and calling
 * this name like so:
 * !enable test
 * That will detach the handler, in this case test_handler, from the event
 * emitter. */
exports.name = 'test';
exports.handler = test_handler;
<commit_msg>fixed the sample plugin<commit_after>/* A sample plugin.
 * First we take the irc object from global (there has to be a better
 * way to do that).  Here we use it to access the privmsg function,
 * but you could really pull anything that's attached to it.
 *
 * Then we give the plugin a name, designate a handler and export
 * them back to the 'main' module, where they are stored and processed. */

var irc = global.irc;

var test_handler = function(act) {
  if (act.params.length === 0) {
    irc.privmsg(act.channel, 'test');
  } else {
    irc.privmsg(act.channel, act.params.join(' '));
  }
};

/* This is where the final object is built.  'name' is how the plugin
 * will be referred to in methods that control plugins, and handler
 * is the hnadler that is controlled.
 *
 * For example, this plugin is called 'test'.  Admins can enable/disable
 * plugins by using the !enable or !disable command in a channel and calling
 * this name like so:
 * !enable test
 * That will detach the handler, in this case test_handler, from the event
 * emitter. */
exports.name = 'test';
exports.handler = test_handler;
<|endoftext|>


<commit_before>var roleReserver = require('roleReserver')

roleSpawner = {

    run: function(roomId) {
	    var store = {
	        'harvester': 2,
	        'worker': 7,
	        'reserver': Object.keys(Memory.claimTargets).length,
	        'distanceHarvester': 6,
	        //'claimer': 1,
	        'settler': 1
	        //'attacker': 1,
	        //'sniper': 1,
	    };

        if(!roleReserver.expiringSoon()) {
            store['reserver'] = 0;
        }

	    for(role in store) {
	        var count = store[role];
	        var creeps = _.filter(Game.creeps, (creep) => creep.memory.role == role && creep.memory.home == roomId);
	        if(creeps.length < count) {

	            var build = undefined;
	            switch (role) {
                    case 'harvester':
                        build = roleSpawner.currentHarvesterBuild();
                        break;
	                case 'worker':
	                    build = roleSpawner.currentWorkerBuild();
	                    break;
	                case 'roadLayer':
	                    build = roleSpawner.currentWorkerBuild();
	                    break;
	                case 'reserver':
	                    build = roleSpawner.currentReserverBuild();
	                    break;
                    case 'claimer':
                        build = roleSpawner.currentClaimerBuild();
                        break;
                    case 'settler':
                        build = roleSpawner.currentSettlerBuild();
                        break;
                    case 'attacker':
                        build = roleSpawner.currentAttackerBuild();
                        break;
                    case 'distanceHarvester':
                        build = roleSpawner.currentDistanceHarvesterBuild();
                        break;
                    case 'sniper':
                        build = roleSpawner.currentSniperBuild();
                        break;
	            }
                var spawnName = Memory[roomId].spawns[0];

                var targetHome = roomId;
                if(role == 'settler') {
                    targetHome = Memory.expansionTarget;
                }

		        var newName = Game.spawns[spawnName].createCreep(build, undefined, {role: role, home: targetHome});
                if(newName != ERR_BUSY && newName != ERR_NOT_ENOUGH_ENERGY) {
                    console.log('spawning new ' + role + ': ' + newName);
                }
	        }
	    }
    },

    assembleBuild: function(stats) {
        var build = [];
        for(part in stats) {
            for(var i=0; i < stats[part]; i++) {
                var partCode = undefined;
                switch (part) {
                    case 'WORK':
                        partCode = WORK;
                        break;
                    case 'CARRY':
                        partCode = CARRY;
                        break;
                    case 'MOVE':
                        partCode = MOVE;
                        break;
                    case 'ATTACK':
                        partCode = ATTACK;
                        break;
                     case 'RANGED_ATTACK':
                         partCode = RANGED_ATTACK;
                         break;
                }

                build.push(partCode);
            }
        }
        return build;
    },

    currentWorkerBuild: function() {
        var spawnRoomCapacity = Game.rooms[Memory.home].energyCapacityAvailable;
        if(spawnRoomCapacity >= 1300) {
            return roleSpawner.assembleBuild({
                WORK: 4,
                CARRY: 8,
                MOVE: 6,
            })
        } else if(spawnRoomCapacity >= 800) {
            return roleSpawner.assembleBuild({
                WORK: 2,
                CARRY: 6,
                MOVE: 4,
            })
        } else if(spawnRoomCapacity >= 550) {
            return roleSpawner.assembleBuild({
                WORK: 2,
                CARRY: 3,
                MOVE: 3,
            })
        } else {
            return [WORK,CARRY,MOVE];
        }
    },

    currentHarvesterBuild: function() {
        var spawnRoomCapacity = Game.rooms[Memory.home].energyCapacityAvailable;
        if(spawnRoomCapacity >= 1300) {
            return roleSpawner.assembleBuild({
                WORK: 6,
                CARRY: 4,
                MOVE: 3,
            })
        } else if(spawnRoomCapacity >= 800) {
            return roleSpawner.assembleBuild({
                WORK: 4,
                CARRY: 4,
                MOVE: 2,
            })
        } else if(spawnRoomCapacity >= 550) {
            return roleSpawner.assembleBuild({
                WORK: 3,
                CARRY: 3,
                MOVE: 2,
            })
        } else {
            return [WORK,CARRY,MOVE];
        }
    },

    currentReserverBuild: function() {
        return [CLAIM, CLAIM, MOVE, MOVE];
    },

    currentClaimerBuild: function() {
        return [CLAIM, CARRY, CARRY, CARRY, CARRY, CARRY, MOVE, MOVE, MOVE, MOVE, MOVE, MOVE];
    },

    currentSettlerBuild: function() {
        return roleSpawner.assembleBuild({
            WORK: 4,
            CARRY: 4,
            MOVE: 8,
        })
    },

    currentAttackerBuild: function() {
        return roleSpawner.assembleBuild({
            ATTACK: 10,
            MOVE: 10,
        })
    },

    currentSniperBuild: function() {
        return roleSpawner.assembleBuild({
            RANGED_ATTACK: 1,
            MOVE: 1,
        })
    },

    currentDistanceHarvesterBuild: function() {
        return roleSpawner.assembleBuild({
            WORK: 5, // 500 + 250
            CARRY: 15, // 500 + 500
            MOVE: 10,
        })
    },
}

module.exports = roleSpawner;
<commit_msg>no more settlers<commit_after>var roleReserver = require('roleReserver')

roleSpawner = {

    run: function(roomId) {
	    var store = {
	        'harvester': 2,
	        'worker': 7,
	        'reserver': Object.keys(Memory.claimTargets).length,
	        'distanceHarvester': 6,
	        //'claimer': 1,
	        //'settler': 1
	        //'attacker': 1,
	        //'sniper': 1,
	    };

        if(!roleReserver.expiringSoon()) {
            store['reserver'] = 0;
        }

	    for(role in store) {
	        var count = store[role];
	        var creeps = _.filter(Game.creeps, (creep) => creep.memory.role == role && creep.memory.home == roomId);
	        if(creeps.length < count) {

	            var build = undefined;
	            switch (role) {
                    case 'harvester':
                        build = roleSpawner.currentHarvesterBuild();
                        break;
	                case 'worker':
	                    build = roleSpawner.currentWorkerBuild();
	                    break;
	                case 'roadLayer':
	                    build = roleSpawner.currentWorkerBuild();
	                    break;
	                case 'reserver':
	                    build = roleSpawner.currentReserverBuild();
	                    break;
                    case 'claimer':
                        build = roleSpawner.currentClaimerBuild();
                        break;
                    case 'settler':
                        build = roleSpawner.currentSettlerBuild();
                        break;
                    case 'attacker':
                        build = roleSpawner.currentAttackerBuild();
                        break;
                    case 'distanceHarvester':
                        build = roleSpawner.currentDistanceHarvesterBuild();
                        break;
                    case 'sniper':
                        build = roleSpawner.currentSniperBuild();
                        break;
	            }
                var spawnName = Memory[roomId].spawns[0];

                var targetHome = roomId;
                if(role == 'settler') {
                    targetHome = Memory.expansionTarget;
                }

		        var newName = Game.spawns[spawnName].createCreep(build, undefined, {role: role, home: targetHome});
                if(newName != ERR_BUSY && newName != ERR_NOT_ENOUGH_ENERGY) {
                    console.log('spawning new ' + role + ': ' + newName);
                }
	        }
	    }
    },

    assembleBuild: function(stats) {
        var build = [];
        for(part in stats) {
            for(var i=0; i < stats[part]; i++) {
                var partCode = undefined;
                switch (part) {
                    case 'WORK':
                        partCode = WORK;
                        break;
                    case 'CARRY':
                        partCode = CARRY;
                        break;
                    case 'MOVE':
                        partCode = MOVE;
                        break;
                    case 'ATTACK':
                        partCode = ATTACK;
                        break;
                     case 'RANGED_ATTACK':
                         partCode = RANGED_ATTACK;
                         break;
                }

                build.push(partCode);
            }
        }
        return build;
    },

    currentWorkerBuild: function() {
        var spawnRoomCapacity = Game.rooms[Memory.home].energyCapacityAvailable;
        if(spawnRoomCapacity >= 1300) {
            return roleSpawner.assembleBuild({
                WORK: 4,
                CARRY: 8,
                MOVE: 6,
            })
        } else if(spawnRoomCapacity >= 800) {
            return roleSpawner.assembleBuild({
                WORK: 2,
                CARRY: 6,
                MOVE: 4,
            })
        } else if(spawnRoomCapacity >= 550) {
            return roleSpawner.assembleBuild({
                WORK: 2,
                CARRY: 3,
                MOVE: 3,
            })
        } else {
            return [WORK,CARRY,MOVE];
        }
    },

    currentHarvesterBuild: function() {
        var spawnRoomCapacity = Game.rooms[Memory.home].energyCapacityAvailable;
        if(spawnRoomCapacity >= 1300) {
            return roleSpawner.assembleBuild({
                WORK: 6,
                CARRY: 4,
                MOVE: 3,
            })
        } else if(spawnRoomCapacity >= 800) {
            return roleSpawner.assembleBuild({
                WORK: 4,
                CARRY: 4,
                MOVE: 2,
            })
        } else if(spawnRoomCapacity >= 550) {
            return roleSpawner.assembleBuild({
                WORK: 3,
                CARRY: 3,
                MOVE: 2,
            })
        } else {
            return [WORK,CARRY,MOVE];
        }
    },

    currentReserverBuild: function() {
        return [CLAIM, CLAIM, MOVE, MOVE];
    },

    currentClaimerBuild: function() {
        return [CLAIM, CARRY, CARRY, CARRY, CARRY, CARRY, MOVE, MOVE, MOVE, MOVE, MOVE, MOVE];
    },

    currentSettlerBuild: function() {
        return roleSpawner.assembleBuild({
            WORK: 4,
            CARRY: 4,
            MOVE: 8,
        })
    },

    currentAttackerBuild: function() {
        return roleSpawner.assembleBuild({
            ATTACK: 10,
            MOVE: 10,
        })
    },

    currentSniperBuild: function() {
        return roleSpawner.assembleBuild({
            RANGED_ATTACK: 1,
            MOVE: 1,
        })
    },

    currentDistanceHarvesterBuild: function() {
        return roleSpawner.assembleBuild({
            WORK: 5, // 500 + 250
            CARRY: 15, // 500 + 500
            MOVE: 10,
        })
    },
}

module.exports = roleSpawner;
<|endoftext|>


<commit_before>/*!
 * bio-grids.js
 * Kevin English, University of Hawaii
 */
Ext.bio.SeqSearchField = Ext.extend(Ext.form.TwinTriggerField, {
  initComponent : function(){
    Ext.bio.SeqSearchField.superclass.initComponent.call(this);
    this.on('specialkey', function(f, e){
      if(e.getKey() == e.ENTER){
        this.onTrigger2Click();
      }
    }, this);
  },
  validationEvent:false,
  validateOnBlur:false,
  trigger1Class:'x-form-clear-trigger',
  trigger2Class:'x-form-search-trigger',
  hideTrigger1:true,
  width:50,
  hasSearch : false,
  paramName : 'query',

  onTrigger1Click : function(){
    if(this.hasSearch){
      this.el.dom.value = '';
      var o = {
        start: 0
      };
      this.store.baseParams = this.store.baseParams || {};
      this.store.baseParams[this.paramName] = '';
      this.store.reload({
        params:o
      });
      this.triggers[0].hide();
      this.hasSearch = false;
    }
  },

  onTrigger2Click : function(){
    var v = this.getRawValue();
    if(v.length < 1){
      this.onTrigger1Click();
      return;
    }
    var o = {
      start: 0
    };
    this.store.baseParams = this.store.baseParams || {};
    this.store.baseParams[this.paramName] = v;
    this.store.reload({
      params:o
    });
    this.hasSearch = true;
    this.triggers[0].show();
  }
});
Ext.bio.BiosequenceGrid =  Ext.extend(Ext.bio.RestfulGrid, {
  pageSize: 50,
  biosequenceViewPanelId: 'xxxx',
  usePagingBarFlag: true,
  displayColumns: [
  {
    header: "Name",
    sortable: true,
    autoWidth: true,
    dataIndex: 'name'
  }, {
    header: "Length",
    autoWidth: true,
    sortable: true,
    dataIndex: 'length'
  }
  ],
  initComponent: function() {
    var biosequenceViewPanelId = this.biosequenceViewPanelId;
    this.store.on('load',function() {
      var viewPanel = Ext.getCmp(biosequenceViewPanelId);
      if (viewPanel) {
        var params = {
          rowIndex: 0
        };
      }
    });
    var cmpId = this.id;

    function onDelete() {
      var grid = Ext.getCmp(cmpId);
      grid.deleteSelectedRow(true,'name',function(params) {
        grid.updateViewPanel({
          rowIndex: params.rowIndex
        });
      });
    }
    Ext.apply(this,{
      tbar:[       'Search: ', ' ',
      new Ext.bio.SeqSearchField({
        store: this.store,
        width:200
      }),
      {
        iconCls:'new_fasta',
        text: 'Fasta File',
        id:'seq-grid-fasta-toolbar-item',
        hidden: true,
        handler: function() {
          var strUrl = Ext.getCmp(cmpId).biodatabasePropertyStore.getAt(0).data.fasta_file_url;
          window.open(strUrl);
        }
      },'-',
      {
        iconCls:'clustalw',
        text: 'View Alignment',
        id:'seq-grid-alignment-toolbar-item',
        hidden: true,
        labelStyle: 'font-weight:bold;',
        alignmentViewPanelId: this.alignmentViewPanelId,
        handler: function() {
          var strUrl = Ext.getCmp(cmpId).biodatabasePropertyStore.getAt(0).data.alignment_file_url;
          var alignmentViewPanel = Ext.getCmp(this.alignmentViewPanelId);
          if (alignmentViewPanel) {
            alignmentViewPanel.updateContent({
              url: strUrl
            });
          }
        //          alignemExt.getCmp(this.alignmentViewPanelId).updateContent(strUrl);
        //          window.open(strUrl);
        }
      }
      , '->', {
        text: 'Delete',
        iconCls:'x-tree-delete',
        handler: onDelete
      }
      ]
    });

    Ext.bio.BiosequenceGrid.superclass.initComponent.call(this);
  },
  updateViewPanel: function(params) {
    var viewPanel = Ext.getCmp(this.biosequenceViewPanelId);
    viewPanel.updateContent(params);
  },
  listeners: {
    afterrender: function( p)  {
      var viewPanel = Ext.getCmp(this.biosequenceViewPanelId);
      viewPanel.setSource(this.store);
    },
    rowclick: function (grid, rowIndex, e) {
      var params = {
        rowIndex: rowIndex
      };
      grid.updateViewPanel(params);
    },
    cellclick: function (grid, rowIndex,columnIndex, e) {
      var fieldName = grid.getColumnModel().getColumnHeader(columnIndex);
      if (fieldName == 'Action'){
        var rec = grid.store.getAt(rowIndex); // getSelectionModel().getSelected();
        if (rec) {
          Ext.MessageBox.confirm('Confirm', 'Are you sure you want to delete "' + rec.data.name +'"?',
            function(btn){
              if (btn == 'yes') {
                grid.store.remove(rec);
                grid.selModel.selectRow(rowIndex);
                grid.updateViewPanel({
                  rowIndex: rowIndex
                });
              }
            });
          return false;
        }
      }
    }

  },
  updateContent: function(params) {
    if (params.biodatabase_id) {
      this.store.baseParams.biodatabase_id = params.biodatabase_id;
      this.store.load({
        params: {
          start: 0,
          limit: this.pageSize
        }
      } );
      var alignmentViewPanelId = this.alignmentViewPanelId;
      this.biodatabasePropertyStore.load({
        params:{
          id:params.biodatabase_id
        },
        callback: function(store, records, options){
          var tbFasta = Ext.getCmp('seq-grid-fasta-toolbar-item');
          //          var tbAlign = Ext.getCmp('seq-grid-alignment-toolbar-item');
          if (tbFasta) {
            if (this.getAt(0).data.fasta_file_url){
              tbFasta.show();
            } else {
              tbFasta.hide();
            }
          }
          var alignmentViewPanel = Ext.getCmp(alignmentViewPanelId );
          if (this.getAt(0).data.alignment_file_url){
            var url = this.getAt(0).data.alignment_file_url;
            if (alignmentViewPanel) {
              alignmentViewPanel.updateContent({
                url: url
              });
            }
          } else {
            alignmentViewPanel.clearContent();
          }
        }
      });
    }
  },
  clearContent : function() {
    this.store.reload();
  }

});
Ext.reg('biosequence-grid', Ext.bio.BiosequenceGrid);
<commit_msg>Javascript commen<commit_after>/*!
 * bio-grids.js
 * Kevin English, University of Hawaii
 */
Ext.bio.SeqSearchField = Ext.extend(Ext.form.TwinTriggerField, {
  initComponent : function(){
    Ext.bio.SeqSearchField.superclass.initComponent.call(this);
    this.on('specialkey', function(f, e){
      if(e.getKey() == e.ENTER){
        this.onTrigger2Click();
      }
    }, this);
  },
  validationEvent:false,
  validateOnBlur:false,
  trigger1Class:'x-form-clear-trigger',
  trigger2Class:'x-form-search-trigger',
  hideTrigger1:true,
  width:50,
  hasSearch : false,
  paramName : 'query',

  onTrigger1Click : function(){
    if(this.hasSearch){
      this.el.dom.value = '';
      var o = {
        start: 0
      };
      this.store.baseParams = this.store.baseParams || {};
      this.store.baseParams[this.paramName] = '';
      this.store.reload({
        params:o
      });
      this.triggers[0].hide();
      this.hasSearch = false;
    }
  },

  onTrigger2Click : function(){
    var v = this.getRawValue();
    if(v.length < 1){
      this.onTrigger1Click();
      return;
    }
    var o = {
      start: 0
    };
    this.store.baseParams = this.store.baseParams || {};
    this.store.baseParams[this.paramName] = v;
    this.store.reload({
      params:o
    });
    this.hasSearch = true;
    this.triggers[0].show();
  }
});
Ext.bio.BiosequenceGrid =  Ext.extend(Ext.bio.RestfulGrid, {
  pageSize: 50,
  biosequenceViewPanelId: 'xxxx',
  usePagingBarFlag: true,
  displayColumns: [
  {
    header: "Name",
    sortable: true,
    autoWidth: true,
    dataIndex: 'name'
  }, {
    header: "Length",
    autoWidth: true,
    sortable: true,
    dataIndex: 'length'
  }
  ],
  initComponent: function() {
    var biosequenceViewPanelId = this.biosequenceViewPanelId;
    this.store.on('load',function() {
      var viewPanel = Ext.getCmp(biosequenceViewPanelId);
      if (viewPanel) {
        var params = {
          rowIndex: 0
        };
      }
    });
    var cmpId = this.id;

    function onDelete() {
      var grid = Ext.getCmp(cmpId);
      grid.deleteSelectedRow(true,'name',function(params) {
        grid.updateViewPanel({
          rowIndex: params.rowIndex
        });
      });
    }
    Ext.apply(this,{
      tbar:[       'Search: ', ' ',
      new Ext.bio.SeqSearchField({
        store: this.store,
        width:200
      }),
      {
        iconCls:'new_fasta',
        text: 'Fasta File',
        id:'seq-grid-fasta-toolbar-item',
        hidden: true,
        handler: function() {
          var strUrl = Ext.getCmp(cmpId).biodatabasePropertyStore.getAt(0).data.fasta_file_url;
          window.open(strUrl);
        }
      },'-',
      {
        iconCls:'clustalw',
        text: 'View Alignment',
        id:'seq-grid-alignment-toolbar-item',
        hidden: true,
        labelStyle: 'font-weight:bold;',
        alignmentViewPanelId: this.alignmentViewPanelId,
        handler: function() {
          var strUrl = Ext.getCmp(cmpId).biodatabasePropertyStore.getAt(0).data.alignment_file_url;
          var alignmentViewPanel = Ext.getCmp(this.alignmentViewPanelId);
          if (alignmentViewPanel) {
            alignmentViewPanel.updateContent({
              url: strUrl
            });
          }
        //          alignemExt.getCmp(this.alignmentViewPanelId).updateContent(strUrl);
        //          window.open(strUrl);
        }
      }
      , '->', {
        text: 'Delete',
        iconCls:'x-tree-delete',
        handler: onDelete
      }
      ]
    });

    Ext.bio.BiosequenceGrid.superclass.initComponent.call(this);
  },
  updateViewPanel: function(params) {
    var viewPanel = Ext.getCmp(this.biosequenceViewPanelId);
    viewPanel.updateContent(params);
  },
  listeners: {
    afterrender: function( p)  {
      var viewPanel = Ext.getCmp(this.biosequenceViewPanelId);
      viewPanel.setSource(this.store);
    },
    rowclick: function (grid, rowIndex, e) {
      var params = {
        rowIndex: rowIndex
      };
      grid.updateViewPanel(params);
    },
    cellclick: function (grid, rowIndex,columnIndex, e) {
      var fieldName = grid.getColumnModel().getColumnHeader(columnIndex);
      if (fieldName == 'Action'){
        var rec = grid.store.getAt(rowIndex); // getSelectionModel().getSelected();
        if (rec) {
          Ext.MessageBox.confirm('Confirm', 'Are you sure you want to delete "' + rec.data.name +'"?',
            function(btn){
              if (btn == 'yes') {
                grid.store.remove(rec);
                grid.selModel.selectRow(rowIndex);
                grid.updateViewPanel({
                  rowIndex: rowIndex
                });
              }
            });
          return false;
        }
      }
    }

  },
  updateContent: function(params) {
    if (params.biodatabase_id) {
      this.store.baseParams.biodatabase_id = params.biodatabase_id;
      this.store.load({
        params: {
          start: 0,
          limit: this.pageSize
        }
      } );
      var alignmentViewPanelId = this.alignmentViewPanelId;
      this.biodatabasePropertyStore.load({
        params:{
          id:params.biodatabase_id
        },
        callback: function(store, records, options){
          var tbFasta = Ext.getCmp('seq-grid-fasta-toolbar-item');
          //          var tbAlign = Ext.getCmp('seq-grid-alignment-toolbar-item');
          if (tbFasta) {
            if (this.getAt(0).data.fasta_file_url){
              tbFasta.show();
            } else {
              tbFasta.hide();
            }
          }
          // Update the alignment page..
          var alignmentViewPanel = Ext.getCmp(alignmentViewPanelId );
          if (this.getAt(0).data.alignment_file_url){
            var url = this.getAt(0).data.alignment_file_url;
            if (alignmentViewPanel) {
              alignmentViewPanel.updateContent({
                url: url
              });
            }
          } else {
            alignmentViewPanel.clearContent();
          }
        }
      });
    }
  },
  clearContent : function() {
    this.store.reload();
  }

});
Ext.reg('biosequence-grid', Ext.bio.BiosequenceGrid);
<|endoftext|>


<commit_before>// @flow
import type { IncomingRequest, OutgoingResponse } from 'http' // = NODE ONLY

// import {
//   decodeRequest,
//   encodeResponse,
//   getStatusCode,
// } from 'phenyl-http-rules/jsnext'

// import {
//   createErrorResult,
// } from 'phenyl-utils'

import type {
  RequestData,
  ResponseData,
} from 'phenyl-interfaces'

export default class PhenylHTTPServer {
  server: net$Server

  constructor(httpModule, options: Object) {
    this.server = httpModule.createServer(options, this.onRequest)
  }

  /**
   *
   */
  listen(port: number, hostname: string, backlog: number, callback: Function) {
    this.server.listen(port, hostname, backlog, callback)
  }

  /**
   * @private
   * @param {IncomingRequest} request
   * @param {OutgoingResponse} response
   */
  onRequest(request: IncomingRequest, response: OutgoingResponse) {
    // TODO: Implement
  }
}
<commit_msg>:sparkles: Implement onRequest<commit_after>// @flow
import type {
  IncomingMessage,
  ServerResponse,
} from 'http'
import type {
  RequestData,
  ResponseData,
  PhenylRunner,
} from 'phenyl-interfaces'

import url from 'url'
import {
  decodeRequest,
  encodeResponse,
  getStatusCode,
} from 'phenyl-http-rules/jsnext'
import {
  createErrorResult,
} from 'phenyl-utils'

export default class PhenylHTTPServer {
  server: net$Server
  phenylCore: PhenylRunner

  constructor(server: net$Server, phenylCore: PhenylRunner) {
    this.server = server
    this.phenylCore = phenylCore
    this.onRequest = this.onRequest.bind(this)
  }

  /**
   *
   */
  listen(port: number, hostname: string, backlog: number, callback: Function) {
    this.server.on('request', this.onRequest)
    this.server.listen(port, hostname, backlog, callback)
  }

  getRequestBody(request: IncomingMessage): Promise<string> {
    return new Promise((resolve, reject) => {
      // https://nodejs.org/api/stream.html#stream_readable_read_size
      request.on('readable', () => {
        const chunks = []
        let chunk
        let totalLength = 0
        while (null !== (chunk = request.read())) {
          chunks.push(chunk)
          totalLength += chunk.length
        }
        resolve(Buffer.concat(chunks, totalLength).toString('utf8'))
      })
    })
  }

  /**
   * @private
   * @param {IncomingMessage} request
   * @param {ServerResponse} response
   */
  async onRequest(request: IncomingMessage, response: ServerResponse) {
    const requestUrl = url.parse(request.url, true)
    let responseData

    try {
      // 1. Decoding Request
      const [requestData, sessionId] = decodeRequest({
        method: request.method,
        path: requestUrl.pathname,
        body: await this.getRequestBody(request),
        headers: request.headers,
        queryString: requestUrl.query,
      })
      // 2. Invoking PhenylCore
      responseData = await this.phenylCore.run(requestData, sessionId)
    }
    catch (err) {
      responseData = { error: createErrorResult(err) }
    }

    // 3. Encoding Response
    const statusCode = getStatusCode(responseData)
    const body = JSON.stringify(encodeResponse(responseData))
    const headers = {
      'Content-Length': Buffer.byteLength(body),
      'Content-Type': 'application/json',
    }
    response.writeHead(statusCode, headers)
    response.write(body)
  }
}
<|endoftext|>