<commit_before>/*
 * minimap
 * https://github.com/dryas/impactjs-minimap
 *
 * v1.1.0
 *
 * A plugin for the ImpactJS engine to display minimaps and a radar for entities.
 *
 * Benjamin Kaiser
 * me@benjaminkaiser.biz
 * http://www.benjaminkaiser.biz
 *
 * This work is licensed under the MIT License (MIT). To view a copy of this license, visit https://github.com/dryas/impactjs-minimap/blob/master/LICENSE.
 *
 * It would be very nice when you inform me, with an short email, when you are using this plugin in a project. Thanks.
 */

ig.module(
	'plugins.minimap'
)
.requires(
	'impact.game'
)
.defines(function() {
	ig.Game.inject({

	// Cache for the map canvases:
	maps: [],

	/*
	 * drawMiniMap(name, posx, posy, entities = [])
	 *
	 * Draws a map on the screen.
	 *
	 * Parameters:
	 *      name           = Name of the map to display (same as
	 *                       used on generateMiniMap())
	 *      posx           = Position (X) where the map should be displayed
	 *      posy           = Position (Y) where the map should be displayed
	 *      entities       = Array of entities which position should be
	 *                       displayed on the map
	 *      showviewport   = [true/false] Show the current viewport on Map
	 *      viewportcolor  = Define color of screenclipping
	 */
	drawMiniMap: function(name, posx, posy, entities, showviewport, viewportcolor)
	{
		// Needed parameters:
		if (typeof name === 'undefined')
			throw "minimap plugin [drawMiniMap()]: no name parameter set";

		// Optional parameters "posx" and "posy". Set to ("posx", "posy") 0 by default:
		posx = typeof posx !== 'undefined' ? posx : 0;
		posy = typeof posy !== 'undefined' ? posy : 0;

		// Optional parameter "viewport" and "viewportcolor":
		viewport = typeof viewport !== 'undefined' ? viewport : false;
		viewportcolor = typeof viewportcolor !== 'undefined' ? viewportcolor : '#f0f';

		// Get scaling factor:
		var s = ig.system.scale;

		// Get canvas and 2d context:
		var ctx = ig.system.context;

		// Save current state of the canvas:
		ctx.save();

		// Draw minimap background:
		ctx.drawImage(this.maps[name], posx, posy);

		// Draw entities position on the minimap:
		if (typeof entities !== 'undefined')
		{
			for(var entityid = 0; entityid < entities.length; entityid++)
			{
				// Get entities by type:
				var entity = this.getEntitiesByType(entities[entityid]);

				for (i=0; i < entity.length; i++)
				{
					// Calculate x and y:
					x = posx + (this.maps[name + '_offsetX'] * s) + (((this.maps[name].width - ((this.maps[name + '_offsetX'] * 2) * s))) * (entity[i].pos.x / ig.game.collisionMap.pxWidth));
					y = posy + (this.maps[name + '_offsetY'] * s) + (((this.maps[name].height - ((this.maps[name + '_offsetY'] * 2) * s)))* (entity[i].pos.y / ig.game.collisionMap.pxHeight));

					// Draw entity as dot on the map or use an icon:
					if (typeof entity[i].miniMap['icon'] !== 'undefined')
					{
						typeof entity[i].miniMap['iconOffset']['x'] !== 'undefined' ? entity[i].miniMap['iconOffset']['x'] : 0;
						typeof entity[i].miniMap['iconOffset']['y'] !== 'undefined' ? entity[i].miniMap['iconOffset']['y'] : 0;

						var mapIcon = new ig.Image(entity[i].miniMap['icon']);

						// Draw Icon:
						mapIcon.draw(
							(x / s) + (this.maps[name].width / ig.game.collisionMap.width / 2) - (entity[i].miniMap['mapSize'] / 2) - (mapIcon.width / 2) + entity[i].miniMap['iconOffset']['x'],
							(y / s) + (this.maps[name].height / ig.game.collisionMap.height / 2) - (entity[i].miniMap['mapSize'] / 2) - (mapIcon.height / 2) + entity[i].miniMap['iconOffset']['y']
						);
					}
					else
					{
						typeof entity[i].miniMap['mapSize'] !== 'undefined' ? entity[i].miniMap['mapSize'] : 5;
						typeof entity[i].miniMap['mapColor'] !== 'undefined' ? entity[i].miniMap['mapColor'] : '#FFFFFF';

						ctx.fillStyle = entity[i].miniMap['mapColor'];

						// Draw square:
						ctx.fillRect(
							x + ((this.maps[name].width / ig.game.collisionMap.width) / 2) - (entity[i].miniMap['mapSize'] / 2),
							y + ((this.maps[name].height / ig.game.collisionMap.height) / 2) - (entity[i].miniMap['mapSize'] / 2),
							entity[i].miniMap['mapSize'],
							entity[i].miniMap['mapSize']
						);
					}
				}
			}
		}

		// Draw viewport:
		if (showviewport)
		{
			// Load background map data:
			var bglayers = ig.game.backgroundMaps;

			// Get the current layer:
			var map = bglayers[0];

			var viewportx = ((this.maps[name].width / s * (ig.system.width / ig.game.collisionMap.pxWidth)) * s) - (this.maps[name + '_offsetX'] * 2);
			var viewporty = ((this.maps[name].width / s * (ig.system.height / ig.game.collisionMap.pxWidth)) * s) - (this.maps[name + '_offsetY'] * 2);
			// Add 0.5 to the starting position (workaround to draw sharp shapes):
			var xa = ((this.maps[name + '_offsetX'] * s) + (this.maps[name].width - (this.maps[name + '_offsetX'] * s * 2)) * (map.scroll.x / ig.game.collisionMap.pxWidth)) + 0.5;
			var ya = ((this.maps[name + '_offsetY'] * s) + (this.maps[name].height - (this.maps[name + '_offsetY'] * s * 2)) * (map.scroll.y / ig.game.collisionMap.pxHeight)) + 0.5;

			ctx.lineWidth = 1;
			ctx.strokeStyle = viewportcolor;
			ctx.strokeRect(
				xa,
				ya,
				viewportx,
				viewporty
			);
		}

		// Restore former state of the canvas:
		ctx.restore();
	},

	/*
	 * generateMiniMap(name, width, height, layer = [0])
	 *
	 * Generates a map, needs to be called in the init function.
	 *
	 * Parameters:
	 *      name      = Name of the map to generate (need to be used at
	 *                  drawMiniMap())
	 *      width     = Width of the minimap
	 *      height    = Height of the minimap
	 *      layer     = Array of layer ids that should be displayed on
	 *                  the generated map
	 *
	 * ATTENTION: Do NOT call it in the draw function because this will have
	 *            a big impact on performance, if the map needs to be redrawn
	 *            on every frame!
	 */
	generateMiniMap: function(name, width, height, layer)
	{
		// Needed parameters:
		if (typeof name === 'undefined')
			throw "minimap plugin [generateMiniMap()]: no name parameter set";
		if (typeof width === 'undefined')
			throw "minimap plugin [generateMiniMap()]: no width parameter set";
		if (typeof height === 'undefined')
			throw "minimap plugin [generateMiniMap()]: no height parameter set";

		// Optional parameter "layer". Set to (Layer) 0 by default:
		layer = typeof layer !== 'undefined' ? layer : [0];

		// Get scaling factor:
		var s = ig.system.scale;

		// create the minimap canvas
		var maptemp = ig.$new('canvas');
		maptemp.width = width * s;
		maptemp.height = height * s;

		// Get the canvas 2d context for map creation:
		var ctx = maptemp.getContext('2d');

		// Set solid background color for map:
		if(ig.game.clearColor)
		{
			ctx.fillStyle = ig.game.clearColor;
			ctx.fillRect(0, 0, maptemp.width, maptemp.height);
		}

		// Load background map data:
		var bglayers = ig.game.backgroundMaps;

		// Cycle through all layers that should be included in the map:
		for(var layerid = 0; layerid < layer.length; layerid++)
		{
			// Get the current layer:
			var map = bglayers[layer[layerid]];

			// Set fixed tilesize factor:
			var fWidth = 4;
			var fHeight = 4;

			// Calculate size of the tileset:
			var w = map.tiles.width * s;
			var h = map.tiles.height * s;
			var ws = w / map.tilesize * fWidth;
			var hs = h / map.tilesize * fHeight;

			// Resize tileset of the current map:
			var ts = ig.$new('canvas');
			var tsctx = ts.getContext('2d');
			ts.width = ws;
			ts.height = hs;
			tsctx.drawImage(map.tiles.data, 0, 0, w, h, 0, 0, ws, hs);

			this.maps[name + '_offsetX'] = Math.floor((width - (map.width * Math.floor(width / map.width))) / 2);
			this.maps[name + '_offsetY'] = Math.floor((height - (map.height * Math.floor(height / map.height))) / 2);

			// draw the map
			var tile = 0;

			for(var x = 0; x < map.width; x++)
			{
				for(var y = 0; y < map.height; y++)
				{
					// Does a tile exists on this position?
					if((tile = map.data[y][x]))
					{
						ctx.drawImage(
							ts,
							Math.floor(((tile-1) * s) % (ws/fWidth)) * fWidth,
							(Math.floor((tile-1) * s / (ws/fHeight)) * fHeight) * s,
							fWidth * s,
							fHeight * s,
							((x * Math.floor(width / map.width)) + this.maps[name + '_offsetX']) * s,
							((y * Math.floor(height / map.height)) + this.maps[name + '_offsetY']) * s,
							Math.floor(width / map.width) * s,
							Math.floor(height / map.height) * s
						);
					}
				}
			}

			// Cache map:
			this.maps[name] = maptemp;
		}
	}
	})
});
<commit_msg>fix missing positioning of the viewport<commit_after>/*
 * minimap
 * https://github.com/dryas/impactjs-minimap
 *
 * v1.1.0
 *
 * A plugin for the ImpactJS engine to display minimaps and a radar for entities.
 *
 * Benjamin Kaiser
 * me@benjaminkaiser.biz
 * http://www.benjaminkaiser.biz
 *
 * This work is licensed under the MIT License (MIT). To view a copy of this license, visit https://github.com/dryas/impactjs-minimap/blob/master/LICENSE.
 *
 * It would be very nice when you inform me, with an short email, when you are using this plugin in a project. Thanks.
 */

ig.module(
	'plugins.minimap'
)
.requires(
	'impact.game'
)
.defines(function() {
	ig.Game.inject({

	// Cache for the map canvases:
	maps: [],

	/*
	 * drawMiniMap(name, posx, posy, entities = [])
	 *
	 * Draws a map on the screen.
	 *
	 * Parameters:
	 *      name           = Name of the map to display (same as
	 *                       used on generateMiniMap())
	 *      posx           = Position (X) where the map should be displayed
	 *      posy           = Position (Y) where the map should be displayed
	 *      entities       = Array of entities which position should be
	 *                       displayed on the map
	 *      showviewport   = [true/false] Show the current viewport on Map
	 *      viewportcolor  = Define color of screenclipping
	 */
	drawMiniMap: function(name, posx, posy, entities, showviewport, viewportcolor)
	{
		// Needed parameters:
		if (typeof name === 'undefined')
			throw "minimap plugin [drawMiniMap()]: no name parameter set";

		// Optional parameters "posx" and "posy". Set to ("posx", "posy") 0 by default:
		posx = typeof posx !== 'undefined' ? posx : 0;
		posy = typeof posy !== 'undefined' ? posy : 0;

		// Optional parameter "viewport" and "viewportcolor":
		viewport = typeof viewport !== 'undefined' ? viewport : false;
		viewportcolor = typeof viewportcolor !== 'undefined' ? viewportcolor : '#f0f';

		// Get scaling factor:
		var s = ig.system.scale;

		// Get canvas and 2d context:
		var ctx = ig.system.context;

		// Save current state of the canvas:
		ctx.save();

		// Draw minimap background:
		ctx.drawImage(this.maps[name], posx, posy);

		// Draw entities position on the minimap:
		if (typeof entities !== 'undefined')
		{
			for(var entityid = 0; entityid < entities.length; entityid++)
			{
				// Get entities by type:
				var entity = this.getEntitiesByType(entities[entityid]);

				for (i=0; i < entity.length; i++)
				{
					// Calculate x and y:
					x = posx + (this.maps[name + '_offsetX'] * s) + (((this.maps[name].width - ((this.maps[name + '_offsetX'] * 2) * s))) * (entity[i].pos.x / ig.game.collisionMap.pxWidth));
					y = posy + (this.maps[name + '_offsetY'] * s) + (((this.maps[name].height - ((this.maps[name + '_offsetY'] * 2) * s)))* (entity[i].pos.y / ig.game.collisionMap.pxHeight));

					// Draw entity as dot on the map or use an icon:
					if (typeof entity[i].miniMap['icon'] !== 'undefined')
					{
						typeof entity[i].miniMap['iconOffset']['x'] !== 'undefined' ? entity[i].miniMap['iconOffset']['x'] : 0;
						typeof entity[i].miniMap['iconOffset']['y'] !== 'undefined' ? entity[i].miniMap['iconOffset']['y'] : 0;

						var mapIcon = new ig.Image(entity[i].miniMap['icon']);

						// Draw Icon:
						mapIcon.draw(
							(x / s) + (this.maps[name].width / ig.game.collisionMap.width / 2) - (entity[i].miniMap['mapSize'] / 2) - (mapIcon.width / 2) + entity[i].miniMap['iconOffset']['x'],
							(y / s) + (this.maps[name].height / ig.game.collisionMap.height / 2) - (entity[i].miniMap['mapSize'] / 2) - (mapIcon.height / 2) + entity[i].miniMap['iconOffset']['y']
						);
					}
					else
					{
						typeof entity[i].miniMap['mapSize'] !== 'undefined' ? entity[i].miniMap['mapSize'] : 5;
						typeof entity[i].miniMap['mapColor'] !== 'undefined' ? entity[i].miniMap['mapColor'] : '#FFFFFF';

						ctx.fillStyle = entity[i].miniMap['mapColor'];

						// Draw square:
						ctx.fillRect(
							x + ((this.maps[name].width / ig.game.collisionMap.width) / 2) - (entity[i].miniMap['mapSize'] / 2),
							y + ((this.maps[name].height / ig.game.collisionMap.height) / 2) - (entity[i].miniMap['mapSize'] / 2),
							entity[i].miniMap['mapSize'],
							entity[i].miniMap['mapSize']
						);
					}
				}
			}
		}

		// Draw viewport:
		if (showviewport)
		{
			// Load background map data:
			var bglayers = ig.game.backgroundMaps;

			// Get the current layer:
			var map = bglayers[0];

			var viewportx = ((this.maps[name].width / s * (ig.system.width / ig.game.collisionMap.pxWidth)) * s) - (this.maps[name + '_offsetX'] * 2);
			var viewporty = ((this.maps[name].width / s * (ig.system.height / ig.game.collisionMap.pxWidth)) * s) - (this.maps[name + '_offsetY'] * 2);
			// Add 0.5 to the starting position (workaround to draw sharp shapes):
			var xa = ((this.maps[name + '_offsetX'] * s) + (this.maps[name].width - (this.maps[name + '_offsetX'] * s * 2)) * (map.scroll.x / ig.game.collisionMap.pxWidth)) + posx + + 0.5;
			var ya = ((this.maps[name + '_offsetY'] * s) + (this.maps[name].height - (this.maps[name + '_offsetY'] * s * 2)) * (map.scroll.y / ig.game.collisionMap.pxHeight)) + posy + 0.5;

			ctx.lineWidth = 1;
			ctx.strokeStyle = viewportcolor;
			ctx.strokeRect(
				xa,
				ya,
				viewportx,
				viewporty
			);
		}

		// Restore former state of the canvas:
		ctx.restore();
	},

	/*
	 * generateMiniMap(name, width, height, layer = [0])
	 *
	 * Generates a map, needs to be called in the init function.
	 *
	 * Parameters:
	 *      name      = Name of the map to generate (need to be used at
	 *                  drawMiniMap())
	 *      width     = Width of the minimap
	 *      height    = Height of the minimap
	 *      layer     = Array of layer ids that should be displayed on
	 *                  the generated map
	 *
	 * ATTENTION: Do NOT call it in the draw function because this will have
	 *            a big impact on performance, if the map needs to be redrawn
	 *            on every frame!
	 */
	generateMiniMap: function(name, width, height, layer)
	{
		// Needed parameters:
		if (typeof name === 'undefined')
			throw "minimap plugin [generateMiniMap()]: no name parameter set";
		if (typeof width === 'undefined')
			throw "minimap plugin [generateMiniMap()]: no width parameter set";
		if (typeof height === 'undefined')
			throw "minimap plugin [generateMiniMap()]: no height parameter set";

		// Optional parameter "layer". Set to (Layer) 0 by default:
		layer = typeof layer !== 'undefined' ? layer : [0];

		// Get scaling factor:
		var s = ig.system.scale;

		// create the minimap canvas
		var maptemp = ig.$new('canvas');
		maptemp.width = width * s;
		maptemp.height = height * s;

		// Get the canvas 2d context for map creation:
		var ctx = maptemp.getContext('2d');

		// Set solid background color for map:
		if(ig.game.clearColor)
		{
			ctx.fillStyle = ig.game.clearColor;
			ctx.fillRect(0, 0, maptemp.width, maptemp.height);
		}

		// Load background map data:
		var bglayers = ig.game.backgroundMaps;

		// Cycle through all layers that should be included in the map:
		for(var layerid = 0; layerid < layer.length; layerid++)
		{
			// Get the current layer:
			var map = bglayers[layer[layerid]];

			// Set fixed tilesize factor:
			var fWidth = 4;
			var fHeight = 4;

			// Calculate size of the tileset:
			var w = map.tiles.width * s;
			var h = map.tiles.height * s;
			var ws = w / map.tilesize * fWidth;
			var hs = h / map.tilesize * fHeight;

			// Resize tileset of the current map:
			var ts = ig.$new('canvas');
			var tsctx = ts.getContext('2d');
			ts.width = ws;
			ts.height = hs;
			tsctx.drawImage(map.tiles.data, 0, 0, w, h, 0, 0, ws, hs);

			this.maps[name + '_offsetX'] = Math.floor((width - (map.width * Math.floor(width / map.width))) / 2);
			this.maps[name + '_offsetY'] = Math.floor((height - (map.height * Math.floor(height / map.height))) / 2);

			// draw the map
			var tile = 0;

			for(var x = 0; x < map.width; x++)
			{
				for(var y = 0; y < map.height; y++)
				{
					// Does a tile exists on this position?
					if((tile = map.data[y][x]))
					{
						ctx.drawImage(
							ts,
							Math.floor(((tile-1) * s) % (ws/fWidth)) * fWidth,
							(Math.floor((tile-1) * s / (ws/fHeight)) * fHeight) * s,
							fWidth * s,
							fHeight * s,
							((x * Math.floor(width / map.width)) + this.maps[name + '_offsetX']) * s,
							((y * Math.floor(height / map.height)) + this.maps[name + '_offsetY']) * s,
							Math.floor(width / map.width) * s,
							Math.floor(height / map.height) * s
						);
					}
				}
			}

			// Cache map:
			this.maps[name] = maptemp;
		}
	}
	})
});
<|endoftext|>


<commit_before>var stylus = require("stylus")
  , path   = require("path")
  , less   = require("less")

module.exports = function(file, name, url, next) {
  var dirname = path.dirname(name)
    , parser = new less.Parser({ paths: [ dirname, __dirname + "/../../assets/less" ]
                               , filename: name
                               })

  try {
    parser.parse(file.toString(), function(err, tree) {
      if(err) {
        next(err)
      }
      if(process.env.NODE_ENV.toLowerCase() === "production") {
        next(null, tree.toCSS({ compress: true }))
      } else {
        next(null, tree.toCSS({ compress: false }))
      }
    })
  } catch(err) {
    next(err)
  }
}
<commit_msg>better less errors<commit_after>var stylus = require("stylus")
  , path   = require("path")
  , less   = require("less")

module.exports = function(file, name, url, next) {
  var dirname = path.dirname(name)
    , parser = new less.Parser({ paths: [ dirname, __dirname + "/../../assets/less" ]
                               , filename: name
                               })

  try {
    parser.parse(file.toString(), function(err, tree) {
      if(err) {
        next(err.message)
      }
      if(process.env.NODE_ENV.toLowerCase() === "production") {
        next(null, tree.toCSS({ compress: true }))
      } else {
        next(null, tree.toCSS({ compress: false }))
      }
    })
  } catch(err) {
    next(err.message)
  }
}
<|endoftext|>


<commit_before>
var getTime = require('../medtronic-clock');

function bgTargetsLookup (inputs) {
  return bound_target_range(lookup(inputs));
}

function lookup (inputs) {
    var bgtargets_data = inputs.targets;
    var temptargets_data = inputs.temptargets;
    var now = new Date();

    //bgtargets_data.targets.sort(function (a, b) { return a.offset > b.offset });

    var bgTargets = bgtargets_data.targets[bgtargets_data.targets.length - 1];

    for (var i = 0; i < bgtargets_data.targets.length - 1; i++) {
        if ((now >= getTime(bgtargets_data.targets[i].offset)) && (now < getTime(bgtargets_data.targets[i + 1].offset))) {
            bgTargets = bgtargets_data.targets[i];
            break;
        }
    }

    var tempTargets = bgTargets;

    // sort tempTargets by date so we can process most recent first
    if (typeof(temptargets_data) != 'undefined') {
        temptargets_data.sort(function (a, b) { return new Date(a.created_at) < new Date(b.created_at) });
    }
    //console.error(temptargets_data);
    //console.error(now);
    for (var i = 0; i < temptargets_data.length; i++) {
        start = new Date(temptargets_data[i].created_at);
        //console.error(start);
        expires = new Date(start.getTime() + temptargets_data[i].duration * 60 * 1000);
        //console.error(expires);
        if (now >= new Date(temptargets_data[i].created_at) && temptargets_data[i].duration == 0) {
            // cancel temp targets
            //console.error(temptargets_data[i]);
            tempTargets = bgTargets;
            break;
        } else if (now >= new Date(temptargets_data[i].created_at) && now < expires ) {
            //console.error(temptargets_data[i]);
            tempTargets.high = temptargets_data[i].targetTop;
            tempTargets.low = temptargets_data[i].targetBottom;
            break;
        }
    }
    bgTargets = tempTargets;
    //console.error(bgTargets);

    return bgTargets;
}

function bound_target_range (target) {
    // hard-code lower bounds for min_bg and max_bg in case pump is set too low, or units are wrong
    target.max_bg = Math.max(80, target.high);
    target.min_bg = Math.max(80, target.low);
    // hard-code upper bound for min_bg in case pump is set too high
    target.min_bg = Math.min(200, target.min_bg);
    target.max_bg = Math.min(200, target.max_bg);
    return target
}

bgTargetsLookup.bgTargetsLookup = bgTargetsLookup;
bgTargetsLookup.lookup = lookup;
bgTargetsLookup.bound_target_range = bound_target_range;
exports = module.exports = bgTargetsLookup;

<commit_msg>try using try/catch block instead of undefined check<commit_after>
var getTime = require('../medtronic-clock');

function bgTargetsLookup (inputs) {
  return bound_target_range(lookup(inputs));
}

function lookup (inputs) {
    var bgtargets_data = inputs.targets;
    var temptargets_data = inputs.temptargets;
    var now = new Date();

    //bgtargets_data.targets.sort(function (a, b) { return a.offset > b.offset });

    var bgTargets = bgtargets_data.targets[bgtargets_data.targets.length - 1];

    for (var i = 0; i < bgtargets_data.targets.length - 1; i++) {
        if ((now >= getTime(bgtargets_data.targets[i].offset)) && (now < getTime(bgtargets_data.targets[i + 1].offset))) {
            bgTargets = bgtargets_data.targets[i];
            break;
        }
    }

    var tempTargets = bgTargets;

    // sort tempTargets by date so we can process most recent first
    try {
        temptargets_data.sort(function (a, b) { return new Date(a.created_at) < new Date(b.created_at) });
    } catch (e) {
        console.error("Could not sort temptargets_data.  Optional feature temporary targets disabled.");
    }
    //console.error(temptargets_data);
    //console.error(now);
    for (var i = 0; i < temptargets_data.length; i++) {
        start = new Date(temptargets_data[i].created_at);
        //console.error(start);
        expires = new Date(start.getTime() + temptargets_data[i].duration * 60 * 1000);
        //console.error(expires);
        if (now >= new Date(temptargets_data[i].created_at) && temptargets_data[i].duration == 0) {
            // cancel temp targets
            //console.error(temptargets_data[i]);
            tempTargets = bgTargets;
            break;
        } else if (now >= new Date(temptargets_data[i].created_at) && now < expires ) {
            //console.error(temptargets_data[i]);
            tempTargets.high = temptargets_data[i].targetTop;
            tempTargets.low = temptargets_data[i].targetBottom;
            break;
        }
    }
    bgTargets = tempTargets;
    //console.error(bgTargets);

    return bgTargets;
}

function bound_target_range (target) {
    // hard-code lower bounds for min_bg and max_bg in case pump is set too low, or units are wrong
    target.max_bg = Math.max(80, target.high);
    target.min_bg = Math.max(80, target.low);
    // hard-code upper bound for min_bg in case pump is set too high
    target.min_bg = Math.min(200, target.min_bg);
    target.max_bg = Math.min(200, target.max_bg);
    return target
}

bgTargetsLookup.bgTargetsLookup = bgTargetsLookup;
bgTargetsLookup.lookup = lookup;
bgTargetsLookup.bound_target_range = bound_target_range;
exports = module.exports = bgTargetsLookup;

<|endoftext|>


<commit_before>// Copyright 2014, Renasar Technologies Inc.
/* jshint: node:true */

'use strict';

var di = require('di');

module.exports = eventsProtocolFactory;

di.annotate(eventsProtocolFactory, new di.Provide('Protocol.Events'));
di.annotate(eventsProtocolFactory,
    new di.Inject(
        'Services.Messenger',
        'Protocol.Exchanges.Events',
        'Assert'
    )
);

function eventsProtocolFactory (messenger, eventsExchange, assert) {
    function EventsProtocol () {
    }

    EventsProtocol.prototype.publishTftpSuccess = function (nodeId, data) {
        assert.ok(nodeId);
        assert.object(data);

        messenger.publish(
            eventsExchange.exchange,
            'tftp.success' + '.' + nodeId,
            data
        );
    };

    EventsProtocol.prototype.publishTftpFailure = function (nodeId, data) {
        assert.ok(nodeId);
        assert.object(data);

        messenger.publish(
            eventsExchange.exchange,
            'tftp.failure' + '.' + nodeId,
            data
        );
    };

    EventsProtocol.prototype.publishHttpResponse = function (nodeId, data) {
        assert.ok(nodeId);
        assert.object(data);

        messenger.publish(
            eventsExchange.exchange,
            'http.response' + '.' + nodeId,
            data
        );
    };

    return new EventsProtocol();
}
<commit_msg>Add DHCP lease binding to the protocol<commit_after>// Copyright 2014, Renasar Technologies Inc.
/* jshint: node:true */

'use strict';

var di = require('di');

module.exports = eventsProtocolFactory;

di.annotate(eventsProtocolFactory, new di.Provide('Protocol.Events'));
di.annotate(eventsProtocolFactory,
    new di.Inject(
        'Services.Messenger',
        'Protocol.Exchanges.Events',
        'Assert'
    )
);

function eventsProtocolFactory (messenger, eventsExchange, assert) {
    function EventsProtocol () {
    }

    EventsProtocol.prototype.publishTftpSuccess = function (nodeId, data) {
        assert.ok(nodeId);
        assert.object(data);

        messenger.publish(
            eventsExchange.exchange,
            'tftp.success' + '.' + nodeId,
            data
        );
    };

    EventsProtocol.prototype.publishTftpFailure = function (nodeId, data) {
        assert.ok(nodeId);
        assert.object(data);

        messenger.publish(
            eventsExchange.exchange,
            'tftp.failure' + '.' + nodeId,
            data
        );
    };

    EventsProtocol.prototype.publishHttpResponse = function (nodeId, data) {
        assert.ok(nodeId);
        assert.object(data);

        messenger.publish(
            eventsExchange.exchange,
            'http.response' + '.' + nodeId,
            data
        );
    };

    EventsProtocol.prototype.publishDhcpBoundLease = function(nodeId, data) {
        assert.ok(nodeId);
        assert.ok(data);

        messenger.publish(
            eventsExchange.exchange,
            'dhcp.bind.success' + '.' + nodeId,
            data
        );
    };

    return new EventsProtocol();
}
<|endoftext|>


<commit_before>var Utils = require('./utils')

module.exports = (function() {
  var QueryInterface = function(sequelize) {
    this.sequelize = sequelize
  }

  QueryInterface.prototype.__defineGetter__('QueryGenerator', function() {
    return this.sequelize.connectorManager.getQueryGenerator()
  })

  QueryInterface.prototype.createTable = function(tableName, attributes, options) {
    var self = this

    return query .call(this, this.QueryGenerator.createTableQuery(tableName, attributes, options))
  }

  QueryInterface.prototype.dropTable = function() {

  }

  QueryInterface.prototype.renameTable = function() {

  }

  QueryInterface.prototype.addColumn = function() {

  }

  QueryInterface.prototype.removeColumn = function() {

  }

  QueryInterface.prototype.changeColumn = function() {

  }

  QueryInterface.prototype.renameColumn = function() {

  }

  QueryInterface.prototype.addIndex = function() {

  }

  QueryInterface.prototype.removeIndex = function() {

  }

  QueryInterface.prototype.insert = function() {

  }

  QueryInterface.prototype.update = function() {

  }

  QueryInterface.prototype.destroy = function() {

  }

  // private

  var query = function() {
    var args = Utils._.map(arguments, function(arg, _) { return arg })

    // add this as the second argument
    if(arguments.length == 1) args.push(this)

    return this.sequelize.query.apply(this.sequelize, args)
  }

  return QueryInterface
})()
<commit_msg>removed getter for direct variable assignment<commit_after>var Utils = require('./utils')

module.exports = (function() {
  var QueryInterface = function(sequelize) {
    this.sequelize = sequelize
    this.QueryGenerator = this.sequelize.connectorManager.getQueryGenerator()
  }

  QueryInterface.prototype.createTable = function(tableName, attributes, options) {
    return query.call(this, this.QueryGenerator.createTableQuery(tableName, attributes, options))
  }

  QueryInterface.prototype.dropTable = function() {

  }

  QueryInterface.prototype.renameTable = function() {

  }

  QueryInterface.prototype.addColumn = function() {

  }

  QueryInterface.prototype.removeColumn = function() {

  }

  QueryInterface.prototype.changeColumn = function() {

  }

  QueryInterface.prototype.renameColumn = function() {

  }

  QueryInterface.prototype.addIndex = function() {

  }

  QueryInterface.prototype.removeIndex = function() {

  }

  QueryInterface.prototype.insert = function() {

  }

  QueryInterface.prototype.update = function() {

  }

  QueryInterface.prototype.destroy = function() {

  }

  // private

  var query = function() {
    var args = Utils._.map(arguments, function(arg, _) { return arg })

    // add this as the second argument
    if(arguments.length == 1) args.push(this)

    return this.sequelize.query.apply(this.sequelize, args)
  }

  return QueryInterface
})()
<|endoftext|>


<commit_before>// Load modules

var Stream = require('stream');
var Zlib = require('zlib');
var Negotiator = require('negotiator');
var Generic = require('./generic');
var Headers = require('./headers');
var Utils = require('../utils');

// Declare internals

var internals = {};

// Stream response (Generic -> Stream)

exports = module.exports = internals.Stream = function (stream) {

    Generic.call(this);
    this.variety = 'stream';
    this.varieties.stream = true;

    delete this._payload;

    this._passThrough = {};
    this._setStream(stream);
};

Utils.inherits(internals.Stream, Generic);

internals.Stream.prototype.bytes = function (bytes) {

    this._headers['Content-Length'] = bytes;
    return this;
};

internals.Stream.prototype._setStream = function (stream) {

    if (!stream) {
        this._stream = null;
        return;
    }

    // Check if stream is a node HTTP response

    if (stream.statusCode) {
        this._passThrough.code = stream.statusCode;
    }

    if (stream.headers) {
        this._passThrough.headers = stream.headers;
    }

    // Support pre node v0.10 streams API

    if (stream.pipe === Stream.prototype.pipe) {
        var oldStream = stream;
        oldStream.pause();
        stream = new Stream.Readable().wrap(oldStream);
        oldStream.once('end', function (chunk) {

            stream.emit('end', chunk);
        });
        oldStream.resume();

        console.log('in old pipe');
    }

    this._stream = stream;
};

internals.Stream.prototype._prepare = function (request, callback) {

    var self = this;

    this._wasPrepared = true;

    if (this._flags.location) {
        this._headers.Location = Headers.location(this._flags.location, request);
    }

    Headers.cache(this, request);
    Headers.cors(this, request);
    Headers.state(this, request, function (err) {

        if (err) {
            return callback(err);
        }

        Headers.auth(self, request, function (err) {

            return callback(err || self);
        });
    });
};

internals.Stream.prototype._transmit = function (request, callback) {

    var self = this;

    // Apply passthrough code and headers

    if (this._passThrough.headers &&
        (!request._route.proxy || request._route.proxy.settings.passThrough)) {

        if (this._passThrough.headers) {
            var localCookies = Utils.clone(this._headers['Set-Cookie']);
            var localHeaders = this._headers;
            this._headers = Utils.clone(this._passThrough.headers);
            Utils.merge(this._headers, localHeaders);

            if (localCookies) {
                var headerKeys = Object.keys(this._passThrough.headers);
                for (var i = 0, il = headerKeys.length; i < il; ++i) {

                    if (headerKeys[i].toLowerCase() === 'set-cookie') {
                        delete this._headers[headerKeys[i]];
                        this._headers['Set-Cookie'] = [].concat(this._passThrough.headers[headerKeys[i]]).concat(localCookies);
                        break;
                    }
                }
            }
        }
    }

    if (this._passThrough.code) {
        this._code = this._passThrough.code;
    }

    var encoder = null;
    if (!this._headers['content-encoding']) {
        var negotiator = new Negotiator(request.raw.req);
        var encoding = negotiator.preferredEncoding(['gzip', 'deflate', 'identity']);
        if (encoding === 'deflate' || encoding === 'gzip') {
            var keys = Object.keys(this._headers);
            for (var i = 0, il = keys.length; i < il; ++i) {
                var key = keys[i];
                if (/content\-length/i.test(key)) {                 // Can be lowercase when coming from proxy
                    delete self._headers[key];
                }
            }

            this._headers['Content-Encoding'] = encoding;
            this._headers.Vary = 'Accept-Encoding';
            encoder = (encoding === 'gzip' ? Zlib.createGzip() : Zlib.createDeflate());
        }
    }

    var headers = Object.keys(this._headers);
    for (var h = 0, hl = headers.length; h < hl; ++h) {
        var header = headers[h];
        request.raw.res.setHeader(header, self._headers[header]);
    }

    request.raw.res.writeHead(this._code);

    var hasEnded = false;
    var end = function (aborted) {

        if (!hasEnded) {
            hasEnded = true;

            if (aborted !== true) {                                 // Can be Error
                request.raw.res.end();
            }

            self._preview.end();
            self._preview.removeAllListeners();

            self._stream.removeAllListeners();
            if (self._stream.destroy) {
                self._stream.destroy();
            }

            callback();
        }
    };

    this._stream.once('error', end);

    request.raw.req.once('aborted', function () {

        request.raw.req.removeListener('close', end);
        end(true);
    });

    request.raw.req.once('close', end);
    request.raw.res.once('close', end);
    request.raw.res.once('finish', end);
    request.raw.res.once('error', end);
console.log('In stream');
    this._stream.pipe(this._preview);
    (encoder ? this._stream.pipe(encoder) : this._stream).pipe(request.raw.res);
};
<commit_msg>Testing stream end issue<commit_after>// Load modules

var Stream = require('stream');
var Zlib = require('zlib');
var Negotiator = require('negotiator');
var Generic = require('./generic');
var Headers = require('./headers');
var Utils = require('../utils');

// Declare internals

var internals = {};

// Stream response (Generic -> Stream)

exports = module.exports = internals.Stream = function (stream) {

    Generic.call(this);
    this.variety = 'stream';
    this.varieties.stream = true;

    delete this._payload;

    this._passThrough = {};
    this._setStream(stream);
};

Utils.inherits(internals.Stream, Generic);

internals.Stream.prototype.bytes = function (bytes) {

    this._headers['Content-Length'] = bytes;
    return this;
};

internals.Stream.prototype._setStream = function (stream) {

    if (!stream) {
        this._stream = null;
        return;
    }

    // Check if stream is a node HTTP response

    if (stream.statusCode) {
        this._passThrough.code = stream.statusCode;
    }

    if (stream.headers) {
        this._passThrough.headers = stream.headers;
    }

    // Support pre node v0.10 streams API

    if (stream.pipe === Stream.prototype.pipe) {
        var oldStream = stream;
        oldStream.pause();
        stream = new Stream.Readable().wrap(oldStream);
        oldStream.resume();
    }

    this._stream = stream;
};

internals.Stream.prototype._prepare = function (request, callback) {

    var self = this;

    this._wasPrepared = true;

    if (this._flags.location) {
        this._headers.Location = Headers.location(this._flags.location, request);
    }

    Headers.cache(this, request);
    Headers.cors(this, request);
    Headers.state(this, request, function (err) {

        if (err) {
            return callback(err);
        }

        Headers.auth(self, request, function (err) {

            return callback(err || self);
        });
    });
};

internals.Stream.prototype._transmit = function (request, callback) {

    var self = this;

    // Apply passthrough code and headers

    if (this._passThrough.headers &&
        (!request._route.proxy || request._route.proxy.settings.passThrough)) {

        if (this._passThrough.headers) {
            var localCookies = Utils.clone(this._headers['Set-Cookie']);
            var localHeaders = this._headers;
            this._headers = Utils.clone(this._passThrough.headers);
            Utils.merge(this._headers, localHeaders);

            if (localCookies) {
                var headerKeys = Object.keys(this._passThrough.headers);
                for (var i = 0, il = headerKeys.length; i < il; ++i) {

                    if (headerKeys[i].toLowerCase() === 'set-cookie') {
                        delete this._headers[headerKeys[i]];
                        this._headers['Set-Cookie'] = [].concat(this._passThrough.headers[headerKeys[i]]).concat(localCookies);
                        break;
                    }
                }
            }
        }
    }

    if (this._passThrough.code) {
        this._code = this._passThrough.code;
    }

    var encoder = null;
    if (!this._headers['content-encoding']) {
        var negotiator = new Negotiator(request.raw.req);
        var encoding = negotiator.preferredEncoding(['gzip', 'deflate', 'identity']);
        if (encoding === 'deflate' || encoding === 'gzip') {
            var keys = Object.keys(this._headers);
            for (var i = 0, il = keys.length; i < il; ++i) {
                var key = keys[i];
                if (/content\-length/i.test(key)) {                 // Can be lowercase when coming from proxy
                    delete self._headers[key];
                }
            }

            this._headers['Content-Encoding'] = encoding;
            this._headers.Vary = 'Accept-Encoding';
            encoder = (encoding === 'gzip' ? Zlib.createGzip() : Zlib.createDeflate());
        }
    }

    var headers = Object.keys(this._headers);
    for (var h = 0, hl = headers.length; h < hl; ++h) {
        var header = headers[h];
        request.raw.res.setHeader(header, self._headers[header]);
    }

    request.raw.res.writeHead(this._code);

    var hasEnded = false;
    var end = function (aborted) {

        if (!hasEnded) {
            hasEnded = true;

            if (aborted !== true) {                                 // Can be Error
                request.raw.res.end();
            }

            self._preview.end();
            self._preview.removeAllListeners();

            self._stream.removeAllListeners();
            if (self._stream.destroy) {
                self._stream.destroy();
            }

            callback();
        }
    };

    this._stream.once('error', end);

    request.raw.req.once('aborted', function () {

        request.raw.req.removeListener('close', end);
        end(true);
    });

    request.raw.req.once('close', end);
    request.raw.res.once('close', end);
    request.raw.res.once('finish', end);
    request.raw.res.once('error', end);

    this._stream.pipe(this._preview);
    this._stream.pipe(request.raw.res);
};
<|endoftext|>


<commit_before>'use strict';

var DiscoveryDocument = require('google-discovery-document');
var _ = require('lodash');
var methodMap = {
  create: 'POST',
  read: 'GET',
  update: 'PUT',
  delete: 'DELETE',
  list: 'GET'
};

function preamble (sails, pkg) {
  var prefix = sails.config.blueprints.prefix;

  return {
    kind: 'discovery#restDescription',
    etag: '',
    discoveryVersion: 'v' + pkg.version,
    version: 'v' + pkg.version,
    id: pkg.name + ':' +  pkg.version,
    name: pkg.name,
    revision: '0',
    title: pkg.name,
    description: pkg.description,
    icons: {
      x16: pkg.favicon
    },
    documentationLink: pkg.homepage,
    protocol: 'rest',
    rootUrl: sails.getBaseUrl(),
    baseUrl: sails.getBaseUrl() + prefix,
    basePath: prefix,
    batchPath: prefix,
    servicePath: prefix
  };
}

function parameters (sails, pkg) {
  return {
    oauth_token: {
      type: 'string',
      description: 'OAuth2 token',
      location: 'query'
    }
  };
}

function auth (sails, pkg) {
  return {
    oauth2: {
      scopes: { }
    }
  };
}

function schemas (sails, pkg) {
  return _.object(_.keys(sails.controllers), _.map(_.keys(sails.controllers), function (ctrl) {
    var model = sails.models[ctrl];

    return {
      id: ctrl,
      type: 'object',
      properties: model ? model.definition : undefined
    };
  }));
}

function resources (sails, pkg) {
  var prefix = sails.config.blueprints.prefix;

  return _.object(_.keys(sails.controllers), _.map(sails.controllers, function (controller, name) {
    return {
      methods: {
        create: resourceMethod('create', controller, prefix),
        read: resourceMethod('read', controller, prefix),
        update: resourceMethod('update', controller, prefix),
        delete: resourceMethod('delete', controller, prefix),
        list: resourceMethod('list', controller, prefix)
      }
    };
  }));
}

function resourceMethod (method, controller, prefix) {
  return {
    id: controller.identity + '.' + method,
    path: methodPath(method, prefix, controller),
    httpMethod: methodMap[method],
    description: methodDescription(method, controller),
    parameters: methodParameters(method, controller),
    scopes: [ ]
  };
}

function methodParameters (method, controller) {
  var idParam = {
    type: 'string',
    location: 'path'
  };
  return {
    create: { },
    read: { id: idParam },
    update: { id: idParam },
    delete: { id: idParam },
    list: { }
  }[method];
}

function methodDescription (method, controller) {
  return controller.identity + ' ' + method;
}

function methodPath (method, prefix, controller) {
  var suffix = {
    create: '', list: '', read: '/{id}', update: '/{id}', delete: '/{id}'
  };
  return prefix + '/' + controller.identity + suffix[method];
}

module.exports = function createRestDescription (sails, pkg) {
  return new DiscoveryDocument(_.extend(preamble(sails, pkg), {
    parameters: parameters(sails, pkg),
    auth: auth(sails, pkg),
    schemas: schemas(sails, pkg),
    resources: resources(sails, pkg)
  }));
};
<commit_msg>add description to schemas<commit_after>'use strict';

var DiscoveryDocument = require('google-discovery-document');
var _ = require('lodash');
var methodMap = {
  create: 'POST',
  read: 'GET',
  update: 'PUT',
  delete: 'DELETE',
  list: 'GET'
};

function preamble (sails, pkg) {
  var prefix = sails.config.blueprints.prefix;

  return {
    kind: 'discovery#restDescription',
    etag: '',
    discoveryVersion: 'v' + pkg.version,
    version: 'v' + pkg.version,
    id: pkg.name + ':' +  pkg.version,
    name: pkg.name,
    revision: '0',
    title: pkg.name,
    description: pkg.description,
    icons: {
      x16: pkg.favicon
    },
    documentationLink: pkg.homepage,
    protocol: 'rest',
    rootUrl: sails.getBaseUrl(),
    baseUrl: sails.getBaseUrl() + prefix,
    basePath: prefix,
    batchPath: prefix,
    servicePath: prefix
  };
}

function parameters (sails, pkg) {
  return {
    oauth_token: {
      type: 'string',
      description: 'OAuth2 token',
      location: 'query'
    }
  };
}

function auth (sails, pkg) {
  return {
    oauth2: {
      scopes: { }
    }
  };
}

function schemas (sails, pkg) {
  return _.object(_.keys(sails.controllers), _.map(_.keys(sails.controllers), function (ctrl) {
    var model = sails.models[ctrl];

    return {
      id: ctrl,
      type: 'object',
      description: model ? model.description : undefined,
      properties: model ? model.definition : undefined
    };
  }));
}

function resources (sails, pkg) {
  var prefix = sails.config.blueprints.prefix;

  return _.object(_.keys(sails.controllers), _.map(sails.controllers, function (controller, name) {
    return {
      methods: {
        create: resourceMethod('create', controller, prefix),
        read: resourceMethod('read', controller, prefix),
        update: resourceMethod('update', controller, prefix),
        delete: resourceMethod('delete', controller, prefix),
        list: resourceMethod('list', controller, prefix)
      }
    };
  }));
}

function resourceMethod (method, controller, prefix) {
  return {
    id: controller.identity + '.' + method,
    path: methodPath(method, prefix, controller),
    httpMethod: methodMap[method],
    description: methodDescription(method, controller),
    parameters: methodParameters(method, controller),
    scopes: [ ]
  };
}

function methodParameters (method, controller) {
  var idParam = {
    type: 'string',
    location: 'path'
  };
  return {
    create: { },
    read: { id: idParam },
    update: { id: idParam },
    delete: { id: idParam },
    list: { }
  }[method];
}

function methodDescription (method, controller) {
  return controller.identity + ' ' + method;
}

function methodPath (method, prefix, controller) {
  var suffix = {
    create: '', list: '', read: '/{id}', update: '/{id}', delete: '/{id}'
  };
  return prefix + '/' + controller.identity + suffix[method];
}

module.exports = function createRestDescription (sails, pkg) {
  return new DiscoveryDocument(_.extend(preamble(sails, pkg), {
    parameters: parameters(sails, pkg),
    auth: auth(sails, pkg),
    schemas: schemas(sails, pkg),
    resources: resources(sails, pkg)
  }));
};
<|endoftext|>


<commit_before>define(function(require) {
    var composition = require('durandal/composition'),
        system = require('durandal/system'),
        viewModel = require('durandal/viewModel');

    var modals = ko.observableArray([]);
    var modalActivator = viewModel.activator().forItems(modals);

    return {
        modals: modals,
        activator: modalActivator,
        currentZIndex: 1000,
        getNextZIndex: function() {
            return ++this.currentZIndex;
        },
        addHost: function(modalWindow) {
            var body = $('body');
            var blockout = $('

')
                .css({ 'z-index': this.getNextZIndex() })
                .appendTo(body);

            var host = $('

')
                .css({ 'z-index': this.getNextZIndex() })
                .appendTo(body);

            modalWindow.host = host.get(0);
            modalWindow.blockout = blockout.get(0);
        },
        removeHost: function(modalWindow) {
            $(modalWindow.host).remove();
            $(modalWindow.blockout).remove();
        },
        onComposed: function(parent, newChild, settings) {
            var $child = $(newChild);
            var width = $child.width();
            var height = $child.height();

            $child.css({
                'margin-top': (-height / 2).toString() + 'px',
                'margin-left': (-width / 2).toString() + 'px'
            });
        },
        createCompositionSettings: function(obj) {
            var settings = obj;
            var moduleId = system.getModuleId(obj);

            if (moduleId) {
                settings = {
                    model: obj
                };
            }

            settings.activate = false;
            settings.onComposed = this.onComposed;

            return settings;
        },
        show: function(obj) {
            var that = this;
            return system.defer(function(dfd) {
                modalActivator.activateItem(obj).then(function(success) {
                    if (success) {
                        var modalWindow = obj.window = {
                            open: function() {
                                that.addHost(modalWindow);
                                composition.compose(modalWindow.host, that.createCompositionSettings(obj));
                            },
                            close: function(result) {
                                modalActivator.deactivateItem(obj, true).then(function(closeSuccess) {
                                    if (closeSuccess) {
                                        that.removeHost(modalWindow);
                                        dfd.resolve(result);
                                    }
                                });
                            }
                        };

                        modalWindow.open();
                    } else {
                        dfd.resolve(false);
                    }
                });
            }).promise();
        }
    };
});<commit_msg>Removed the open func from internal modal.<commit_after>define(function(require) {
    var composition = require('durandal/composition'),
        system = require('durandal/system'),
        viewModel = require('durandal/viewModel');

    var modals = ko.observableArray([]);
    var modalActivator = viewModel.activator().forItems(modals);

    return {
        modals: modals,
        activator: modalActivator,
        currentZIndex: 1000,
        getNextZIndex: function() {
            return ++this.currentZIndex;
        },
        addHost: function(modalWindow) {
            var body = $('body');
            var blockout = $('

')
                .css({ 'z-index': this.getNextZIndex() })
                .appendTo(body);

            var host = $('

')
                .css({ 'z-index': this.getNextZIndex() })
                .appendTo(body);

            modalWindow.host = host.get(0);
            modalWindow.blockout = blockout.get(0);
        },
        removeHost: function(modalWindow) {
            $(modalWindow.host).remove();
            $(modalWindow.blockout).remove();
        },
        onComposed: function(parent, newChild, settings) {
            var $child = $(newChild);
            var width = $child.width();
            var height = $child.height();

            $child.css({
                'margin-top': (-height / 2).toString() + 'px',
                'margin-left': (-width / 2).toString() + 'px'
            });
        },
        createCompositionSettings: function(obj) {
            var settings = obj;
            var moduleId = system.getModuleId(obj);

            if (moduleId) {
                settings = {
                    model: obj
                };
            }

            settings.activate = false;
            settings.onComposed = this.onComposed;

            return settings;
        },
        show: function(obj) {
            var that = this;
            return system.defer(function(dfd) {
                modalActivator.activateItem(obj).then(function(success) {
                    if (success) {
                        var modalWindow = obj.window = {
                            close:function(result) {
                                modalActivator.deactivateItem(obj, true).then(function(closeSuccess) {
                                    if(closeSuccess) {
                                        that.removeHost(modalWindow);
                                        dfd.resolve(result);
                                    }
                                });
                            }
                        };

                        that.addHost(modalWindow);
                        composition.compose(modalWindow.host, that.createCompositionSettings(obj));
                    } else {
                        dfd.resolve(false);
                    }
                });
            }).promise();
        }
    };
});<|endoftext|>


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

var amqp = require('amqplib/callback_api');

amqp.connect('amqp://localhost', function(err, conn) {
  conn.createChannel(function(err, ch) {
    var q = 'hello';
    var buffer = new Buffer('Hello World!');

    ch.assertQueue(q, {durable: false});
    ch.sendToQueue(q, buffer);
    console.log(" [x] Sent %s", buffer.toString());
  });
  setTimeout(function() { conn.close(); process.exit(0) }, 500);
});
<commit_msg>Minor change<commit_after>#!/usr/bin/env node

var amqp = require('amqplib/callback_api');

amqp.connect('amqp://localhost', function(err, conn) {
  conn.createChannel(function(err, ch) {
    var q = 'hello';
    var msg = 'Hello World!';

    ch.assertQueue(q, {durable: false});
    ch.sendToQueue(q, new Buffer(msg));
    console.log(" [x] Sent %s", msg);
  });
  setTimeout(function() { conn.close(); process.exit(0) }, 500);
});
<|endoftext|>


<commit_before>(function($) {
	$.entwine('ss', function($){
		/**
		 * Reset the parent node selection if the type is
		 * set back to "toplevel page", to avoid submitting inconsistent state.
		 */
		$(".cms-add-form .parent-mode :input").entwine({
			onclick: function(e) {
				if(this.val() == 'top') {
					var parentField = this.closest('form').find('#Form_AddForm_ParentID_Holder .TreeDropdownField')
					parentField.setValue('');
					parentField.setTitle('');
				}
			}
		});

		$(".cms-add-form").entwine({
			ParentID: 0, // Last selected parentID
			ParentCache: {}, // Cache allowed children for each selected page
			onadd: function() {
				var self = this;
				this.find('#Form_AddForm_ParentID_Holder .TreeDropdownField').bind('change', function() {
					self.updateTypeList();
				});
				this.find(".SelectionGroup.parent-mode").bind('change',  function() {
					self.updateTypeList();
				});
				this.updateTypeList();
			},
			loadCachedChildren: function(parentID) {
				var cache = this.getParentCache();
				if(typeof cache[parentID] !== 'undefined') return cache[parentID];
				else return null;
			},
			saveCachedChildren: function(parentID, children) {
				var cache = this.getParentCache();
				cache[parentID] = children;
				this.setParentCache(cache);
			},
			/**
			 * Limit page type selection based on parent selection.
			 * Select of root classes is pre-computed, but selections with a given parent
			 * are updated on-demand.
			 * Similar implementation to LeftAndMain.Tree.js.
			 */
			updateTypeList: function() {
				var hints = this.data('hints'),
					parentTree = this.find('#Form_AddForm_ParentID_Holder .TreeDropdownField'),
					parentMode = this.find("input[name=ParentModeField]:checked").val(),
					metadata = parentTree.data('metadata'),
					id = (metadata && parentMode === 'child')
						? (parentTree.getValue() || this.getParentID())
						: null,
					newClassName = metadata ? metadata.ClassName : null,
					hintKey = (newClassName && parentMode === 'child')
						? newClassName
						: 'Root',
					hint = (typeof hints[hintKey] !== 'undefined') ? hints[hintKey] : null,
					self = this,
					defaultChildClass = (hint && typeof hint.defaultChild !== 'undefined')
						? hint.defaultChild
						: null,
					disallowedChildren = [];

				if(id) {
					// Prevent interface operations
					if(this.hasClass('loading')) return;
					this.addClass('loading');

					// Enable last parent ID to be re-selected from memory
					this.setParentID(id);
					if(!parentTree.getValue()) parentTree.setValue(id);

					// Use cached data if available
					disallowedChildren = this.loadCachedChildren(id);
					if(disallowedChildren !== null) {
						this.updateSelectionFilter(disallowedChildren, defaultChildClass);
						this.removeClass('loading');
						return;
					}
					$.ajax({
						url: self.data('childfilter'),
						data: {'ParentID': id},
						success: function(data) {
							// reload current form and tree
							self.saveCachedChildren(id, data);
							self.updateSelectionFilter(data, defaultChildClass);
						},
						complete: function() {
							self.removeClass('loading');
						}
					});

					return false;
				} else {
					disallowedChildren = (hint && typeof hint.disallowedChildren !== 'undefined')
						? hint.disallowedChildren
						: [],
					this.updateSelectionFilter(disallowedChildren, defaultChildClass);
				}
			},
			/**
			 * Update the selection filter with the given blacklist and default selection
			 *
			 * @param array disallowedChildren
			 * @param string defaultChildClass
			 */
			updateSelectionFilter: function(disallowedChildren, defaultChildClass) {
				// Limit selection
				var allAllowed = null; // troolian
				this.find('#Form_AddForm_PageType li').each(function() {
					var className = $(this).find('input').val(),
						isAllowed = ($.inArray(className, disallowedChildren) === -1);

					$(this).setEnabled(isAllowed);
					if(!isAllowed) $(this).setSelected(false);
					if(allAllowed === null) allAllowed = isAllowed;
					else allAllowed = allAllowed && isAllowed;
				});

				// Set default child selection, or fall back to first available option
				if(defaultChildClass) {
					var selectedEl = this
						.find('#Form_AddForm_PageType li input[value=' + defaultChildClass + ']')
						.parents('li:first');
				} else {
					var selectedEl = this.find('#Form_AddForm_PageType li:not(.disabled):first');
				}
				selectedEl.setSelected(true);
				selectedEl.siblings().setSelected(false);

				// Disable the "Create" button if none of the pagetypes are available
				var buttonState = this.find('#Form_AddForm_PageType li:not(.disabled)').length
					? 'enable'
					: 'disable';
				this.find('button[name=action_doAdd]').button(buttonState);

				this.find('.message-restricted')[allAllowed ? 'hide' : 'show']();
			}
		});

		$(".cms-add-form #Form_AddForm_PageType li").entwine({
			onclick: function(e) {
				this.setSelected(true);
			},
			setSelected: function(bool) {
				var input = this.find('input');
				if(bool && !input.is(':disabled')) {
					this.siblings().setSelected(false);
					this.toggleClass('selected', true);
					input.prop('checked', true);
				} else {
					this.toggleClass('selected', false);
					input.prop('checked', false);
				}
			},
			setEnabled: function(bool) {
				$(this).toggleClass('disabled', !bool);
				if(!bool) $(this).find('input').attr('disabled',  'disabled').removeAttr('checked');
				else $(this).find('input').removeAttr('disabled');
			}
		});

		$(".cms-page-add-button").entwine({
			onclick: function(e) {
				var tree = $('.cms-tree'), list = $('.cms-list'), parentId = 0;

				// Choose parent ID either from tree or list view, depending which is visible
				if(tree.is(':visible')) {
					var selected = tree.jstree('get_selected');
					parentId = selected ? $(selected[0]).data('id') : null;
				} else {
					var state = list.find('input[name="Page[GridState]"]').val();
					if(state) parentId = parseInt(JSON.parse(state).ParentID, 10);
				}

				var data = {selector: this.data('targetPanel'),pjax: this.data('pjax')}, url;
				if(parentId) {
					extraParams = this.data('extraParams') ? this.data('extraParams') : '';
					url = $.path.addSearchParams(ss.i18n.sprintf(this.data('urlAddpage'), parentId), extraParams);
				} else {
					url = this.attr('href');
				}

				$('.cms-container').loadPanel(url, null, data);
				e.preventDefault();

				// Remove focussed state from button
				this.blur();

				// $('.cms-page-add-form-dialog').dialog('open');
				// e.preventDefault();
			}
		});
	});
}(jQuery));
<commit_msg>BUG Fix incorrect "Add Page" button selector Fixes https://github.com/silverstripe/silverstripe-framework/issues/4540<commit_after>(function($) {
	$.entwine('ss', function($){
		/**
		 * Reset the parent node selection if the type is
		 * set back to "toplevel page", to avoid submitting inconsistent state.
		 */
		$(".cms-add-form .parent-mode :input").entwine({
			onclick: function(e) {
				if(this.val() == 'top') {
					var parentField = this.closest('form').find('#Form_AddForm_ParentID_Holder .TreeDropdownField')
					parentField.setValue('');
					parentField.setTitle('');
				}
			}
		});

		$(".cms-add-form").entwine({
			ParentID: 0, // Last selected parentID
			ParentCache: {}, // Cache allowed children for each selected page
			onadd: function() {
				var self = this;
				this.find('#Form_AddForm_ParentID_Holder .TreeDropdownField').bind('change', function() {
					self.updateTypeList();
				});
				this.find(".SelectionGroup.parent-mode").bind('change',  function() {
					self.updateTypeList();
				});
				this.updateTypeList();
			},
			loadCachedChildren: function(parentID) {
				var cache = this.getParentCache();
				if(typeof cache[parentID] !== 'undefined') return cache[parentID];
				else return null;
			},
			saveCachedChildren: function(parentID, children) {
				var cache = this.getParentCache();
				cache[parentID] = children;
				this.setParentCache(cache);
			},
			/**
			 * Limit page type selection based on parent selection.
			 * Select of root classes is pre-computed, but selections with a given parent
			 * are updated on-demand.
			 * Similar implementation to LeftAndMain.Tree.js.
			 */
			updateTypeList: function() {
				var hints = this.data('hints'),
					parentTree = this.find('#Form_AddForm_ParentID_Holder .TreeDropdownField'),
					parentMode = this.find("input[name=ParentModeField]:checked").val(),
					metadata = parentTree.data('metadata'),
					id = (metadata && parentMode === 'child')
						? (parentTree.getValue() || this.getParentID())
						: null,
					newClassName = metadata ? metadata.ClassName : null,
					hintKey = (newClassName && parentMode === 'child')
						? newClassName
						: 'Root',
					hint = (typeof hints[hintKey] !== 'undefined') ? hints[hintKey] : null,
					self = this,
					defaultChildClass = (hint && typeof hint.defaultChild !== 'undefined')
						? hint.defaultChild
						: null,
					disallowedChildren = [];

				if(id) {
					// Prevent interface operations
					if(this.hasClass('loading')) return;
					this.addClass('loading');

					// Enable last parent ID to be re-selected from memory
					this.setParentID(id);
					if(!parentTree.getValue()) parentTree.setValue(id);

					// Use cached data if available
					disallowedChildren = this.loadCachedChildren(id);
					if(disallowedChildren !== null) {
						this.updateSelectionFilter(disallowedChildren, defaultChildClass);
						this.removeClass('loading');
						return;
					}
					$.ajax({
						url: self.data('childfilter'),
						data: {'ParentID': id},
						success: function(data) {
							// reload current form and tree
							self.saveCachedChildren(id, data);
							self.updateSelectionFilter(data, defaultChildClass);
						},
						complete: function() {
							self.removeClass('loading');
						}
					});

					return false;
				} else {
					disallowedChildren = (hint && typeof hint.disallowedChildren !== 'undefined')
						? hint.disallowedChildren
						: [],
					this.updateSelectionFilter(disallowedChildren, defaultChildClass);
				}
			},
			/**
			 * Update the selection filter with the given blacklist and default selection
			 *
			 * @param array disallowedChildren
			 * @param string defaultChildClass
			 */
			updateSelectionFilter: function(disallowedChildren, defaultChildClass) {
				// Limit selection
				var allAllowed = null; // troolian
				this.find('#Form_AddForm_PageType li').each(function() {
					var className = $(this).find('input').val(),
						isAllowed = ($.inArray(className, disallowedChildren) === -1);

					$(this).setEnabled(isAllowed);
					if(!isAllowed) $(this).setSelected(false);
					if(allAllowed === null) allAllowed = isAllowed;
					else allAllowed = allAllowed && isAllowed;
				});

				// Set default child selection, or fall back to first available option
				if(defaultChildClass) {
					var selectedEl = this
						.find('#Form_AddForm_PageType li input[value=' + defaultChildClass + ']')
						.parents('li:first');
				} else {
					var selectedEl = this.find('#Form_AddForm_PageType li:not(.disabled):first');
				}
				selectedEl.setSelected(true);
				selectedEl.siblings().setSelected(false);

				// Disable the "Create" button if none of the pagetypes are available
				var buttonState = this.find('#Form_AddForm_PageType li:not(.disabled)').length
					? 'enable'
					: 'disable';
				this.find('button[name=action_doAdd]').button(buttonState);

				this.find('.message-restricted')[allAllowed ? 'hide' : 'show']();
			}
		});

		$(".cms-add-form #Form_AddForm_PageType li").entwine({
			onclick: function(e) {
				this.setSelected(true);
			},
			setSelected: function(bool) {
				var input = this.find('input');
				if(bool && !input.is(':disabled')) {
					this.siblings().setSelected(false);
					this.toggleClass('selected', true);
					input.prop('checked', true);
				} else {
					this.toggleClass('selected', false);
					input.prop('checked', false);
				}
			},
			setEnabled: function(bool) {
				$(this).toggleClass('disabled', !bool);
				if(!bool) $(this).find('input').attr('disabled',  'disabled').removeAttr('checked');
				else $(this).find('input').removeAttr('disabled');
			}
		});

		$(".cms-content-addpage-button").entwine({
			onclick: function(e) {
				var tree = $('.cms-tree'), list = $('.cms-list'), parentId = 0;

				// Choose parent ID either from tree or list view, depending which is visible
				if(tree.is(':visible')) {
					var selected = tree.jstree('get_selected');
					parentId = selected ? $(selected[0]).data('id') : null;
				} else {
					var state = list.find('input[name="Page[GridState]"]').val();
					if(state) parentId = parseInt(JSON.parse(state).ParentID, 10);
				}

				var data = {selector: this.data('targetPanel'),pjax: this.data('pjax')}, url;
				if(parentId) {
					extraParams = this.data('extraParams') ? this.data('extraParams') : '';
					url = $.path.addSearchParams(ss.i18n.sprintf(this.data('urlAddpage'), parentId), extraParams);
				} else {
					url = this.attr('href');
				}

				$('.cms-container').loadPanel(url, null, data);
				e.preventDefault();

				// Remove focussed state from button
				this.blur();

				// $('.cms-page-add-form-dialog').dialog('open');
				// e.preventDefault();
			}
		});
	});
}(jQuery));
<|endoftext|>


<commit_before>// Learning about numbers in Javascript
console.log("Result", 1 + 1);

// Integer number
var integerNumber = 20;
console.log('This is an integer number',integerNumber);
// Float number
var floatNumber = 20.1;
console.log('This is a float number',floatNumber);
// Double number
var doubleNumber = 20.1233;
console.log('This is a double number',doubleNumber);

//Arithmetic Operations with a integer,float and double numbers
// Addition +
console.log('Addition between integers:',25,'+',20, 'Result: ',25 + 20);
console.log('Addition between floats:',25.5,'+',20.4, 'Result: ',25.5 + 20.4);
console.log('Addition between doubles:',25.51,'+',20.41, 'Result: ',25.51 + 20.41);
console.log('Addition between integer and float:',25,'+',20.1, 'Result: ',25 + 20.1);
console.log('Addition between integer and double:',25,'+',20.123, 'Result: ',25 + 20.123);
console.log('Addition between float and double:',25.1,'+',20.123, 'Result: ',25.1 + 20.123);
// Subtraction -
console.log('Subtraction between integers:',25,'-',20, 'Result: ',25 - 20);
console.log('Subtraction between floats:',25.5,'-',20.4, 'Result: ',25.5 - 20.4);
console.log('Subtraction between doubles:',25.51,'-',20.41, 'Result: ',25.51 - 20.41);
console.log('Subtraction between integer and float:',25,'-',20.1, 'Result: ',25 - 20.1);
console.log('Subtraction between integer and double:',25,'-',20.123, 'Result: ',25 - 20.123);
console.log('Subtraction between float and double:',25.1,'-',20.123, 'Result: ',25.1 - 20.123);
//Multiply *
console.log('Multiply between integers:',5,'*',2, 'Result: ',5 * 2);
console.log('Multiply between floats:',5.5,'*',2.4, 'Result: ',5.5 * 2.4);
console.log('Multiply between doubles:',5.51,'*',2.41, 'Result: ',5.51 * 2.41);
console.log('Multiply between integer and float:',5,'*',2.1, 'Result: ',5 * 2.1);
console.log('Multiply between integer and double:',5,'*',2.123, 'Result: ',5 * 2.123);
console.log('Multiply between float and double:',5.1,'*',2.123, 'Result: ',5.1 * 2.123);
//Modulus /
console.log('Modulus between integers:',5,'/',2, 'Result: ',5 / 2);
console.log('Modulus between floats:',5.5,'/',2.4, 'Result: ',5.5 / 2.4);
console.log('Modulus between doubles:',5.51,'/',2.41, 'Result: ',5.51 / 2.41);
console.log('Modulus between integer and float:',5,'/',2.1, 'Result: ',5 / 2.1);
console.log('Modulus between integer and double:',5,'/',2.123, 'Result: ',5 / 2.123);
console.log('Modulus between float and double:',5.1,'/',2.123, 'Result: ',5.1 / 2.123);
//Remainder %
console.log('Remainder between integers:',5,'%',2, 'Result: ',5 % 2);
console.log('Remainder between floats:',5.5,'%',2.4, 'Result: ',5.5 % 2.4);
console.log('Remainder between doubles:',5.51,'%',2.41, 'Result: ',5.51 % 2.41);
console.log('Remainder between integer and float:',5,'%',2.1, 'Result: ',5 % 2.1);
console.log('Remainder between integer and double:',5,'%',2.123, 'Result: ',5 % 2.123);
console.log('Remainder between float and double:',5.1,'%',2.123, 'Result: ',5.1 % 2.123);<commit_msg>Converting strings to numbers<commit_after>// Learning about numbers in Javascript
console.log("Result", 1 + 1);

// Integer number
var integerNumber = 20;
console.log('This is an integer number',integerNumber);
// Float number
var floatNumber = 20.1;
console.log('This is a float number',floatNumber);
// Double number
var doubleNumber = 20.1233;
console.log('This is a double number',doubleNumber);

//Arithmetic Operations with a integer,float and double numbers
// Addition +
console.log('Addition between integers:',25,'+',20, 'Result: ',25 + 20);
console.log('Addition between floats:',25.5,'+',20.4, 'Result: ',25.5 + 20.4);
console.log('Addition between doubles:',25.51,'+',20.41, 'Result: ',25.51 + 20.41);
console.log('Addition between integer and float:',25,'+',20.1, 'Result: ',25 + 20.1);
console.log('Addition between integer and double:',25,'+',20.123, 'Result: ',25 + 20.123);
console.log('Addition between float and double:',25.1,'+',20.123, 'Result: ',25.1 + 20.123);
// Subtraction -
console.log('Subtraction between integers:',25,'-',20, 'Result: ',25 - 20);
console.log('Subtraction between floats:',25.5,'-',20.4, 'Result: ',25.5 - 20.4);
console.log('Subtraction between doubles:',25.51,'-',20.41, 'Result: ',25.51 - 20.41);
console.log('Subtraction between integer and float:',25,'-',20.1, 'Result: ',25 - 20.1);
console.log('Subtraction between integer and double:',25,'-',20.123, 'Result: ',25 - 20.123);
console.log('Subtraction between float and double:',25.1,'-',20.123, 'Result: ',25.1 - 20.123);
//Multiply *
console.log('Multiply between integers:',5,'*',2, 'Result: ',5 * 2);
console.log('Multiply between floats:',5.5,'*',2.4, 'Result: ',5.5 * 2.4);
console.log('Multiply between doubles:',5.51,'*',2.41, 'Result: ',5.51 * 2.41);
console.log('Multiply between integer and float:',5,'*',2.1, 'Result: ',5 * 2.1);
console.log('Multiply between integer and double:',5,'*',2.123, 'Result: ',5 * 2.123);
console.log('Multiply between float and double:',5.1,'*',2.123, 'Result: ',5.1 * 2.123);

//Modulus /
console.log('Modulus between integers:',5,'/',2, 'Result: ',5 / 2);
console.log('Modulus between floats:',5.5,'/',2.4, 'Result: ',5.5 / 2.4);
console.log('Modulus between doubles:',5.51,'/',2.41, 'Result: ',5.51 / 2.41);
console.log('Modulus between integer and float:',5,'/',2.1, 'Result: ',5 / 2.1);
console.log('Modulus between integer and double:',5,'/',2.123, 'Result: ',5 / 2.123);
console.log('Modulus between float and double:',5.1,'/',2.123, 'Result: ',5.1 / 2.123);
//Remainder %
console.log('Remainder between integers:',5,'%',2, 'Result: ',5 % 2);
console.log('Remainder between floats:',5.5,'%',2.4, 'Result: ',5.5 % 2.4);
console.log('Remainder between doubles:',5.51,'%',2.41, 'Result: ',5.51 % 2.41);
console.log('Remainder between integer and float:',5,'%',2.1, 'Result: ',5 % 2.1);
console.log('Remainder between integer and double:',5,'%',2.123, 'Result: ',5 % 2.123);
console.log('Remainder between float and double:',5.1,'%',2.123, 'Result: ',5.1 % 2.123);

//Built-in parseInt()
console.log("Using parseInt");
console.log("120 in base 10:", parseInt('120',10)); //decimal base
console.log("120 in base-8:",parseInt('120',8)); // base-8 (octal)
console.log("120 in base-16:",parseInt('120',16)); //hexadecimal base
console.log("120 in base-2:", parseInt('120',2)); //binary base<|endoftext|>


<commit_before>function getParams() {
  var raw_params = document.URL.replace(document.baseURI + '?', ''),
      params = {};

  $.each(raw_params.split(/&/g), function() {
    var slice = this.split(/=/);
    params[slice[0]] = slice[1];
  });

  return params;
}

$(function() {
  var params = getParams();

  $(".n-Nd").trigger('click');

  var reloader = function() {
    var div = $("div.n-Ob div[contenteditable]");
    if ( !div.length ) {
      setTimeout(reloader, 200);
    } else {
      div.text(params['status']);
    }
  };

  setTimeout(reloader, 200);
});
<commit_msg>Refactor in plus_extension.js<commit_after>(function($) {
  var params = (function() {
    var url_tokens = document.URL.replace(document.baseURI.concat('?'), '').split(/&/g),
        params = {};

    for(piece in url_tokens) {
      var slice = url_tokens[piece].split(/=/);
      params[slice[0]] = decodeURIComponent(slice[1]);
    }

    return params;
  })();

  $(function() {
    $(".n-Nd").trigger('click');

    var reloader = function() {
      var div = $("div.n-Ob div[contenteditable]");
      if ( !div.length ) {
        setTimeout(reloader, 200);
      } else {
        var text = params['title'].replace(/\+/g, ' ') + ': ' + params['href'];
        div.text(text);
      }
    };

    setTimeout(reloader, 200);
  });
})(jQuery);

<|endoftext|>


<commit_before>//how AuthorBot summarizes a session
//eventually moon prophecies will use this.
//a prophecy can be any of these values that don't match the values in the current session summary.
function SessionSummary(){
	this.session_id = null;
	this.num_scenes = null;
	this.players = null;  //can ask for sessions with a blood player and a murder mode, for example
	this.mvp = null;
	this.scratchAvailable = null;
	this.parentSession = null;
	this.yellowYard = null;
	this.numLiving = null;
	this.numDead = null;
	this.ectoBiologyStarted = null;
	this.denizenFought = null;
	this.plannedToExileJack = null;
	this.exiledJack = null;
	this.exiledQueen = null;
	this.jackGotWeapon = null;
	this.jackPromoted = null;
	this.jackRampage = null;
	this.jackScheme = null;
	this.kingTooPowerful = null;
	this.queenRejectRing = null;
	this.democracyStarted = null;
	this.murderMode = null;
	this.grimDark = null;
	this.frogLevel = null;
	this.hasDiamonds = null;
	this.hasSpades = null;
	this.hasClubs = null;
	this.hasHearts = null;
	//set when generatingHTML
	this.threeTimesSessionCombo = false;
	this.fourTimesSessionCombo = false;
	this.fiveTimesSessionCombo = false;
	this.holyShitMmmmmonsterCombo = false;
	this.frogStatus = null;

	//thanks to bob for helping me puzzle out the logic to make filters AND not OR.
	//why was that so hard???
	this.satifies_filter_array = function(filter_array){
		//console.log(filter_array)
		for(var i = 0; i< filter_array.length; i++){
			var filter = filter_array[i];

			if(filter == "numberNoFrog"){
				if(this.frogStatus  != "No Frog"){
				//	console.log("not no frog")
					return false;
				}
			}else if(filter == "numberSickFrog"){
				if(this.frogStatus  != "Sick Frog"){
					//console.log("not sick frog")
					return false;
				}
			}else if(filter == "numberFullFrog"){
				if(this.frogStatus  != "Full Frog"){
					//console.log("not full frog")
					return false;
				}
			}else if(filter == "timesAllDied"){
				if(this.numLiving != 0){
					//console.log("not all dead")
					return false;
				}
			}else if(filter == "timesAllLived"){
				if(this.numDead != 0){  //if this were an and on the outer if, it would let it fall down to the else if(!this[filter) and i don't want that.
					//console.log("not all alive")
					return false;
				}

			}else if(filter == "comboSessions"){
				if(!this.parentSession){  //if this were an and on the outer if, it would let it fall down to the else if(!this[filter) and i don't want that.
					//console.log("not combo session")
					return false;
				}

			}else if(!this[filter]){
				//console.log("property not true: " + filter)
				return false;
			}
		}
		//console.log("i pass all filters")
		return true;
	}

	this.decodeLineageGenerateHTML = function(){
			var html = "";
			var lineage = this.parentSession.getLineage(); //i am not a session so remember to tack myself on at the end.
			html += "
 Session: " +lineage[0].session_id + " "
			for(var i = 1; i< lineage.length; i++){
				html += " combined with: " + "" +lineage[i].session_id + " "
			}
			html += " combined with: " + "" +this.session_id + " "
			if((lineage.length +1) == 3){
				this.threeTimesSessionCombo = true;
				html += " 3x SESSIONS COMBO!!!"
			}
			if((lineage.length +1) == 4){
				this.fourTimesSessionCombo = true;
				html += " 4x SESSIONS COMBO!!!!"
			}
			if((lineage.length +1 ) ==5){
				this.fiveTimesSessionCombo = true;
				html += " 5x SESSIONS COMBO!!!!!"
			}
			if((lineage.length +1) > 5){
				this.holyShitMmmmmonsterCombo = true;
				html += " The session pile doesn't stop from getting taller. "
			}
			return html;

	}

	//generate own html, complete with div.  just return it, dn't add it to anything
	this.generateHTML = function(){
		var html = "
";
		for(var propertyName in this) {
				if(propertyName == "players"){
					html += "
" + propertyName + ": " + getPlayersTitlesBasic(this.players);
				}else if(propertyName == "mvp"){
					html += "
" + propertyName + ": " + this.mvp.htmlTitle() + " With a Power of: " + this.mvp.power;
				}else if(propertyName == "frogLevel"){
					html += "
" + propertyName + ": " + this.frogLevel + " (" + this.frogStatus +")";
				}else if(propertyName == "session_id"){
					if(this.parentSession){
						html += this.decodeLineageGenerateHTML();
					}else{
						html += "
 Session: " +this.session_id + ""
					}
				}else if(propertyName == "satifies_filter_array" || propertyName == "frogStatus" || propertyName == "decodeLineageGenerateHTML"|| propertyName == "threeTimesSessionCombo" || propertyName == "fourTimesSessionCombo"  || propertyName == "fiveTimesSessionCombo"  || propertyName == "holyShitMmmmmonsterCombo"  ){
					//do nothing. properties used elsewhere.
				}else if(propertyName != "generateHTML"){
					html += "
" + propertyName + ": " + this[propertyName] ;
				}
		}

		html += "

"
		return html;
	}

}

function MultiSessionSummary(){
	this.total = 0;
	this.scratchAvailable = 0;
	this.yellowYard = 0;
	this.timesAllLived = 0;
	this.timesAllDied = 0;
	this.ectoBiologyStarted = 0;
	this.denizenFought = 0;
	this.plannedToExileJack = 0;
	this.exiledJack = 0;
	this.exiledQueen = 0;
	this.jackGotWeapon = 0;
	this.jackPromoted = 0;
	this.jackRampage = 0;
	this.jackScheme = 0;
	this.kingTooPowerful = 0;
	this.queenRejectRing = 0;
	this.democracyStarted = 0;
	this.murderMode = 0;
	this.grimDark = 0;
	this.hasDiamonds = 0;
	this.hasSpades = 0;
	this.hasClubs = 0;
	this.hasHearts = 0;
	this.comboSessions = 0;
	this.threeTimesSessionCombo = 0;
	this.fourTimesSessionCombo= 0;
	this.fiveTimesSessionCombo = 0;
	this.holyShitMmmmmonsterCombo = 0;
	this.numberFullFrog = 0;
	this.numberSickFrog = 0;
	this.numberNoFrog = 0;

	this.generateHTML = function(){
		var html = "
";
		var header = "
Stats for All Displayed Sessions:
(When done finding, can filter)"
		html += header;
		//http://stackoverflow.com/questions/85992/how-do-i-enumerate-the-properties-of-a-javascript-object
		for(var propertyName in this) {
			if(propertyName == "total"){
				html += "
 ";
				html +=  propertyName + ": " + this[propertyName] ;
				html += " (" + Math.round(100* (this[propertyName]/this.total)) + "%)";
			}else if(propertyName != "generateHTML"){
				html += "
 <input disabled='true' type='checkbox' name='filter' value='"+propertyName +"' id='" + propertyName + "' onchange='filterSessionSummaries()'>";
				html +=  propertyName + ": " + this[propertyName] ;
				html += " (" + Math.round(100* (this[propertyName]/this.total)) + "%)";
			}
		}

		html += "

"
		return html;
	}

}

function summaryHasProperty(summary, property){
	return summary[propertyName]
}

function collateMultipleSessionSummaries(sessionSummaries){
	var mss = new MultiSessionSummary();
	for(var i = 0; i<sessionSummaries.length; i++){
		var ss = sessionSummaries[i];
		mss.total ++;
		if(ss.scratchAvailable) mss.scratchAvailable ++;
		if(ss.yellowYard) mss.yellowYard ++;
		if(ss.numLiving == 0) mss.timesAllDied ++;
		if(ss.numDead == 0) mss.timesAllLived ++;
		if(ss.ectoBiologyStarted) mss.ectoBiologyStarted ++;
		if(ss.denizenFought) mss.denizenFought ++;
		if(ss.plannedToExileJack) mss.plannedToExileJack ++;
		if(ss.exiledJack) mss.exiledJack ++;
		if(ss.exiledQueen) mss.exiledQueen ++;
		if(ss.jackGotWeapon) mss.jackGotWeapon ++;
		if(ss.jackPromoted) mss.jackPromoted ++;
		if(ss.jackRampage) mss.jackRampage ++;
		if(ss.jackScheme) mss.jackScheme ++;
		if(ss.kingTooPowerful) mss.kingTooPowerful ++;
		if(ss.queenRejectRing) mss.queenRejectRing ++;
		if(ss.democracyStarted) mss.democracyStarted ++;
		if(ss.murderMode) mss.murderMode ++;
		if(ss.grimDark) mss.grimDark ++;
		if(ss.hasDiamonds) mss.hasDiamonds ++;
		if(ss.hasSpades) mss.hasSpades ++;
		if(ss.hasClubs) mss.hasClubs ++;
		if(ss.hasHearts) mss.hasHearts ++;
		if(ss.parentSession) mss.comboSessions ++;
		if(ss.threeTimesSessionCombo) mss.threeTimesSessionCombo ++;
		if(ss.fourTimesSessionCombo) mss.fourTimesSessionCombo ++;
		if(ss.fiveTimesSessionCombo) mss.fiveTimesSessionCombo ++;
		if(ss.holyShitMmmmmonsterCombo) mss.holyShitMmmmmonsterCombo ++;
		if(ss.frogStatus == "No Frog") mss.numberNoFrog ++;
		if(ss.frogStatus == "Sick Frog") mss.numberSickFrog ++;
		if(ss.frogStatus == "Full Frog") mss.numberFullFrog ++;
	}
	return mss;
}
<commit_msg>added a surival rate to authorbot<commit_after>//how AuthorBot summarizes a session
//eventually moon prophecies will use this.
//a prophecy can be any of these values that don't match the values in the current session summary.
function SessionSummary(){
	this.session_id = null;
	this.num_scenes = null;
	this.players = null;  //can ask for sessions with a blood player and a murder mode, for example
	this.mvp = null;
	this.scratchAvailable = null;
	this.parentSession = null;
	this.yellowYard = null;
	this.numLiving = null;
	this.numDead = null;
	this.ectoBiologyStarted = null;
	this.denizenFought = null;
	this.plannedToExileJack = null;
	this.exiledJack = null;
	this.exiledQueen = null;
	this.jackGotWeapon = null;
	this.jackPromoted = null;
	this.jackRampage = null;
	this.jackScheme = null;
	this.kingTooPowerful = null;
	this.queenRejectRing = null;
	this.democracyStarted = null;
	this.murderMode = null;
	this.grimDark = null;
	this.frogLevel = null;
	this.hasDiamonds = null;
	this.hasSpades = null;
	this.hasClubs = null;
	this.hasHearts = null;
	//set when generatingHTML
	this.threeTimesSessionCombo = false;
	this.fourTimesSessionCombo = false;
	this.fiveTimesSessionCombo = false;
	this.holyShitMmmmmonsterCombo = false;
	this.frogStatus = null;

	//thanks to bob for helping me puzzle out the logic to make filters AND not OR.
	//why was that so hard???
	this.satifies_filter_array = function(filter_array){
		//console.log(filter_array)
		for(var i = 0; i< filter_array.length; i++){
			var filter = filter_array[i];

			if(filter == "numberNoFrog"){
				if(this.frogStatus  != "No Frog"){
				//	console.log("not no frog")
					return false;
				}
			}else if(filter == "numberSickFrog"){
				if(this.frogStatus  != "Sick Frog"){
					//console.log("not sick frog")
					return false;
				}
			}else if(filter == "numberFullFrog"){
				if(this.frogStatus  != "Full Frog"){
					//console.log("not full frog")
					return false;
				}
			}else if(filter == "timesAllDied"){
				if(this.numLiving != 0){
					//console.log("not all dead")
					return false;
				}
			}else if(filter == "timesAllLived"){
				if(this.numDead != 0){  //if this were an and on the outer if, it would let it fall down to the else if(!this[filter) and i don't want that.
					//console.log("not all alive")
					return false;
				}

			}else if(filter == "comboSessions"){
				if(!this.parentSession){  //if this were an and on the outer if, it would let it fall down to the else if(!this[filter) and i don't want that.
					//console.log("not combo session")
					return false;
				}

			}else if(!this[filter]){
				//console.log("property not true: " + filter)
				return false;
			}
		}
		//console.log("i pass all filters")
		return true;
	}

	this.decodeLineageGenerateHTML = function(){
			var html = "";
			var lineage = this.parentSession.getLineage(); //i am not a session so remember to tack myself on at the end.
			html += "
 Session: " +lineage[0].session_id + " "
			for(var i = 1; i< lineage.length; i++){
				html += " combined with: " + "" +lineage[i].session_id + " "
			}
			html += " combined with: " + "" +this.session_id + " "
			if((lineage.length +1) == 3){
				this.threeTimesSessionCombo = true;
				html += " 3x SESSIONS COMBO!!!"
			}
			if((lineage.length +1) == 4){
				this.fourTimesSessionCombo = true;
				html += " 4x SESSIONS COMBO!!!!"
			}
			if((lineage.length +1 ) ==5){
				this.fiveTimesSessionCombo = true;
				html += " 5x SESSIONS COMBO!!!!!"
			}
			if((lineage.length +1) > 5){
				this.holyShitMmmmmonsterCombo = true;
				html += " The session pile doesn't stop from getting taller. "
			}
			return html;

	}

	//generate own html, complete with div.  just return it, dn't add it to anything
	this.generateHTML = function(){
		var html = "
";
		for(var propertyName in this) {
				if(propertyName == "players"){
					html += "
" + propertyName + ": " + getPlayersTitlesBasic(this.players);
				}else if(propertyName == "mvp"){
					html += "
" + propertyName + ": " + this.mvp.htmlTitle() + " With a Power of: " + this.mvp.power;
				}else if(propertyName == "frogLevel"){
					html += "
" + propertyName + ": " + this.frogLevel + " (" + this.frogStatus +")";
				}else if(propertyName == "session_id"){
					if(this.parentSession){
						html += this.decodeLineageGenerateHTML();
					}else{
						html += "
 Session: " +this.session_id + ""
					}
				}else if(propertyName == "satifies_filter_array" || propertyName == "frogStatus" || propertyName == "decodeLineageGenerateHTML"|| propertyName == "threeTimesSessionCombo" || propertyName == "fourTimesSessionCombo"  || propertyName == "fiveTimesSessionCombo"  || propertyName == "holyShitMmmmmonsterCombo"  ){
					//do nothing. properties used elsewhere.
				}else if(propertyName != "generateHTML"){
					html += "
" + propertyName + ": " + this[propertyName] ;
				}
		}

		html += "

"
		return html;
	}

}

function MultiSessionSummary(){
	this.total = 0;
	this.totalDeadPlayers = 0;
	this.scratchAvailable = 0;
	this.yellowYard = 0;
	this.timesAllLived = 0;
	this.timesAllDied = 0;
	this.ectoBiologyStarted = 0;
	this.denizenFought = 0;
	this.plannedToExileJack = 0;
	this.exiledJack = 0;
	this.exiledQueen = 0;
	this.totalLivingPlayers = 0;
	this.survivalRate = 0;
	this.jackGotWeapon = 0;
	this.jackPromoted = 0;
	this.jackRampage = 0;
	this.jackScheme = 0;
	this.kingTooPowerful = 0;
	this.queenRejectRing = 0;
	this.democracyStarted = 0;
	this.murderMode = 0;
	this.grimDark = 0;
	this.hasDiamonds = 0;
	this.hasSpades = 0;
	this.hasClubs = 0;
	this.hasHearts = 0;
	this.comboSessions = 0;
	this.threeTimesSessionCombo = 0;
	this.fourTimesSessionCombo= 0;
	this.fiveTimesSessionCombo = 0;
	this.holyShitMmmmmonsterCombo = 0;
	this.numberFullFrog = 0;
	this.numberSickFrog = 0;
	this.numberNoFrog = 0;

	this.generateHTML = function(){
		var html = "
";
		var header = "
Stats for All Displayed Sessions:
(When done finding, can filter)"
		html += header;
		//http://stackoverflow.com/questions/85992/how-do-i-enumerate-the-properties-of-a-javascript-object
		for(var propertyName in this) {
			if(propertyName == "total"){
				html += "
 ";
				html +=  propertyName + ": " + this[propertyName] ;
				html += " (" + Math.round(100* (this[propertyName]/this.total)) + "%)";
			}else if(propertyName == "totalDeadPlayers"){
				html += "
totalDeadPlayers:  " + this.totalDeadPlayers + " ("+this.survivalRate + " % survival rate)";
			}else if(propertyName == "totalLivingPlayers" || propertyName == "survivalRate" ){
				//do nothing
			}else if(propertyName != "generateHTML"){
				html += "
 <input disabled='true' type='checkbox' name='filter' value='"+propertyName +"' id='" + propertyName + "' onchange='filterSessionSummaries()'>";
				html +=  propertyName + ": " + this[propertyName] ;
				html += " (" + Math.round(100* (this[propertyName]/this.total)) + "%)";
			}
		}

		html += "

"
		return html;
	}

}

function summaryHasProperty(summary, property){
	return summary[propertyName]
}

function collateMultipleSessionSummaries(sessionSummaries){
	var mss = new MultiSessionSummary();
	for(var i = 0; i<sessionSummaries.length; i++){
		var ss = sessionSummaries[i];
		mss.total ++;
		if(ss.scratchAvailable) mss.scratchAvailable ++;
		if(ss.yellowYard) mss.yellowYard ++;
		if(ss.numLiving == 0) mss.timesAllDied ++;
		if(ss.numDead == 0) mss.timesAllLived ++;
		if(ss.ectoBiologyStarted) mss.ectoBiologyStarted ++;
		if(ss.denizenFought) mss.denizenFought ++;
		if(ss.plannedToExileJack) mss.plannedToExileJack ++;
		if(ss.exiledJack) mss.exiledJack ++;
		if(ss.exiledQueen) mss.exiledQueen ++;
		if(ss.jackGotWeapon) mss.jackGotWeapon ++;
		if(ss.jackPromoted) mss.jackPromoted ++;
		if(ss.jackRampage) mss.jackRampage ++;
		if(ss.jackScheme) mss.jackScheme ++;
		if(ss.kingTooPowerful) mss.kingTooPowerful ++;
		if(ss.queenRejectRing) mss.queenRejectRing ++;
		if(ss.democracyStarted) mss.democracyStarted ++;
		if(ss.murderMode) mss.murderMode ++;
		if(ss.grimDark) mss.grimDark ++;
		if(ss.hasDiamonds) mss.hasDiamonds ++;
		if(ss.hasSpades) mss.hasSpades ++;
		if(ss.hasClubs) mss.hasClubs ++;
		if(ss.hasHearts) mss.hasHearts ++;
		if(ss.parentSession) mss.comboSessions ++;
		if(ss.threeTimesSessionCombo) mss.threeTimesSessionCombo ++;
		if(ss.fourTimesSessionCombo) mss.fourTimesSessionCombo ++;
		if(ss.fiveTimesSessionCombo) mss.fiveTimesSessionCombo ++;
		if(ss.holyShitMmmmmonsterCombo) mss.holyShitMmmmmonsterCombo ++;
		if(ss.frogStatus == "No Frog") mss.numberNoFrog ++;
		if(ss.frogStatus == "Sick Frog") mss.numberSickFrog ++;
		if(ss.frogStatus == "Full Frog") mss.numberFullFrog ++;
		mss.totalDeadPlayers += ss.numDead;
		mss.totalLivingPlayers += ss.numLiving;
	}
	mss.survivalRate = Math.round(100 * (mss.totalLivingPlayers/(mss.totalLivingPlayers + mss.totalDeadPlayers)));
	return mss;
}
<|endoftext|>


<commit_before>/*jshint strict:true, trailing:false, unused:true, node:true */
'use strict';

require("babel/register");

var EventEmitter = require('eventemitter3');
var emitter = new EventEmitter();

var rx = function(req, res) {
  var data = req.body;
  emitter.emit('pkg', data);
  res.end();
};

var tx = function(req, res) {
  res.writeHead(200, {
    'Content-Type':   'text/event-stream',
    'Cache-Control':  'no-cache',
    'Connection':     'keep-alive'
  });

  // Heartbeat
  var nln = () => res.write('\n');
  var hbt = setInterval(nln, 15000);

  var onPkg = (data) => {
    res.write("retry: 500\n");
    res.write(`event: pkg\n`);
    res.write(`data: ${JSON.stringify(data)}\n\n`);
  };

  emitter.on('pkg', onPkg);

  // Clear heartbeat and listener
  req.on('close', () => {
    clearInterval(hbt);
    emitter.removeListener('pkg', onPkg);
  });
};

module.exports = {
  rx: rx,
  tx: tx
};
<commit_msg>Add protection via API_KEY in parameter<commit_after>/*jshint strict:true, trailing:false, unused:true, node:true */
'use strict';

require("babel/register");

var EventEmitter = require('eventemitter3');
var emitter = new EventEmitter();

var rx = function(req, res) {
  if(req.query.api_key === process.env.API_KEY){
    var data = req.body;
    emitter.emit('pkg', data);
  }
  res.end();
};

var tx = function(req, res) {
  res.writeHead(200, {
    'Content-Type':   'text/event-stream',
    'Cache-Control':  'no-cache',
    'Connection':     'keep-alive'
  });

  // Heartbeat
  var nln = () => res.write('\n');
  var hbt = setInterval(nln, 15000);

  var onPkg = (data) => {
    res.write("retry: 500\n");
    res.write(`event: pkg\n`);
    res.write(`data: ${JSON.stringify(data)}\n\n`);
  };

  emitter.on('pkg', onPkg);

  // Clear heartbeat and listener
  req.on('close', () => {
    clearInterval(hbt);
    emitter.removeListener('pkg', onPkg);
  });
};

module.exports = {
  rx: rx,
  tx: tx
};
<|endoftext|>


<commit_before>// policies.js
// --------------------
//
// Run policies in order for a given controller/action pair
//

// Export runPolicy behavior
module.exports = runPolicy;

var _ = require('lodash');

// Determine route plan for incoming requests based on policy
//	-> controllerName
//	-> actionName
//	-> req
//	-> res
//	-> next - the actual controller action fn underneath this policy
function runPolicy(controllerName, actionName, req, res, next) {

	// TODO: move this to configuration.js so the server won't be allowed to start w/ invalid policies
	if (!sails.config.policies || !_.isObject(sails.config.policies) || _.isUndefined(sails.config.policies['*'])) {
		sails.log.error('Invalid policy configuration: Missing default * policy!');
		console.log(sails.config.policies);
		process.exit(1);
	}

	// The routing directions
	var routePlan = sails.config.policies;

	// Determine which policies apply directly to this request

	// policy for this controller

	var cPolicy = sails.config.policies[controllerName];

	// Get the controllerName and camelize it
	var camelController = require('inflection').camelize(controllerName) + 'Controller';

	// If a policy exists for the route don't bother looking for *Controller
	// if it doesn't then check for
	cPolicy = (!!cPolicy) ? cPolicy : sails.config.policies[camelController];

	if (!_.isUndefined(cPolicy)) {
		routePlan = cPolicy;

		// If policy is an object (but not an array), check if action exists
		if (!_.isArray(routePlan) && _.isObject(routePlan)) {

			// Check policy for this action within the controller policy map
			var aPolicy = routePlan[actionName];
			if (!_.isUndefined(aPolicy)) {
				routePlan = aPolicy;
			}
			// If no action OR * policy is defined, use top-level policy
			else if (_.isUndefined(routePlan['*'])) {
				routePlan = sails.config.policies;
			}
			// Otherwise, use the object itself (since a * is defined)
		}
	}

	// Build policy chain
	// (convert routePlan into executable chain)
	routePlan = buildPolicyChain(routePlan, req, res, next);

	// Initiate policy chain
	// (req,res, and appropriate next action
	//	are already bound at this point)
	routePlan();
}

// Build a chain of policies using 'policies' resulting in 'afterwards'
// returns a function which kicks the chain off
function buildPolicyChain(policies, req, res, afterwards) {

	// If policies are not a list, turn them into one
	if (!_.isArray(policies)) policies = [policies];

	// Keep track of middleware chain
	var chain = afterwards;

	// Iterate through policies and build function chain
	for (var i=policies.length-1; i >= 0; i--) {

		// Get actual policy function for this policy definition
		var policySet = interpretPolicy( policies[i] );

        // Handle arrays - convert to an array if the result of interpretPolicy is simple
        if (policySet && !_.isArray(policySet)) {
            policySet = [policySet];
        }
		// Set up chain to call next middleware after itself
        for (var j=policySet.length-1; j >= 0; j--) {
            chain = _.bind(policySet[j], {}, req, res, chain);
        }
	}

	return chain;
}

// Interpret a policy defintion as a chainable policy function
function interpretPolicy(policy) {

	// Disambiguate fully qualified policy objects (e.g. {'*': 'foo'} )
	if (!_.isArray(policy) && !_.isFunction(policy) && _.isObject(policy)) {
		policy = policy['*'];
	}

	// Publicly accessible: anyone can access
	if (policy === true) return function (req,res,next) {
		next();
	};

	// Globally disabled: no one can access
	else if (policy === false) return function (req,res,next) {
		return res.send("Sorry, this action has been globally disabled using a 'false' policy config.",403);
	};

	// Inline policy
	else if (_.isFunction(policy)) return policy;

	// Named policy: look up policy logic by name
	else if (_.isString(policy)) {

		// use it if it exists
		if (sails.policies[policy.toLowerCase()]) {
			return sails.policies[policy.toLowerCase()];
		}
		else return function (req,res,next) {
			return res.send('Sorry, the specified policy ('+policy+') does not exist.',500);
		};
	}
    else if (_.isArray(policy)) {
        var policies = _.map(
            policy,
            function(p){
                return interpretPolicy(p);
            });
        return policies;
    }

	// Unknown policy
	else {
		var message = "Invalid entry ("+policy+") in policy configuration!";
		sails.log.error(policy,"::",message);
		return function (req,res,next) {
			res.send(message, 500);
		};
	}
}<commit_msg>Removed old policies module.<commit_after><|endoftext|>