<commit_before>import undoable, { distinctState, excludeAction } from 'redux-undo'
import { ADD_PLAYER, REMOVE_PLAYER, EDIT_PLAYER, CHANGE_SCORE, RECORD_HIT, MOVE_PLAYER_UP, MOVE_PLAYER_DOWN, NEXT_PLAYER, START_GAME } from '../actions'
import { hits, BEFORE_GAME, DURING_GAME, AFTER_GAME } from '../defaults/'

const isPlayerFirst = (players, player) => players.indexOf(player) === 0;

const isPlayerLast = (players, player) => players.indexOf(player) === players.length -1;

const moveDown = (players, player) => {
  const playerId = players.indexOf(player);

  return [...players.slice(0, playerId), players[playerId+1], players[playerId], ...players.slice(playerId+2)];
}

const moveUp = (players, player) => {
  const playerId = players.indexOf(player);

  return [...players.slice(0, playerId - 1), players[playerId], players[playerId-1], ...players.slice(playerId+1)];
}

const isValidHit = (hits, currentHit) => {
  return typeof hits[currentHit] === 'number';
}

const updateHits = (hits, currentHit) => {
  if (isValidHit(hits, currentHit)) {
    return {...hits, [currentHit]: hits[currentHit] + 1};
  }
  return hits;
}

const hasPlayerClosed = (hits, number) => {
  return hits[number] >= 3;
}

const updateScores = (player, hit, players) => {
  if (hasPlayerClosed(player.hits, hit)) {
    const extraHits = player.hits[hit] - 3;
    return players.map(p => {
      if (!hasPlayerClosed(p.hits, hit) && p !== player){
        p.score += hit;
      }
      return p;
    })
  }
  return players;
}

const getCurrentPlayer = (players, curentPlayerId) => {
  return players.find(player => player.id === curentPlayerId);
}

function main(state = {}, action) {
  const updatedPlayers = players(state.players, action);
  let currentPlayerId = updatedPlayers[0].id;
  switch (action.type) {
    case START_GAME:
      return {...state, players: updatedPlayers, gameStage: DURING_GAME }
    case REMOVE_PLAYER:
    case MOVE_PLAYER_UP:
    case MOVE_PLAYER_DOWN:
      return {...state, players: updatedPlayers, currentPlayerId};
    case RECORD_HIT:
      if (isValidHit(hits, action.hit)) return {...state, players: updatedPlayers, lastHit: action}
      return state;
    case NEXT_PLAYER:
      const players = state.players;
      const currentPlayer = getCurrentPlayer(state.players, state.currentPlayerId);
      const indexOfPlayer = players.indexOf(currentPlayer);
      const newCurrentPlayerId = (indexOfPlayer === players.length - 1) ? 0 : indexOfPlayer + 1;
      currentPlayerId = players[newCurrentPlayerId].id;
      return {...state, currentPlayerId}
    default:
      return {...state, players: updatedPlayers}
  }
}

function players(players = [], action) {
  const currentPlayer = players.find(player => player.id === action.id);
  switch (action.type) {
    case ADD_PLAYER:
      return [
        ...players,
        {
          name: action.name,
          id: action.id,
          score: 0,
          hits
        }
      ]
    case REMOVE_PLAYER:
      return players.filter(player => player.id !== action.id);
    case EDIT_PLAYER:
      return players.map(player => {
        if (player.id === action.id) {
          return { ...player, name: action.name }
        }
        return player;
      })
    case CHANGE_SCORE:
      return players.map(player => {
        if (player.id === action.id) {
          return { ...player, score: action.score }
        }
        return player;
      })
    case RECORD_HIT:
      const playersAfterHitRecorded  = players.map(player => {
        if (player.id === action.id) {
          const hits = updateHits(player.hits, action.hit);
          return {...player, hits};
        }
        return player;
      });
      return updateScores(currentPlayer, action.hit, playersAfterHitRecorded);
    case MOVE_PLAYER_UP:
      if (!isPlayerFirst(players, currentPlayer)) {
        return moveUp(players, currentPlayer);
      }
      return players;
    case MOVE_PLAYER_DOWN:
      if (!isPlayerLast(players, currentPlayer)) {
        return moveDown(players, currentPlayer);
      }
    default:
      return players
  }
}

const dartsApp = undoable(main, {
  filter: excludeAction([ADD_PLAYER, START_GAME])
});

export default dartsApp
<commit_msg>adding game over condition<commit_after>import undoable, { distinctState, excludeAction } from 'redux-undo'
import { ADD_PLAYER, REMOVE_PLAYER, EDIT_PLAYER, CHANGE_SCORE, RECORD_HIT, MOVE_PLAYER_UP, MOVE_PLAYER_DOWN, NEXT_PLAYER, START_GAME } from '../actions'
import { hits, BEFORE_GAME, DURING_GAME, AFTER_GAME } from '../defaults/'

const isPlayerFirst = (players, player) => players.indexOf(player) === 0;

const isPlayerLast = (players, player) => players.indexOf(player) === players.length -1;

const moveDown = (players, player) => {
  const playerId = players.indexOf(player);

  return [...players.slice(0, playerId), players[playerId+1], players[playerId], ...players.slice(playerId+2)];
}

const moveUp = (players, player) => {
  const playerId = players.indexOf(player);

  return [...players.slice(0, playerId - 1), players[playerId], players[playerId-1], ...players.slice(playerId+1)];
}

const isValidHit = (hits, currentHit) => {
  return typeof hits[currentHit] === 'number';
}

const isGameOver = (players) => {
  for (let i = 0; i < players.length; i++) {
    if (Object.keys(players[i].hits).filter(h => players[i].hits[h] < 3).length === 0) return true
  }
  return false;
}

const updateHits = (hits, currentHit) => {
  if (isValidHit(hits, currentHit)) {
    return {...hits, [currentHit]: hits[currentHit] + 1};
  }
  return hits;
}

const hasPlayerClosed = (hits, number) => {
  return hits[number] >= 3;
}

const updateScores = (player, hit, players) => {
  if (hasPlayerClosed(player.hits, hit)) {
    const extraHits = player.hits[hit] - 3;
    return players.map(p => {
      if (!hasPlayerClosed(p.hits, hit) && p !== player){
        p.score += hit;
      }
      return p;
    })
  }
  return players;
}

const getCurrentPlayer = (players, curentPlayerId) => {
  return players.find(player => player.id === curentPlayerId);
}

function main(state = {}, action) {
  const updatedPlayers = players(state.players, action);
  let currentPlayerId = updatedPlayers[0].id;
  switch (action.type) {
    case START_GAME:
      return {...state, players: updatedPlayers, gameStage: DURING_GAME }
    case REMOVE_PLAYER:
    case MOVE_PLAYER_UP:
    case MOVE_PLAYER_DOWN:
      return {...state, players: updatedPlayers, currentPlayerId};
    case RECORD_HIT:
      if (!isValidHit(hits, action.hit)) return state;
      const newGameStage =  isGameOver(updatedPlayers) ? AFTER_GAME : DURING_GAME;

      return {...state, players: updatedPlayers, lastHit: action, gameStage: newGameStage}
    case NEXT_PLAYER:
      const players = state.players;
      const currentPlayer = getCurrentPlayer(state.players, state.currentPlayerId);
      const indexOfPlayer = players.indexOf(currentPlayer);
      const newCurrentPlayerId = (indexOfPlayer === players.length - 1) ? 0 : indexOfPlayer + 1;
      currentPlayerId = players[newCurrentPlayerId].id;
      return {...state, currentPlayerId}
    default:
      return {...state, players: updatedPlayers}
  }
}

function players(players = [], action) {
  const currentPlayer = players.find(player => player.id === action.id);
  switch (action.type) {
    case ADD_PLAYER:
      return [
        ...players,
        {
          name: action.name,
          id: action.id,
          score: 0,
          hits
        }
      ]
    case REMOVE_PLAYER:
      return players.filter(player => player.id !== action.id);
    case EDIT_PLAYER:
      return players.map(player => {
        if (player.id === action.id) {
          return { ...player, name: action.name }
        }
        return player;
      })
    case CHANGE_SCORE:
      return players.map(player => {
        if (player.id === action.id) {
          return { ...player, score: action.score }
        }
        return player;
      })
    case RECORD_HIT:
      const playersAfterHitRecorded  = players.map(player => {
        if (player.id === action.id) {
          const hits = updateHits(player.hits, action.hit);
          return {...player, hits};
        }
        return player;
      });
      return updateScores(currentPlayer, action.hit, playersAfterHitRecorded);
    case MOVE_PLAYER_UP:
      if (!isPlayerFirst(players, currentPlayer)) {
        return moveUp(players, currentPlayer);
      }
      return players;
    case MOVE_PLAYER_DOWN:
      if (!isPlayerLast(players, currentPlayer)) {
        return moveDown(players, currentPlayer);
      }
    default:
      return players
  }
}

const dartsApp = undoable(main, {
  filter: excludeAction([ADD_PLAYER, START_GAME])
});

export default dartsApp
<|endoftext|>


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

var CleanPlugin = require('clean-webpack-plugin');
var CopyPlugin = require('copy-webpack-plugin');
var HtmlPlugin = require('html-webpack-plugin');

__dirname = path.resolve(__dirname, '..');

var examples = require('../app/examples/index.json');

// Compute entry points for the examples.
var entryPoints = examples.map(function (ex) {
  return {
    key: 'examples/' + ex.link,
    value: './app/examples/' + ex.link + '/index.js'
  };
});

var entry = {
  examples: './app/examples/index.js'
};

entryPoints.forEach(function (ep) {
  entry[ep.key] = ep.value;
});

// Compute HTML file stubs for the examples.
var htmlPlugins = examples.map(function (ex) {
  return new HtmlPlugin({
    title: ex.title,
    filename: 'examples/' + ex.link + '/index.html',
    chunks: ['examples/' + ex.link]
  });
});

var plugins = [
  new CleanPlugin([path.resolve(__dirname, 'build/examples')], {
    root: __dirname
  }),

  new HtmlPlugin({
    title: 'Candela Examples',
    filename: 'examples/index.html',
    chunks: ['examples']
  })
];

htmlPlugins.forEach(function (hp) {
  plugins.push(hp);
});

module.exports = {
  __dirname: __dirname,
  entry: entry,
  output: {
    library: '[name]',
    libraryTarget: 'umd',
    path: 'build',
    filename: '[name]/[name].js'
  },
  plugins: plugins,
  module: {
    loaders: [
      {
        test: /\.js$/,
        loader: 'babel-loader',
        query: {
          presets: ['es2015']
        },
        include: [
          __dirname + '/app',
          __dirname + '/index.js',
          __dirname + '/components',
          __dirname + '/test',
          __dirname + '/util',
          __dirname + '/VisComponent'
        ]
      },
      {
        test: function (path) {
          return path.endsWith('/src/external/pc.js');
        },
        loader: 'legacy-loader'
      },
      {
        test: /\.jpe?g$|\.gif$|\.png$|\.woff$|\.wav$|\.mp3$|\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$|\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
        loader: 'url-loader'
      },
      {
        test: /\.csv$/,
        loader: 'raw-loader'
      },
      {
        test: /\.html$/,
        loader: 'html-loader?attrs=img:src'
      },
      {
        test: /\.styl$/,
        loaders: ['style-loader', 'css-loader', 'stylus-loader']
      },
      {
        test: /\.css$/,
        loaders: ['style-loader', 'css-loader']
      },
      {
        test: /\.scss$/,
        loaders: ['style-loader', 'css-loader', 'sass-loader']
      },
      {
        test: /\.jade$/,
        loaders: ['jade-loader']
      },
      {
        test: /\.json$/,
        loaders: ['json-loader', 'strip-json-comments-loader']
      },
      {
        test: /bootstrap\/js\//,
        loader: 'imports?jQuery=jquery'
      }
    ]
  }
};
<commit_msg>Fix examples webpack<commit_after>var webpack = require('webpack');
var path = require('path');

var CleanPlugin = require('clean-webpack-plugin');
var CopyPlugin = require('copy-webpack-plugin');
var HtmlPlugin = require('html-webpack-plugin');

__dirname = path.resolve(__dirname, '..');

var examples = require('../app/examples/index.json');

// Compute entry points for the examples.
var entryPoints = examples.map(function (ex) {
  return {
    key: 'examples/' + ex.link,
    value: './app/examples/' + ex.link + '/index.js'
  };
});

var entry = {
  examples: './app/examples/index.js'
};

entryPoints.forEach(function (ep) {
  entry[ep.key] = ep.value;
});

// Compute HTML file stubs for the examples.
var htmlPlugins = examples.map(function (ex) {
  return new HtmlPlugin({
    title: ex.title,
    filename: 'examples/' + ex.link + '/index.html',
    chunks: ['examples/' + ex.link]
  });
});

var plugins = [
  new CleanPlugin([path.resolve(__dirname, 'build/examples')], {
    root: __dirname
  }),

  new HtmlPlugin({
    title: 'Candela Examples',
    filename: 'examples/index.html',
    chunks: ['examples']
  })
];

htmlPlugins.forEach(function (hp) {
  plugins.push(hp);
});

module.exports = {
  __dirname: __dirname,
  entry: entry,
  output: {
    library: '[name]',
    libraryTarget: 'umd',
    path: 'build',
    filename: '[name]/[name].js'
  },
  plugins: plugins,
  module: {
    loaders: [
      {
        test: /\.js$/,
        loader: 'babel-loader',
        query: {
          presets: ['es2015']
        },
        include: [
          __dirname + '/app',
          __dirname + '/candela.js',
          __dirname + '/components',
          __dirname + '/test',
          __dirname + '/util',
          __dirname + '/VisComponent'
        ]
      },
      {
        test: function (path) {
          return path.endsWith('/src/external/pc.js');
        },
        loader: 'legacy-loader'
      },
      {
        test: /\.jpe?g$|\.gif$|\.png$|\.woff$|\.wav$|\.mp3$|\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$|\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
        loader: 'url-loader'
      },
      {
        test: /\.csv$/,
        loader: 'raw-loader'
      },
      {
        test: /\.html$/,
        loader: 'html-loader?attrs=img:src'
      },
      {
        test: /\.styl$/,
        loaders: ['style-loader', 'css-loader', 'stylus-loader']
      },
      {
        test: /\.css$/,
        loaders: ['style-loader', 'css-loader']
      },
      {
        test: /\.scss$/,
        loaders: ['style-loader', 'css-loader', 'sass-loader']
      },
      {
        test: /\.jade$/,
        loaders: ['jade-loader']
      },
      {
        test: /\.json$/,
        loaders: ['json-loader', 'strip-json-comments-loader']
      },
      {
        test: /bootstrap\/js\//,
        loader: 'imports?jQuery=jquery'
      }
    ]
  }
};
<|endoftext|>


<commit_before>angular.module("omniControllers")
	.controller("DExOverviewController", ["$scope","Account","Orderbook","Wallet","PropertyManager","$http"
		function DExOverviewController($scope,Account,Orderbook,Wallet,PropertyManager,$http){
			$scope.isLoggedIn = Account.isLoggedIn;
			$scope.markets = [];
			$scope.noMarkets = true;
			$scope.ecosystem = 1;
			$scope.setEcosystem = function(ecosystem){
				$scope.ecosystem = ecosystem;
			};

			$http.post('/v1/markets/designatingcurrencies',{ecosystem:$scope.ecosystem}).success(
				function(response) {
					$scope.designatingcurrencies = response.data.currencies;
				}
			);

	}]);<commit_msg>Fixes for markets view<commit_after>angular.module("omniControllers")
	.controller("DExOverviewController", ["$scope","Account","Orderbook","Wallet","PropertyManager","$http"
		function DExOverviewController($scope,Account,Orderbook,Wallet,PropertyManager,$http){
			$scope.isLoggedIn = Account.isLoggedIn;
			$scope.markets = [];
			$scope.noMarkets = true;
			$scope.ecosystem = 1;
			$scope.setEcosystem = function(ecosystem){
				$scope.ecosystem = ecosystem;
			};

			$http.post('/v1/markets/designatingcurrencies',{ecosystem:$scope.ecosystem}).success(function(response) {$scope.designatingcurrencies = response.data.currencies;});

	}]);<|endoftext|>


<commit_before>'use strict';

angular.module('ximsApp')
  .value('AppSettings', {
    pagination: {maxSize: 3, itemsPerPage: 10
    }
  });<commit_msg>adding employee alert types to app settings.<commit_after>'use strict';

angular.module('ximsApp')
  .value('AppSettings', {
    pagination: {maxSize: 3, itemsPerPage: 10},
    employeeAlertsType: {riskInsuranceExpired: 1,
      medicalExamExpired: 2, noInductionTraining: 3}
  });<|endoftext|>


<commit_before>// Filename: views/device/weatherStation.js
define([
	'jquery',
	'underscore',
	'backbone',
	'toastr',
	'models/variable',
	'views/device/baseStatus',
	'i18n!nls/strings',
	'text!templates/device/weatherStation.html'
], function($, _, Backbone, toastr, Variable, BaseStatusView, strings, template) {

	return BaseStatusView.extend({

		template: _.template(template),

		events: {
			'click #switchButton': 'onClick'
		},

		render: function(el) {
			var windDir = this.variables.windDirDeg.value;

			if (windDir) {
				windDir = Math.ceil(windDir/45.0) * 45.0;
			}

			this.$el.html(this.template({
				strings: strings,
        available: this.available,
				variables: this.variables,
				windDir: windDir
			}));

			return this;
		},

		onVariableUpdate: function(name, value) {
			this.render();
		}

	});

});
<commit_msg>Fixed bug with display weather station data with no wind info.<commit_after>// Filename: views/device/weatherStation.js
define([
	'jquery',
	'underscore',
	'backbone',
	'toastr',
	'models/variable',
	'views/device/baseStatus',
	'i18n!nls/strings',
	'text!templates/device/weatherStation.html'
], function($, _, Backbone, toastr, Variable, BaseStatusView, strings, template) {

	return BaseStatusView.extend({

		template: _.template(template),

		events: {
			'click #switchButton': 'onClick'
		},

		render: function(el) {
			var windDir = (this.variables.windDirDeg) ? this.variables.windDirDeg.value : null;

			if (windDir) {
				windDir = Math.ceil(windDir/45.0) * 45.0;
			}

			this.$el.html(this.template({
				strings: strings,
        available: this.available,
				variables: this.variables,
				windDir: windDir
			}));

			return this;
		},

		onVariableUpdate: function(name, value) {
			this.render();
		}

	});

});
<|endoftext|>


<commit_before>/*global exports, require*/
var _ = require('underscore'),
    nextId = 1;

function Base(config) {
    _.extend(this, config);
    this.id = nextId;
    nextId += 1;
}

_.extend(Base.prototype, {
    toString: function () {
        return "[" + this.type + "/" + this.id + "]";
    }
});

exports.Base = Base;
<commit_msg>relations.Base.toString: Report attached assets.<commit_after>/*global exports, require*/
var _ = require('underscore'),
    nextId = 1;

function Base(config) {
    _.extend(this, config);
    this.id = nextId;
    nextId += 1;
}

_.extend(Base.prototype, {
    toString: function () {
        return "[" + this.type + "/" + this.id + ": " + ((this.from && this.to) ? this.from.toString() + " => " + this.to.toString() : " unattached") + "]";
    }
});

exports.Base = Base;
<|endoftext|>


<commit_before>requirejs.config({
  baseUrl: '/',
  paths: {
    jquery: 'lib/jquery/jquery',
	jasmine: 'lib/jasmine/lib/jasmine-core/jasmine',
    'jasmine-html': 'lib/jasmine/lib/jasmine-core/jasmine-html',
    'jasmine-jquery': 'lib/jasmine-jquery/lib/jasmine-jquery',
    text: 'lib/requirejs-text/text',
    hgn: 'lib/requirejs-hogan-plugin/hgn',
    hogan: 'lib/hogan/web/builds/2.0.0/hogan-2.0.0.amd',
    json: 'lib/requirejs-plugins/src/json',
    base64: 'lib/base64/base64',
    'event-emitter': 'lib/event-emitter/src/event-emitter',
    inherits: 'lib/inherits/inherits',
    d3: 'lib/d3/d3',
    colorbrewer: 'lib/colorbrewer/colorbrewer',
    topojson: 'lib/topojson/topojson'
  },
  packages: [{
    name: "streamhub-sdk",
    location: "lib/streamhub-sdk/src/"
  },{
    name: "streamhub-sdk/auth",
    location: "lib/streamhub-sdk/src/auth"
  },{
    name: "streamhub-sdk/collection",
    location: "lib/streamhub-sdk/src/collection"
  },{
    name: "streamhub-sdk/content",
    location: "lib/streamhub-sdk/src/content"
  },{
    name: "streamhub-sdk/modal",
    location: "lib/streamhub-sdk/src/modal"
  },{
    name: "streamhub-sdk-tests",
    location: "lib/streamhub-sdk/tests/"
  },{
    name: "stream",
    location: "lib/stream/src"
  },{
	name: "streamhub-map",
  	location: "src"
  },{
    name: "streamhub-map-resources",
    location: "src/resources/"
  },{
    name: "streamhub-hot-collections",
    location: "lib/streamhub-hot-collections/src/"
  },{
    name: "streamhub-hot-collections-tests",
    location: "lib/streamhub-hot-collections/tests/"
  },{
    name: "streamhub-metrics",
    location: "lib/streamhub-metrics/src/"
  },{
    name: "view",
    location: "lib/view/src",
    main: "view"
  },{
    name: 'leaflet',
    location: 'lib/leaflet/',
    main: 'leaflet-src'
  },{
    name: 'leaflet-markercluster',
    location: 'lib/leaflet-markercluster/dist/',
    main: 'leaflet.markercluster-src'
  }],
  shim: {
    jasmine: {
      exports: 'jasmine'
    },
    'jasmine-html': {
      deps: ['jasmine'],
      exports: 'jasmine'
    },
    'jasmine-jquery': {
      deps: ['jquery', 'jasmine']
    },
    jquery: {
        exports: '$'
    },
    d3: {
        exports: 'd3'
    },
    colorbrewer: {
        exports: 'colorbrewer'
    },
    topojson: {
        exports: 'topojson'
    },
    'leaflet-markercluster': {
        deps: ['leaflet']
    }
  },
  urlArgs: "_=" +  (new Date()).getTime()
});
<commit_msg>Remove unused deps from requirejs.conf<commit_after>requirejs.config({
  baseUrl: '/',
  paths: {
    jquery: 'lib/jquery/jquery',
	jasmine: 'lib/jasmine/lib/jasmine-core/jasmine',
    'jasmine-html': 'lib/jasmine/lib/jasmine-core/jasmine-html',
    'jasmine-jquery': 'lib/jasmine-jquery/lib/jasmine-jquery',
    text: 'lib/requirejs-text/text',
    hgn: 'lib/requirejs-hogan-plugin/hgn',
    hogan: 'lib/hogan/web/builds/2.0.0/hogan-2.0.0.amd',
    json: 'lib/requirejs-plugins/src/json',
    base64: 'lib/base64/base64',
    'event-emitter': 'lib/event-emitter/src/event-emitter',
    inherits: 'lib/inherits/inherits'
  },
  packages: [{
    name: "streamhub-sdk",
    location: "lib/streamhub-sdk/src/"
  },{
    name: "streamhub-sdk/auth",
    location: "lib/streamhub-sdk/src/auth"
  },{
    name: "streamhub-sdk/collection",
    location: "lib/streamhub-sdk/src/collection"
  },{
    name: "streamhub-sdk/content",
    location: "lib/streamhub-sdk/src/content"
  },{
    name: "streamhub-sdk/modal",
    location: "lib/streamhub-sdk/src/modal"
  },{
    name: "streamhub-sdk-tests",
    location: "lib/streamhub-sdk/tests/"
  },{
    name: "stream",
    location: "lib/stream/src"
  },{
	name: "streamhub-map",
  	location: "src"
  },{
    name: "streamhub-map-resources",
    location: "src/resources/"
  },{
    name: "streamhub-hot-collections",
    location: "lib/streamhub-hot-collections/src/"
  },{
    name: "streamhub-hot-collections-tests",
    location: "lib/streamhub-hot-collections/tests/"
  },{
    name: "streamhub-metrics",
    location: "lib/streamhub-metrics/src/"
  },{
    name: "view",
    location: "lib/view/src",
    main: "view"
  },{
    name: 'leaflet',
    location: 'lib/leaflet/',
    main: 'leaflet-src'
  },{
    name: 'leaflet-markercluster',
    location: 'lib/leaflet-markercluster/dist/',
    main: 'leaflet.markercluster-src'
  }],
  shim: {
    jasmine: {
      exports: 'jasmine'
    },
    'jasmine-html': {
      deps: ['jasmine'],
      exports: 'jasmine'
    },
    'jasmine-jquery': {
      deps: ['jquery', 'jasmine']
    },
    jquery: {
        exports: '$'
    },
    d3: {
        exports: 'd3'
    },
    colorbrewer: {
        exports: 'colorbrewer'
    },
    topojson: {
        exports: 'topojson'
    },
    'leaflet-markercluster': {
        deps: ['leaflet']
    }
  },
  urlArgs: "_=" +  (new Date()).getTime()
});
<|endoftext|>


<commit_before>angular.module('dogfeed', [
    'ngFeeds',
    'ngSockethubClient',
    'ngSockethubRemoteStorage',
    'ngRemoteStorage',
    'ngMessages',
    'ngRoute'
]).

/**
 * routes
 */
config(['$routeProvider', '$locationProvider',
function ($routeProvider, $locationProvider) {
  $locationProvider.html5Mode(true);
  $routeProvider.
    when('/', {
      templateUrl: "/res/views/main.html"
    }).
    when('/settings/sockethub', {
      templateUrl: "sockethub-settings.html"
    }).
    when('/feeds/add', {
      templateUrl: '/res/js/feeds/feed-add.html.tpl'
    }).
    when('/feeds/edit/:feed', {
      templateUrl: '/res/js/feeds/feed-edit.html.tpl'
    }).
    when('/feeds/:feed', {
      templateUrl: 'main.html'
    }).
    when('/about', {
      templateUrl: 'about.html'
    }).
    otherwise({
      redirectTo: "/"
    });
}]).

run(['$rootScope', '$timeout',
function ($rootScope, $timeout) {
  $rootScope.delayed = false;
  $timeout(function () {
    // give the app a second or two to load before we determine if the user
    // is logged in or not.
    $rootScope.delayed = true;
  }, 3000);
}]).

run([function () {
  // TODO
  // this should be executed when we know the appropriate dom elements are
  // loaded.
  // right now if someone *starts* on the settings page, this will be executed
  // and wont bind to anything as the contacts view was not registered.
  setTimeout(function () {
    $(document).ready(function() {
      $('[data-toggle=offcanvas]').click(function() {
        $('.opposite-sidebar').toggleClass('slider-active');
      });
      $("[name='showRead']").bootstrapSwitch('size', 'small');
    });
  }, 500);
}]).

/**
 * remotestorage config
 */
run(['RemoteStorageConfig',
function (RScfg) {
  RScfg.modules = [
    ['sockethub', 'rw', {'cache': true, 'public': false}],
    ['feeds', 'rw', {'cache': true, 'public': false}],
    ['articles', 'rw', {'cache': true, 'public': false}]
  ];
}]).

/**
 * messages config
 */
run(['MessagesConfig',
function (cfg) {
  cfg.timeout = 15000;
}]).

/**
 * get sockethub settings and try to connect
 */
run(['SockethubBootstrap',
function (SockethubBootstrap) {
  SockethubBootstrap.run('dogfeed', {
    // default connection settings, if none found in remoteStorage
    host: 'silverbucket.net',
    port: '443',
    path: '/sockethub',
    tls: true,
    secret: '1234567890'
  });
}]).

/**
 * remoteStorage
 */
run(['$rootScope', 'RS', '$timeout',
function ($rootScope, RS, $timeout) {
  // set custom messages
  var dict = RemoteStorage.I18n.getDictionary();
  dict.view_connect = "Login";
  RemoteStorage.I18n.setDictionary(dict);

  // check if connected
  if (!RS.isConnected()) {
    $timeout(function () {
      if (!RS.isConnected()) {
        $rootScope.$broadcast('message', {message: 'remotestorage-connect', timeout: false});
      }
    }, 3000);
  }
}]).

/**
 * listeners/emitters
 */
run(['$rootScope', '$location',
function ($rootScope, $location) {
  $rootScope.$on('sockethubSettingsSaved', function() {
    $location.path('/');
  });
}]).

/**
 * filter: fromNow (date)
 */
filter('fromNow', [
function() {
  return function (dateString) {
    return new Date(dateString).toDateString(); ///moment(new Date(dateString)).fromNow();
  };
}]).

/**
 * filter: pagination
 */
filter('pagination', [
function() {
  var count = 0;
  var max = 3;
  return function (article) {
    console.log("pagination received: ", article);
    if (!article) { return false; }
    count = count + 1;
    if (count > 10) {
      console.log('pagination returned false');
      return false;
    }
    console.log('pagination returned article: ',article);
    return article;
  };
}]).

///////////////////////////////////////////////////////////////////////////
//
// CONTROLLERS
//
///////////////////////////////////////////////////////////////////////////

/**
 * controller: titlebarCtrl
 */
controller('titlebarCtrl',
['$scope', '$rootScope', 'SockethubSettings', 'RS',
function ($scope, $rootScope, settings, RS) {

  $scope.showFeedList = function () {
    if ($rootScope.snapper.state().state === "left") {
      $rootScope.snapper.close();
    } else {
      $rootScope.snapper.open('left');
    }
  };

  $scope.$watch('settings.connected', function (newVal, oldVal) {
    if (settings.connected) {
      settings.conn.port = Number(settings.conn.port);
      RS.call('sockethub', 'writeConfig', ['dogfeed', settings.conn]).then(function () {
        console.log("Sockethub config saved to remoteStorage");
      }, function (err) {
        console.log('Failed saving Sockethub config to remoteStorage: ', err);
      });
    }
  });
}]).

controller('mainCtrl', ['$scope', 'RS', 'SH', '$timeout', '$rootScope', '$routeParams', 'Feeds',
function ($scope, RS, SH, $timeout, $rootScope, $routeParams, Feeds) {
  //console.log("mainCtrl ROUTE PARAMS: ", $routeParams);
  $scope.isConnected = function () {
    //console.log('isConnected: ['+RS.isConnected()+'] ['+SH.isConnected()+'] ['+$routeParams.feed+']');
    if ((RS.isConnected()) && (SH.isConnected())) {
      return true;
    } else {
      if ((($routeParams.feed) || (Feeds.data.articles.length > 0)) && (SH.isConnected())) {
        return true;
      } else {
        return false;
      }
    }
  };

  $scope.isConnecting = function () {
    //console.log('isConnecting: ['+RS.isConnected()+'] ['+SH.isConnected()+']');
    if ((RS.isConnecting()) || (SH.isConnecting())) {
      return true;
    } else {
      return false;
    }
  };

  $scope.delayed = function () {
    return $rootScope.delayed;
  };

  $scope.waitingForArticles = function () {
    if ((Feeds.data.articles.length <= 1) &&
        (Feeds.data.infoArray > 0)) {
      return true;
    } else {
      return false;
    }
  };

  $scope.haveArticles = function () {
    if (Feeds.data.articles.length > 0) {
      return true;
    } else {
      return false;
    }
  };

}]).

directive('loading', [
function () {
  return {
    restrict: 'E',
    templateUrl: 'loading.html'
  };
}]).

directive('welcome', [
function () {
  return {
    restrict: 'E',
    templateUrl: 'welcome.html'
  };
}]).

directive('about', [
function () {
  return {
    restrict: 'E',
    templateUrl: 'about.html'
  };
}]);
<commit_msg>what a long timeout<commit_after>angular.module('dogfeed', [
    'ngFeeds',
    'ngSockethubClient',
    'ngSockethubRemoteStorage',
    'ngRemoteStorage',
    'ngMessages',
    'ngRoute'
]).

/**
 * routes
 */
config(['$routeProvider', '$locationProvider',
function ($routeProvider, $locationProvider) {
  $locationProvider.html5Mode(true);
  $routeProvider.
    when('/', {
      templateUrl: "/res/views/main.html"
    }).
    when('/settings/sockethub', {
      templateUrl: "sockethub-settings.html"
    }).
    when('/feeds/add', {
      templateUrl: '/res/js/feeds/feed-add.html.tpl'
    }).
    when('/feeds/edit/:feed', {
      templateUrl: '/res/js/feeds/feed-edit.html.tpl'
    }).
    when('/feeds/:feed', {
      templateUrl: 'main.html'
    }).
    when('/about', {
      templateUrl: 'about.html'
    }).
    otherwise({
      redirectTo: "/"
    });
}]).

run(['$rootScope', '$timeout',
function ($rootScope, $timeout) {
  $rootScope.delayed = false;
  $timeout(function () {
    // give the app a second or two to load before we determine if the user
    // is logged in or not.
    $rootScope.delayed = true;
  }, 3000);
}]).

run([function () {
  // TODO
  // this should be executed when we know the appropriate dom elements are
  // loaded.
  // right now if someone *starts* on the settings page, this will be executed
  // and wont bind to anything as the contacts view was not registered.
  setTimeout(function () {
    $(document).ready(function() {
      $('[data-toggle=offcanvas]').click(function() {
        $('.opposite-sidebar').toggleClass('slider-active');
      });
      $("[name='showRead']").bootstrapSwitch('size', 'small');
    });
  }, 500);
}]).

/**
 * remotestorage config
 */
run(['RemoteStorageConfig',
function (RScfg) {
  RScfg.modules = [
    ['sockethub', 'rw', {'cache': true, 'public': false}],
    ['feeds', 'rw', {'cache': true, 'public': false}],
    ['articles', 'rw', {'cache': true, 'public': false}]
  ];
}]).

/**
 * messages config
 */
run(['MessagesConfig',
function (cfg) {
  //cfg.timeout = 15000;
}]).

/**
 * get sockethub settings and try to connect
 */
run(['SockethubBootstrap',
function (SockethubBootstrap) {
  SockethubBootstrap.run('dogfeed', {
    // default connection settings, if none found in remoteStorage
    host: 'silverbucket.net',
    port: '443',
    path: '/sockethub',
    tls: true,
    secret: '1234567890'
  });
}]).

/**
 * remoteStorage
 */
run(['$rootScope', 'RS', '$timeout',
function ($rootScope, RS, $timeout) {
  // set custom messages
  var dict = RemoteStorage.I18n.getDictionary();
  dict.view_connect = "Login";
  RemoteStorage.I18n.setDictionary(dict);

  // check if connected
  if (!RS.isConnected()) {
    $timeout(function () {
      if (!RS.isConnected()) {
        $rootScope.$broadcast('message', {message: 'remotestorage-connect', timeout: false});
      }
    }, 3000);
  }
}]).

/**
 * listeners/emitters
 */
run(['$rootScope', '$location',
function ($rootScope, $location) {
  $rootScope.$on('sockethubSettingsSaved', function() {
    $location.path('/');
  });
}]).

/**
 * filter: fromNow (date)
 */
filter('fromNow', [
function() {
  return function (dateString) {
    return new Date(dateString).toDateString(); ///moment(new Date(dateString)).fromNow();
  };
}]).

/**
 * filter: pagination
 */
filter('pagination', [
function() {
  var count = 0;
  var max = 3;
  return function (article) {
    console.log("pagination received: ", article);
    if (!article) { return false; }
    count = count + 1;
    if (count > 10) {
      console.log('pagination returned false');
      return false;
    }
    console.log('pagination returned article: ',article);
    return article;
  };
}]).

///////////////////////////////////////////////////////////////////////////
//
// CONTROLLERS
//
///////////////////////////////////////////////////////////////////////////

/**
 * controller: titlebarCtrl
 */
controller('titlebarCtrl',
['$scope', '$rootScope', 'SockethubSettings', 'RS',
function ($scope, $rootScope, settings, RS) {

  $scope.showFeedList = function () {
    if ($rootScope.snapper.state().state === "left") {
      $rootScope.snapper.close();
    } else {
      $rootScope.snapper.open('left');
    }
  };

  $scope.$watch('settings.connected', function (newVal, oldVal) {
    if (settings.connected) {
      settings.conn.port = Number(settings.conn.port);
      RS.call('sockethub', 'writeConfig', ['dogfeed', settings.conn]).then(function () {
        console.log("Sockethub config saved to remoteStorage");
      }, function (err) {
        console.log('Failed saving Sockethub config to remoteStorage: ', err);
      });
    }
  });
}]).

controller('mainCtrl', ['$scope', 'RS', 'SH', '$timeout', '$rootScope', '$routeParams', 'Feeds',
function ($scope, RS, SH, $timeout, $rootScope, $routeParams, Feeds) {
  //console.log("mainCtrl ROUTE PARAMS: ", $routeParams);
  $scope.isConnected = function () {
    //console.log('isConnected: ['+RS.isConnected()+'] ['+SH.isConnected()+'] ['+$routeParams.feed+']');
    if ((RS.isConnected()) && (SH.isConnected())) {
      return true;
    } else {
      if ((($routeParams.feed) || (Feeds.data.articles.length > 0)) && (SH.isConnected())) {
        return true;
      } else {
        return false;
      }
    }
  };

  $scope.isConnecting = function () {
    //console.log('isConnecting: ['+RS.isConnected()+'] ['+SH.isConnected()+']');
    if ((RS.isConnecting()) || (SH.isConnecting())) {
      return true;
    } else {
      return false;
    }
  };

  $scope.delayed = function () {
    return $rootScope.delayed;
  };

  $scope.waitingForArticles = function () {
    if ((Feeds.data.articles.length <= 1) &&
        (Feeds.data.infoArray > 0)) {
      return true;
    } else {
      return false;
    }
  };

  $scope.haveArticles = function () {
    if (Feeds.data.articles.length > 0) {
      return true;
    } else {
      return false;
    }
  };

}]).

directive('loading', [
function () {
  return {
    restrict: 'E',
    templateUrl: 'loading.html'
  };
}]).

directive('welcome', [
function () {
  return {
    restrict: 'E',
    templateUrl: 'welcome.html'
  };
}]).

directive('about', [
function () {
  return {
    restrict: 'E',
    templateUrl: 'about.html'
  };
}]);
<|endoftext|>


<commit_before>(function (angular) {
  'use strict';

  var PresenceService = function ($log, $interval, $rootScope, WindowVisibility, ReactiveWebSocket, UrlBuilder, callbackContainer) {

    var service = this;

    this.onOtherWatchersUpdated = callbackContainer();

    this.keepAliveTimeout = 10 * 1000;

    this._watcherId = new UUID(4).format();

    this._reference = null;

    this._otherWatchers = [];

    this.watchReference = function (reference) {
      this._reference = reference;

      if (WindowVisibility.isVisible()) {
        this._createWebSocket();
      }
    };

    this.pause = function () {
      this._closeWebSocket();
    };

    this.resume = function () {
      this._createWebSocket();
    };

    this.unwatch = function () {
      this._closeWebSocket();
    };

    this._createWebSocket = function () {
      if (!this._ws) {

        this._ws = ReactiveWebSocket();
        this._ws.url = UrlBuilder.createWebSocketUrl('/presence', {
          watcherId: this._watcherId,
          type: this._reference.type,
          reference: this._reference.reference
        });
        this._ws.encoder = angular.toJson;
        this._ws.decoder = angular.fromJson;

        this._ws.onOpen(function () {
          service._enableKeepAlive();
        });

        this._ws.onMessage(function (message) {
          $log.debug('Received message:', message);

          if (message.type === 'OTHER_WATCHERS') {
            service._updateWatchers(message.watcherIds);
          }
        });

        this._ws.onClose(function () {
          service._disableKeepAlive();
          service._ws = null;
          service._otherWatchers = [];

          service._updateWatchers([]);
        });

        this._ws.open();

      }
    };

    this._closeWebSocket = function () {
      if (this._ws) {
        this._ws.close();
        this._ws = null;
      }
    };

    this._keepAliveTimer = null;

    this._enableKeepAlive = function () {
      this._keepAliveTimer = $interval(function () {
        service._sendRefresh();
      }, this.keepAliveTimeout);
    };

    this._disableKeepAlive = function () {
      if (this._keepAliveTimer) {
        $interval.cancel(this._keepAliveTimer);
      }
    };

    this._updateWatchers = function (watcherIds) {
      var self = this;

      this._otherWatchers = watcherIds;
      $log.debug('Other watchers:', this._otherWatchers);

      $rootScope.$apply(function () {
        self.onOtherWatchersUpdated.invoke(service._otherWatchers);
      });

    };

    this._sendRefresh = function () {
      this._ws.send({ type: 'REFRESH' });
    };

    WindowVisibility.onVisible(function () {
      $log.debug('Visible, resuming');
      service.resume();
    });

    WindowVisibility.onHidden(function () {
      $log.debug('Hidden, pausing');
      service.pause();
    });

  };

  angular.module('zucchini-ui-frontend')
    .service('PresenceService', PresenceService);

})(angular);
<commit_msg>Fix WS closing bug<commit_after>(function (angular) {
  'use strict';

  var PresenceService = function ($log, $interval, $rootScope, WindowVisibility, ReactiveWebSocket, UrlBuilder, callbackContainer) {

    var service = this;

    this.onOtherWatchersUpdated = callbackContainer();

    this.keepAliveTimeout = 10 * 1000;

    this._watcherId = new UUID(4).format();

    this._reference = null;

    this._otherWatchers = [];

    this.watchReference = function (reference) {
      this._reference = reference;

      if (WindowVisibility.isVisible()) {
        this._createWebSocket();
      }
    };

    this.pause = function () {
      this._closeWebSocket();
    };

    this.resume = function () {
      this._createWebSocket();
    };

    this.unwatch = function () {
      this._closeWebSocket();
    };

    this._createWebSocket = function () {
      if (!this._ws) {

        this._ws = ReactiveWebSocket();
        this._ws.url = UrlBuilder.createWebSocketUrl('/presence', {
          watcherId: this._watcherId,
          type: this._reference.type,
          reference: this._reference.reference
        });
        this._ws.encoder = angular.toJson;
        this._ws.decoder = angular.fromJson;

        this._ws.onOpen(function () {
          service._enableKeepAlive();
        });

        this._ws.onMessage(function (message) {
          $log.debug('Received message:', message);

          if (message.type === 'OTHER_WATCHERS') {
            service._updateWatchers(message.watcherIds);
          }
        });

        this._ws.onClose(function () {
          service._disableKeepAlive();
          service._ws = null;
          service._otherWatchers = [];

          service._updateWatchers([]);
        });

        this._ws.open();

      }
    };

    this._closeWebSocket = function () {
      if (this._ws) {
        this._ws.close();
      }
    };

    this._keepAliveTimer = null;

    this._enableKeepAlive = function () {
      if (!this._keepAliveTimer) {
        this._keepAliveTimer = $interval(function () {
          service._sendRefresh();
        }, this.keepAliveTimeout);
      }
    };

    this._disableKeepAlive = function () {
      if (this._keepAliveTimer) {
        $interval.cancel(this._keepAliveTimer);
        this._keepAliveTimer = null;
      }
    };

    this._updateWatchers = function (watcherIds) {
      var self = this;

      this._otherWatchers = watcherIds;
      $log.debug('Other watchers:', this._otherWatchers);

      $rootScope.$apply(function () {
        self.onOtherWatchersUpdated.invoke(service._otherWatchers);
      });

    };

    this._sendRefresh = function () {
      if (this._ws) {
        this._ws.send({ type: 'REFRESH' });
      }
    };

    WindowVisibility.onVisible(function () {
      $log.debug('Visible, resuming');
      service.resume();
    });

    WindowVisibility.onHidden(function () {
      $log.debug('Hidden, pausing');
      service.pause();
    });

  };

  angular.module('zucchini-ui-frontend')
    .service('PresenceService', PresenceService);

})(angular);
<|endoftext|>


<commit_before>var roleHarvester = {

    run: function(creep, source) {

    	harvestEnergy(creep)

    	console.log("Harvester "+creep.name+" is harvesting "+creep.memory.harvesting);

    	if (creep.memory.harvesting) {
    		if(creep.harvest(source) == ERR_NOT_IN_RANGE) {
            creep.moveTo(source);
            return;
        }

    	var targets = getTargetsForEnergyTransfer();

        if(targets.length > 0) {

            if(creep.transfer(targets[0], RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                creep.moveTo(targets[0]);
            }
        }
    	}
	}
}

function getTargetsForEnergyTransfer(){
	return creep.room.find(FIND_STRUCTURES, {
        filter: (structure) => {
            return (structure.structureType == STRUCTURE_EXTENSION ||
                    structure.structureType == STRUCTURE_SPAWN ||
                    structure.structureType == STRUCTURE_TOWER) && structure.energy < structure.energyCapacity;
        }
	});
}

function setHarvestFlagForCreep(creep){
	if (creep.carry.energy == 0){
		 creep.memory.harvesting = true;
		 return;
	}

	if (creep.carry.energy == creep.carryCapacity){
		 creep.memory.harvesting = false;
		 return;
	}
}

module.exports = roleHarvester;<commit_msg>Bugfix<commit_after>var roleHarvester = {

    run: function(creep, source) {

    	setHarvestFlagForCreep(creep)

    	console.log("Harvester "+creep.name+" is harvesting "+creep.memory.harvesting);

    	if (creep.memory.harvesting) {
    		if(creep.harvest(source) == ERR_NOT_IN_RANGE) {
            creep.moveTo(source);
            return;
        }

    	var targets = getTargetsForEnergyTransfer();

        if(targets.length > 0) {

            if(creep.transfer(targets[0], RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                creep.moveTo(targets[0]);
            }
        }
    	}
	}
}

function getTargetsForEnergyTransfer(){
	return creep.room.find(FIND_STRUCTURES, {
        filter: (structure) => {
            return (structure.structureType == STRUCTURE_EXTENSION ||
                    structure.structureType == STRUCTURE_SPAWN ||
                    structure.structureType == STRUCTURE_TOWER) && structure.energy < structure.energyCapacity;
        }
	});
}

function setHarvestFlagForCreep(creep){
	if (creep.carry.energy == 0){
		 creep.memory.harvesting = true;
		 return;
	}

	if (creep.carry.energy == creep.carryCapacity){
		 creep.memory.harvesting = false;
		 return;
	}
}

module.exports = roleHarvester;<|endoftext|>


<commit_before>var roleHarvester = {

    run: function(creep, source) {

    	setHarvestFlagForCreep(creep)

    	console.log("Harvester "+creep.name+" is harvesting "+creep.memory.harvesting +" energy "+creep.carry.energy+" max "+creep.carryCapacity);

    	if (creep.memory.harvesting) {
    		if(creep.harvest(source) == ERR_NOT_IN_RANGE) {
    			creep.moveTo(source);
    		}
    	}else{
	    	var targets = getTargetsForEnergyTransfer(creep);

	        if(targets.length > 0) {

	            if(creep.transfer(targets[0], RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
	                creep.moveTo(targets[0]);
	            }
	        }
        }
    }
}

function getTargetsForEnergyTransfer(creep){
	return creep.room.find(FIND_STRUCTURES, {
        filter: (structure) => {
            return (structure.structureType == STRUCTURE_EXTENSION ||
                    structure.structureType == STRUCTURE_SPAWN ||
                    structure.structureType == STRUCTURE_TOWER) && structure.energy < structure.energyCapacity;
        }
	});
}

function setHarvestFlagForCreep(creep){
	if (creep.carry.energy == 0){
		 creep.memory.harvesting = true;
		 return;
	}

	if (creep.carry.energy == creep.carryCapacity){
		 creep.memory.harvesting = false;
		 return;
	}
}

module.exports = roleHarvester;<commit_msg>Harvester transfers all carried energy before harvesting again.<commit_after>var roleHarvester = {

    run: function(creep, source) {
    	setHarvestFlagForCreep(creep)

    	console.log("Harvester "+creep.name+" harvesting "+ creep.memory.harvesting+ " ernergy "+creep.carry.energy);

    	if (creep.memory.harvesting) {
    		if(creep.harvest(source) == ERR_NOT_IN_RANGE) {
    			creep.moveTo(source);
    		}
    	}else{
	    	var targets = getTargetsForEnergyTransfer(creep);

	        if(targets.length > 0) {

	            if(creep.transfer(targets[0], RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
	                creep.moveTo(targets[0]);
	            }
	        }
        }
    }
}

function getTargetsForEnergyTransfer(creep){
	return creep.room.find(FIND_STRUCTURES, {
        filter: (structure) => {
            return (structure.structureType == STRUCTURE_EXTENSION ||
                    structure.structureType == STRUCTURE_SPAWN ||
                    structure.structureType == STRUCTURE_TOWER) && structure.energy < structure.energyCapacity;
        }
	});
}

function setHarvestFlagForCreep(creep){

	if (creep.carry.energy === 0){
		 creep.memory.harvesting = true;
	}

	if (creep.carry.energy === creep.carryCapacity){
		 creep.memory.harvesting = false;
	}
}

module.exports = roleHarvester;<|endoftext|>


<commit_before>var roleHarvester = {

    run: function(creep, source) {

	    if(creep.carry.energy < creep.carryCapacity) {
            if(creep.harvest(source) == ERR_NOT_IN_RANGE) {
                creep.moveTo(source);
            }
        }
        else {
            var targets = creep.room.find(FIND_STRUCTURES, {
                    filter: (structure) => {
                        return (structure.structureType == STRUCTURE_EXTENSION ||
                                structure.structureType == STRUCTURE_SPAWN ||
                                structure.structureType == STRUCTURE_TOWER) && structure.energy < structure.energyCapacity;
                    }
            });
            if(targets.length > 0) {
                if(creep.transfer(targets[0], RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                    creep.moveTo(targets[0]);
                }
            }
        }
	}

}

module.exports = roleHarvester;<commit_msg>Imporved Harvesters<commit_after>var roleHarvester = {

    run: function(creep, source) {

    	harvestEnergy(creep)

    	console.log("Harvester "+creep.name+" is harvesting "+creep.memory.harvesting);

    	if (creep.memory.harvesting) {
    		if(creep.harvest(source) == ERR_NOT_IN_RANGE) {
            creep.moveTo(source);
            return;
        }

    	var targets = getTargetsForEnergyTransfer();

        if(targets.length > 0) {

            if(creep.transfer(targets[0], RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                creep.moveTo(targets[0]);
            }
        }
    	}
	}
}

function getTargetsForEnergyTransfer(){
	return creep.room.find(FIND_STRUCTURES, {
        filter: (structure) => {
            return (structure.structureType == STRUCTURE_EXTENSION ||
                    structure.structureType == STRUCTURE_SPAWN ||
                    structure.structureType == STRUCTURE_TOWER) && structure.energy < structure.energyCapacity;
        }
	});
}

function setHarvestFlagForCreep(creep){
	if (creep.carry.energy == 0){
		 creep.memory.harvesting = true;
		 return;
	}

	if (creep.carry.energy == creep.carryCapacity){
		 creep.memory.harvesting = false;
		 return;
	}
}

module.exports = roleHarvester;<|endoftext|>


<commit_before>(function (Q, $, window, undefined) {

var Streams = Q.Streams;
var Users = Q.Users;

/**
 * @module Streams-tools
 */

/**
 * Renders an interface to handle Streams/calls
 * @class Streams calls
 * @constructor
 * @param {Object} [options] any options for the tool
 * @param {Q.Event} [options.maxCalls=0] Max calls can be related to this category
 * @param {Q.Event} [options.publisherId=Users.currentCommunityId] Publisher of Streams/calls/main stream
 * @param {Q.Event} [options.streamName=Streams/calls/main] Category stream name
 */
Q.Tool.define("Streams/calls", function(options) {
	var tool = this;
	var state = this.state;

	var pipe = new Q.pipe(["style", "text", "stream"], function () {
		if (tool.stream.testWriteLevel("edit")) {
			tool.settings();
		} else {
			tool.call();
		}
	});

	Streams.get.force(state.publisherId, state.streamName, function (err) {
		var msg = Q.firstErrorMessage(err);
		if (msg) {
			return Q.alert(msg);
		}

		// join every user to allow get messages
		this.join();

		tool.stream = this;

		// check availability and also listen messages Streams/relation/[available, unavailable]
		var calls = Q.getObject(["relatedToTotals", state.relationType, "Streams/webrtc"], this) || 0;
		var maxCalls = tool.getMaxCalls();
		tool.available(calls < maxCalls);
		this.onMessage("Streams/relation/available").set(function (stream, message) {
			tool.available(true);
		}, tool);
		this.onMessage("Streams/relation/unavailable").set(function (stream, message) {
			tool.available(false);
		}, tool);

		pipe.fill("stream")();
	}, {
		withRelatedToTotals: [state.relationType]
	});

	Q.Text.get("Streams/content", function (err, content) {
		if (err) {
			return;
		}

		tool.text = content;
		pipe.fill("text")();
	});
	Q.addStylesheet('{{Streams}}/css/tools/calls.css', { slotName: 'Streams' }, pipe.fill("style"));
},

{
	maxCalls: 0,
	publisherId: Users.currentCommunityId,
	streamName: "Streams/calls/main",
	relationType: "Streams/calls"
},

{
	/**
	 * Set tool status to available/unavailable
	 * @method available
	 * @params {boolean} state
	 */
	available: function (state) {
		var $toolElement = $(this.element);

		// available/unavailable only for regular users
		if (this.stream.testWriteLevel("edit")) {
			return;
		}

		if (state) {
			$toolElement.removeClass("Q_disabled_2");
			$toolElement.addClass("Q_pulsate");
		} else {
			$toolElement.addClass("Q_disabled_2");
			$toolElement.removeClass("Q_pulsate");
		}
	},
	/**
	 * Get current max calls from stream attributes
	 * @method getMaxCalls
	 * @params {boolean} state
	 */
	getMaxCalls: function () {
		return Q.getObject(this.state.relationType, this.stream.getAttribute("maxRelations")) || 0;
	},
	/**
	 * Implement settings UI for admins
	 * @method settings
	 */
	settings: function () {
		var tool = this;
		var state = tool.state;
		var $toolElement = $(tool.element);

		$toolElement.addClass("Streams_calls_settings").on(Q.Pointer.fastclick, function () {
			Q.invoke({
				title: tool.text.calls.SettingsTitle,
				columnClass: "Streams_calls_settings",
				className: "Streams_calls_settings",
				template: {
					name: "Streams/calls/settings",
					fields: {
						text: tool.text.calls,
						maxCalls: tool.getMaxCalls()
					}
				},
				trigger: $toolElement[0],
				callback: function () {
					// if opened in columns - third argument is a column element,
					// if opened dialog - first argument is dialog element
					var parentElement = arguments[2] instanceof HTMLElement ? arguments[2] : arguments[0];
					$(".Streams_calls_related", parentElement).tool("Streams/related", {
						publisherId: state.publisherId,
						streamName: state.streamName,
						relationType: state.relationType,
						editable: false,
						closeable: true,
						sortable: false,
						realtime: true
					}).activate();

					$("button[name=update]", parentElement).on(Q.Pointer.fastclick, function () {
						var maxCalls = parseInt($("input[name=maxCalls]", parentElement).val());
						var maxRelations = tool.stream.getAttribute("maxRelations") || {};
						var oldMaxCalls = parseInt(Q.getObject(state.relationType, maxRelations));

						if (maxCalls !== oldMaxCalls) {
							maxRelations[state.relationType] = maxCalls;
							tool.stream.setAttribute("maxRelations", maxRelations).save();
						}

					});
				}
			});
		});
	},
	/**
	 * Implement call UI for regular users
	 * @method call
	 */
	call: function () {
		var tool = this;
		var state = tool.state;
		var $toolElement = $(tool.element);

		$toolElement.addClass("Streams_calls_call").on(Q.Pointer.fastclick, function () {
			Q.prompt(null, function (content) {
				if (!content) {
					return;
				}

				Streams.WebRTC.start({
					publisherId: state.publisherId,
					streamName: state.streamName,
					relationType: state.relationType,
					content: content,
					resumeClosed: false,
					useExisting: false,
					tool: tool
				});
			}, {
				title: tool.text.calls.CallReasonTitle,
				noClose: false
			});
		});
	}
});

Q.Template.set("Streams/calls/settings",
	'

' +
	'{{text.MaxCalls}}<input name="maxCalls" type="number" value="{{maxCalls}}">' +
	'<button class="Q_button" name="update">{{text.Update}}</button>'
);

})(Q, Q.$, window);<commit_msg>Updated Streams/calls tool. If admin leave webrtc call, remove this call from calls list.<commit_after>(function (Q, $, window, undefined) {

var Streams = Q.Streams;
var Users = Q.Users;

/**
 * @module Streams-tools
 */

/**
 * Renders an interface to handle Streams/calls
 * @class Streams calls
 * @constructor
 * @param {Object} [options] any options for the tool
 * @param {Q.Event} [options.maxCalls=0] Max calls can be related to this category
 * @param {Q.Event} [options.publisherId=Users.currentCommunityId] Publisher of Streams/calls/main stream
 * @param {Q.Event} [options.streamName=Streams/calls/main] Category stream name
 */
Q.Tool.define("Streams/calls", function(options) {
	var tool = this;
	var state = this.state;

	var pipe = new Q.pipe(["style", "text", "stream"], function () {
		if (tool.stream.testWriteLevel("edit")) {
			state.isAdmin = true;
			tool.settings();
		} else {
			tool.call();
		}
	});

	Streams.get.force(state.publisherId, state.streamName, function (err) {
		var msg = Q.firstErrorMessage(err);
		if (msg) {
			return Q.alert(msg);
		}

		// join every user to allow get messages
		this.join();

		tool.stream = this;

		// check availability and also listen messages Streams/relation/[available, unavailable]
		var calls = Q.getObject(["relatedToTotals", state.relationType, "Streams/webrtc"], this) || 0;
		var maxCalls = tool.getMaxCalls();
		tool.available(calls < maxCalls);
		this.onMessage("Streams/relation/available").set(function (stream, message) {
			tool.available(true);
		}, tool);
		this.onMessage("Streams/relation/unavailable").set(function (stream, message) {
			tool.available(false);
		}, tool);

		pipe.fill("stream")();
	}, {
		withRelatedToTotals: [state.relationType]
	});

	Q.Text.get("Streams/content", function (err, content) {
		if (err) {
			return;
		}

		tool.text = content;
		pipe.fill("text")();
	});
	Q.addStylesheet('{{Streams}}/css/tools/calls.css', { slotName: 'Streams' }, pipe.fill("style"));
},

{
	maxCalls: 0,
	publisherId: Users.currentCommunityId,
	streamName: "Streams/calls/main",
	relationType: "Streams/calls"
},

{
	/**
	 * Set tool status to available/unavailable
	 * @method available
	 * @params {boolean} state
	 */
	available: function (state) {
		var $toolElement = $(this.element);

		// available/unavailable only for regular users
		if (this.stream.testWriteLevel("edit")) {
			return;
		}

		if (state) {
			$toolElement.removeClass("Q_disabled_2");
			$toolElement.addClass("Q_pulsate");
		} else {
			$toolElement.addClass("Q_disabled_2");
			$toolElement.removeClass("Q_pulsate");
		}
	},
	/**
	 * Get current max calls from stream attributes
	 * @method getMaxCalls
	 * @params {boolean} state
	 */
	getMaxCalls: function () {
		return Q.getObject(this.state.relationType, this.stream.getAttribute("maxRelations")) || 0;
	},
	/**
	 * Implement settings UI for admins
	 * @method settings
	 */
	settings: function () {
		var tool = this;
		var state = tool.state;
		var $toolElement = $(tool.element);

		$toolElement.addClass("Streams_calls_settings").on(Q.Pointer.fastclick, function () {
			Q.invoke({
				title: tool.text.calls.SettingsTitle,
				columnClass: "Streams_calls_settings",
				className: "Streams_calls_settings",
				template: {
					name: "Streams/calls/settings",
					fields: {
						text: tool.text.calls,
						maxCalls: tool.getMaxCalls()
					}
				},
				trigger: $toolElement[0],
				callback: function () {
					// if opened in columns - third argument is a column element,
					// if opened dialog - first argument is dialog element
					var parentElement = arguments[2] instanceof HTMLElement ? arguments[2] : arguments[0];
					$(".Streams_calls_related", parentElement).tool("Streams/related", {
						publisherId: state.publisherId,
						streamName: state.streamName,
						relationType: state.relationType,
						editable: false,
						closeable: true,
						sortable: false,
						realtime: true
					}).activate();

					$("button[name=update]", parentElement).on(Q.Pointer.fastclick, function () {
						var maxCalls = parseInt($("input[name=maxCalls]", parentElement).val());
						var maxRelations = tool.stream.getAttribute("maxRelations") || {};
						var oldMaxCalls = parseInt(Q.getObject(state.relationType, maxRelations));

						if (maxCalls !== oldMaxCalls) {
							maxRelations[state.relationType] = maxCalls;
							tool.stream.setAttribute("maxRelations", maxRelations).save();
						}
					});

					parentElement.forEachTool("Streams/webrtc/preview", function () {
						this.state.onWebRTCRoomEnded.set(function () {
							if (!state.isAdmin) {
								return;
							}

							Q.Streams.unrelate(
								state.publisherId,
								state.streamName,
								state.relationType,
								this.stream.fields.publisherId,
								this.stream.fields.name
							);
						}, tool);
					}, tool);
				}
			});
		});
	},
	/**
	 * Implement call UI for regular users
	 * @method call
	 */
	call: function () {
		var tool = this;
		var state = tool.state;
		var $toolElement = $(tool.element);

		$toolElement.addClass("Streams_calls_call").on(Q.Pointer.fastclick, function () {
			Q.prompt(null, function (content) {
				if (!content) {
					return;
				}

				Streams.WebRTC.start({
					publisherId: state.publisherId,
					streamName: state.streamName,
					relationType: state.relationType,
					content: content,
					resumeClosed: false,
					useExisting: false,
					tool: tool
				});
			}, {
				title: tool.text.calls.CallReasonTitle,
				noClose: false
			});
		});
	}
});

Q.Template.set("Streams/calls/settings",
	'

' +
	'{{text.MaxCalls}}<input name="maxCalls" type="number" value="{{maxCalls}}">' +
	'<button class="Q_button" name="update">{{text.Update}}</button>'
);

})(Q, Q.$, window);<|endoftext|>


<commit_before>/*
 * Popup extension to L.Marker, adding openPopup & bindPopup methods.
 */

L.Marker.include({
	openPopup: function () {
		if (this._popup && this._map) {
			this._popup.setLatLng(this._latlng);
			this._map.openPopup(this._popup);
		}

		return this;
	},

	closePopup: function () {
		if (this._popup) {
			this._popup._close();
		}
		return this;
	},

	bindPopup: function (content, options) {
		var anchor = L.point(this.options.icon.options.popupAnchor) || new L.Point(0, 0);

		anchor = anchor.add(L.Popup.prototype.options.offset);

		if (options && options.offset) {
			anchor = anchor.add(options.offset);
		}

		options = L.Util.extend({offset: anchor}, options);

		if (!this._popup) {
			this
				.on('click', this.openPopup, this)
				.on('remove', this.closePopup, this)
				.on('move', this.movePopup, this);
		}

		this._popup = new L.Popup(options, this)
			.setContent(content);

		return this;
	},

	unbindPopup: function () {
		if (this._popup) {
			this._popup = null;
			this
				.off('click', this.openPopup)
				.off('remove', this.closePopup)
				.off('move', this.movePopup);
		}
		return this;
	},

	_movePopup: function (e) {
		this._popup.setLatLng(e.latlng);
	}
});
<commit_msg>Fix up event handler method typo after movePopup rename.<commit_after>/*
 * Popup extension to L.Marker, adding openPopup & bindPopup methods.
 */

L.Marker.include({
	openPopup: function () {
		if (this._popup && this._map) {
			this._popup.setLatLng(this._latlng);
			this._map.openPopup(this._popup);
		}

		return this;
	},

	closePopup: function () {
		if (this._popup) {
			this._popup._close();
		}
		return this;
	},

	bindPopup: function (content, options) {
		var anchor = L.point(this.options.icon.options.popupAnchor) || new L.Point(0, 0);

		anchor = anchor.add(L.Popup.prototype.options.offset);

		if (options && options.offset) {
			anchor = anchor.add(options.offset);
		}

		options = L.Util.extend({offset: anchor}, options);

		if (!this._popup) {
			this
				.on('click', this.openPopup, this)
				.on('remove', this.closePopup, this)
				.on('move', this._movePopup, this);
		}

		this._popup = new L.Popup(options, this)
			.setContent(content);

		return this;
	},

	unbindPopup: function () {
		if (this._popup) {
			this._popup = null;
			this
				.off('click', this.openPopup)
				.off('remove', this.closePopup)
				.off('move', this._movePopup);
		}
		return this;
	},

	_movePopup: function (e) {
		this._popup.setLatLng(e.latlng);
	}
});
<|endoftext|>


<commit_before>/**
 * Copyright 2016 The AMP HTML Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS-IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * Converts an array-like object to an array.
 * @param {?IArrayLike<T>|string} arrayLike
 * @return {!Array<T>}
 * @template T
 */
export function toArray(arrayLike) {
  return arrayLike ? Array.prototype.slice.call(arrayLike) : [];
}

/**
 * Determines if value is actually an Array.
 * @param {*} value
 * @return {boolean}
 */
export const {isArray} = Array;

/**
 * If the specified argument is an array, it's returned as is. If it's a
 * single item, the array containing this item is created and returned.
 * @param {!Array<T>|T} arrayOrSingleItem
 * @return {!Array<T>}
 * @template T
 */
export function arrayOrSingleItemToArray(arrayOrSingleItem) {
  return isArray(arrayOrSingleItem)
    ? /** @type {!Array<T>} */ (arrayOrSingleItem)
    : [arrayOrSingleItem];
}

/**
 * Compares if two arrays contains exactly same elements of same number
 * of same order. Note that it does NOT handle NaN case as expected.
 *
 * @param {!Array<T>} arr1
 * @param {!Array<T>} arr2
 * @return {boolean}
 * @template T
 */
export function areEqualOrdered(arr1, arr2) {
  if (arr1.length !== arr2.length) {
    return false;
  }
  for (let i = 0; i < arr1.length; i++) {
    if (arr1[i] !== arr2[i]) {
      return false;
    }
  }
  return true;
}

/**
 * Removes elements that shouldRemove returns true for from the array.
 *
 * @param {!Array<T>} array
 * @param {function(T, number, !Array<T>):boolean} shouldRemove
 * @return {!Array<T>}
 * @template T
 */
export function remove(array, shouldRemove) {
  const removed = [];
  let index = 0;
  for (let i = 0; i < array.length; i++) {
    const item = array[i];
    if (shouldRemove(item, i, array)) {
      removed.push(item);
    } else {
      if (index < i) {
        array[index] = item;
      }
      index++;
    }
  }
  if (index < array.length) {
    array.length = index;
  }
  return removed;
}

/**
 * Returns the index of the first element matching the predicate.
 * Like Array#findIndex.
 *
 * @param {!Array<T>} array
 * @param {function(T, number, !Array<T>):boolean} predicate
 * @return {number}
 * @template T
 */
export function findIndex(array, predicate) {
  for (let i = 0; i < array.length; i++) {
    if (predicate(array[i], i, array)) {
      return i;
    }
  }
  return -1;
}

/**
 * Converts the given iterator to an array.
 *
 * @param {!Iterator<T>} iterator
 * @return {Array<T>}
 * @template T
 */
export function fromIterator(iterator) {
  const array = [];
  for (let e = iterator.next(); !e.done; e = iterator.next()) {
    array.push(e.value);
  }
  return array;
}

/**
 * Adds item to array if it is not already present.
 *
 * @param {Array<T>} array
 * @param {T} item
 * @return {boolean}
 * @template T
 */
export function pushIfNotExist(array, item) {
  if (array.indexOf(item) < 0) {
    array.push(item);
    return true;
  }
  return false;
}

/**
 * Removes the first matching item in the array. Returns `true` if the array
 * has changed.
 *
 * @param {!Array<T>} array
 * @param {T} item
 * @return {boolean}
 * @template T
 */
export function removeItem(array, item) {
  const index = array.indexOf(item);
  if (index == -1) {
    return false;
  }
  array.splice(index, 1);
  return true;
}

/**
 * Returns the last item in an array.
 *
 * @param {Array<T>} array
 * @template T
 * @return {?T}
 */
export function lastItem(array) {
  return array[array.length - 1];
}
<commit_msg>Solve dumb CC type inference bug (#34355)<commit_after>/**
 * Copyright 2016 The AMP HTML Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS-IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * Converts an array-like object to an array.
 * @param {?IArrayLike<T>|string} arrayLike
 * @return {!Array<T>}
 * @template T
 */
export function toArray(arrayLike) {
  return arrayLike ? Array.prototype.slice.call(arrayLike) : [];
}

/**
 * Determines if value is actually an Array.
 * @param {*} value
 * @return {boolean}
 */
export const {isArray} = Array;

/**
 * If the specified argument is an array, it's returned as is. If it's a
 * single item, the array containing this item is created and returned.
 *
 * The double-template pattern here solves a bug where CC can be passed a value
 * with declared type {string|!Array<string>} and return a value with a type of
 * {!Array<string|Array<string>>}.
 *
 * @param {!Array<T>|S} arrayOrSingleItem
 * @return {!Array<T>|!Array<S>}
 * @template S
 * @template T
 */
export function arrayOrSingleItemToArray(arrayOrSingleItem) {
  return isArray(arrayOrSingleItem)
    ? /** @type {!Array<T>} */ (arrayOrSingleItem)
    : [/** @type {!S} */ (arrayOrSingleItem)];
}

/**
 * Compares if two arrays contains exactly same elements of same number
 * of same order. Note that it does NOT handle NaN case as expected.
 *
 * @param {!Array<T>} arr1
 * @param {!Array<T>} arr2
 * @return {boolean}
 * @template T
 */
export function areEqualOrdered(arr1, arr2) {
  if (arr1.length !== arr2.length) {
    return false;
  }
  for (let i = 0; i < arr1.length; i++) {
    if (arr1[i] !== arr2[i]) {
      return false;
    }
  }
  return true;
}

/**
 * Removes elements that shouldRemove returns true for from the array.
 *
 * @param {!Array<T>} array
 * @param {function(T, number, !Array<T>):boolean} shouldRemove
 * @return {!Array<T>}
 * @template T
 */
export function remove(array, shouldRemove) {
  const removed = [];
  let index = 0;
  for (let i = 0; i < array.length; i++) {
    const item = array[i];
    if (shouldRemove(item, i, array)) {
      removed.push(item);
    } else {
      if (index < i) {
        array[index] = item;
      }
      index++;
    }
  }
  if (index < array.length) {
    array.length = index;
  }
  return removed;
}

/**
 * Returns the index of the first element matching the predicate.
 * Like Array#findIndex.
 *
 * @param {!Array<T>} array
 * @param {function(T, number, !Array<T>):boolean} predicate
 * @return {number}
 * @template T
 */
export function findIndex(array, predicate) {
  for (let i = 0; i < array.length; i++) {
    if (predicate(array[i], i, array)) {
      return i;
    }
  }
  return -1;
}

/**
 * Converts the given iterator to an array.
 *
 * @param {!Iterator<T>} iterator
 * @return {Array<T>}
 * @template T
 */
export function fromIterator(iterator) {
  const array = [];
  for (let e = iterator.next(); !e.done; e = iterator.next()) {
    array.push(e.value);
  }
  return array;
}

/**
 * Adds item to array if it is not already present.
 *
 * @param {Array<T>} array
 * @param {T} item
 * @return {boolean}
 * @template T
 */
export function pushIfNotExist(array, item) {
  if (array.indexOf(item) < 0) {
    array.push(item);
    return true;
  }
  return false;
}

/**
 * Removes the first matching item in the array. Returns `true` if the array
 * has changed.
 *
 * @param {!Array<T>} array
 * @param {T} item
 * @return {boolean}
 * @template T
 */
export function removeItem(array, item) {
  const index = array.indexOf(item);
  if (index == -1) {
    return false;
  }
  array.splice(index, 1);
  return true;
}

/**
 * Returns the last item in an array.
 *
 * @param {Array<T>} array
 * @template T
 * @return {?T}
 */
export function lastItem(array) {
  return array[array.length - 1];
}
<|endoftext|>


<commit_before>// Mock Senso responses

// Firmware version to report in DEV_INFO
const VERSION_MAJOR = 2
const VERSION_MINOR = 0
const VERSION_FEATURE = 0
const VERSION_FIX = 0

// DATA_TYPES
const DATA_TYPE_GET_DEV_INFO = 0xD1
const DATA_TYPE_GET_VCC_INFO = 0xD2

module.exports = function (profile, data) {
  console.log(data)
  const body = data.slice(8)
  const type = body.readUInt16LE(2)
  switch (type) {
    case DATA_TYPE_GET_DEV_INFO:
      return devInfo(profile)

    case DATA_TYPE_GET_VCC_INFO:
      return vccInfo()

    default:
      return standardResponse(type)
  }
}

function devInfoItem (serial_number) {
  var devInfoItem = Buffer.alloc(32)

  // status code
  devInfoItem.writeUInt32LE(0, 0)

  // error code
  devInfoItem.writeUInt32LE(0, 4)

  // software version
  devInfoItem.writeInt8(VERSION_MAJOR, 11)
  devInfoItem.writeInt8(VERSION_MINOR, 10)
  devInfoItem.writeInt8(VERSION_FEATURE, 9)
  devInfoItem.writeInt8(VERSION_FIX, 8)

  // hardware version
  devInfoItem.writeUInt32LE(0, 12)

  // serial number
  devInfoItem.write(serial_number, 16, 16, 'ascii')

  return devInfoItem
}

function devInfo (profile) {
  var header = Buffer.alloc(8)

  var lenType = Buffer.alloc(4)
  lenType.writeUInt16LE(32 * 6, 0)
  lenType.writeUInt16LE(DATA_TYPE_GET_DEV_INFO | 0x8000, 2)

  return Buffer.concat([header,
    lenType,
    devInfoItem(profile.board_serial_numbers.controller),
    devInfoItem(profile.board_serial_numbers.led_boards.center),
    devInfoItem(profile.board_serial_numbers.led_boards.up),
    devInfoItem(profile.board_serial_numbers.led_boards.right),
    devInfoItem(profile.board_serial_numbers.led_boards.down),
    devInfoItem(profile.board_serial_numbers.led_boards.left)
  ])
}

function vccInfo () {
  var header = Buffer.alloc(8)

  var lenType = Buffer.alloc(4)
  lenType.writeUInt16LE(12 * 6, 0)
  lenType.writeUInt16LE(DATA_TYPE_GET_VCC_INFO | 0x8000, 2)

  var vccInfo = Buffer.alloc(12)
  // vcc_3_3
  vccInfo.writeUInt16LE(3300, 0)
  // vcc5
  vccInfo.writeUInt16LE(5000, 2)
  // vcc_12_mot
  vccInfo.writeUInt16LE(12000, 4)
  // vcc_12_led
  vccInfo.writeUInt16LE(12000, 6)
  // vcc_19_led
  vccInfo.writeUInt16LE(19000, 8)
  // temperature
  vccInfo.writeInt16LE(0, 10)

  return Buffer.concat([
    header,
    lenType,
    // controller
    vccInfo,
    // 5 LED boards
    vccInfo,
    vccInfo,
    vccInfo,
    vccInfo,
    vccInfo
  ])
}

function standardResponse (type) {
  var header = Buffer.alloc(8)

  var response = Buffer.alloc(2 + 2 + 4 + 4 + 4)
  // write type with bit 15 set to indicate a response
  response.writeUInt16LE(type | 0x8000, 2)

  return Buffer.concat([header, response])
}
<commit_msg>Use device serial number in controller board dev_info_item<commit_after>// Mock Senso responses

// Firmware version to report in DEV_INFO
const VERSION_MAJOR = 2
const VERSION_MINOR = 0
const VERSION_FEATURE = 0
const VERSION_FIX = 0

// DATA_TYPES
const DATA_TYPE_GET_DEV_INFO = 0xD1
const DATA_TYPE_GET_VCC_INFO = 0xD2

module.exports = function (profile, data) {
  console.log(data)
  const body = data.slice(8)
  const type = body.readUInt16LE(2)
  switch (type) {
    case DATA_TYPE_GET_DEV_INFO:
      return devInfo(profile)

    case DATA_TYPE_GET_VCC_INFO:
      return vccInfo()

    default:
      return standardResponse(type)
  }
}

function devInfoItem (serial_number) {
  var devInfoItem = Buffer.alloc(32)

  // status code
  devInfoItem.writeUInt32LE(0, 0)

  // error code
  devInfoItem.writeUInt32LE(0, 4)

  // software version
  devInfoItem.writeInt8(VERSION_MAJOR, 11)
  devInfoItem.writeInt8(VERSION_MINOR, 10)
  devInfoItem.writeInt8(VERSION_FEATURE, 9)
  devInfoItem.writeInt8(VERSION_FIX, 8)

  // hardware version
  devInfoItem.writeUInt32LE(0, 12)

  // serial number
  devInfoItem.write(serial_number, 16, 16, 'ascii')

  return devInfoItem
}

function devInfo (profile) {
  var header = Buffer.alloc(8)

  var lenType = Buffer.alloc(4)
  lenType.writeUInt16LE(32 * 6, 0)
  lenType.writeUInt16LE(DATA_TYPE_GET_DEV_INFO | 0x8000, 2)

  return Buffer.concat([header,
    lenType,
    // The controller dev_info_item holds the device serial number and not the controller serial number!
    devInfoItem(profile.serial_number),
    devInfoItem(profile.board_serial_numbers.led_boards.center),
    devInfoItem(profile.board_serial_numbers.led_boards.up),
    devInfoItem(profile.board_serial_numbers.led_boards.right),
    devInfoItem(profile.board_serial_numbers.led_boards.down),
    devInfoItem(profile.board_serial_numbers.led_boards.left)
  ])
}

function vccInfo () {
  var header = Buffer.alloc(8)

  var lenType = Buffer.alloc(4)
  lenType.writeUInt16LE(12 * 6, 0)
  lenType.writeUInt16LE(DATA_TYPE_GET_VCC_INFO | 0x8000, 2)

  var vccInfo = Buffer.alloc(12)
  // vcc_3_3
  vccInfo.writeUInt16LE(3300, 0)
  // vcc5
  vccInfo.writeUInt16LE(5000, 2)
  // vcc_12_mot
  vccInfo.writeUInt16LE(12000, 4)
  // vcc_12_led
  vccInfo.writeUInt16LE(12000, 6)
  // vcc_19_led
  vccInfo.writeUInt16LE(19000, 8)
  // temperature
  vccInfo.writeInt16LE(0, 10)

  return Buffer.concat([
    header,
    lenType,
    // controller
    vccInfo,
    // 5 LED boards
    vccInfo,
    vccInfo,
    vccInfo,
    vccInfo,
    vccInfo
  ])
}

function standardResponse (type) {
  var header = Buffer.alloc(8)

  var response = Buffer.alloc(2 + 2 + 4 + 4 + 4)
  // write type with bit 15 set to indicate a response
  response.writeUInt16LE(type | 0x8000, 2)

  return Buffer.concat([header, response])
}
<|endoftext|>