<commit_before>/**
 * Map constructor
 *
 * @class Roguelike.Map
 * @classdesc The object that holds all the rooms, corridors and tiles
 *
 * @param {Roguelike.Game} game - Reference to the current game object
 */
Roguelike.Map = function(game) {

	/**
	 * @property {Roguelike.Game} game - Reference to the current game object
	 */
	this.game = game;

	/**
	 * @property {Roguelike.Group} entities - Holds all the entities of this game
	 */
	this.entities = null;

	/**
	 * @property {Object} settings - The empty settings object
	 */
	this.settings = {};

	/**
	 * @property {Array} rooms - An array that holds all room objects
	 */
	this.rooms = [];

	/**
	 * @property {Array} tiles - An array that holds all tile objects
	 */
	this.tiles = [];

	/**
	 * @property {Array} objects - An array that holds all objects that are on the map
	 */
	this.objects = [];

	/**
	 * @property {Roguelike.Vector2} entrance - An object that holds the position of the entrance of this map
	 */
	this.entrance = null;

	/**
	 * @property {Roguelike.Vector2} exit - An object that holds the position of the exit of this map
	 */
	this.exit = null;

	this.allRooms = [];

	this.mediumRooms = [];

	/**
	 * @property {Array} objects - An array that holds all objects that are on the map
	 */
	this.roomsToExit = [];

	//Initialize itself
	this.initialize();

};

Roguelike.Map.prototype = {

	/**
	 * Initialize the layout of the map, filling it with empty tiles
	 * @protected
	 */
	initialize: function() {

		//TODO: Make this dynamic on the depth of the dungeon, this will allow the generator to make more complicated maps the deeper you go
		//Define settings
		this.settings = {
			tilesX: 60, //The number of horizontal tiles on this map
			tilesY: 40, //The number of vertical tiles on this map
			tileSize: 16, //The width and height of a single tile
			maxRooms: 15, //The maximum number of rooms on this map
			minRoomWidth: 5, //The minimum width of a single room
			maxRoomWidth: 8, //The maximum width of a single room
			minRoomHeight: 5, //The minimum height of a single room
			maxRoomHeight: 8, //The maximum height of a single room
			roomSpacing: 1, //The length of a corridor, 0 for no corridors
			maxMainRooms: 15,
			maxMediumRooms: 5
		};

		//Loop through every horizontal row
		for(var x = 0; x < this.settings.tilesX; x++) {

			//Initialize this row
			this.tiles[x] = [];

			//Loop through every vertical row
			for(var y = 0; y < this.settings.tilesY; y++) {

				//Initialize this position by setting it to zero, and blocking light
				this.tiles[x][y] = new Roguelike.Tile(0, true, 0, 0);

			}

		}

	},

	/**
	 * Function that returns an array with only the tiletypes of every position
	 * Used for EasyStar Pathfinding
	 * @protected
	 *
	 * @return {Array} Array with only the tiletypes of every position on the map
	 */
	typeList: function() {

		//Define variables
		var mapTypeList = [];

		//Loop through every horizontal row
		for(var y = 0; y < this.settings.tilesY; y++) {

			//Initialize this row
			mapTypeList.push([]);

			//Loop through every vertical row
			for(var x = 0; x < this.settings.tilesX; x++) {

				//Initialize this position by setting it to zero, and blocking light
				mapTypeList[y][x] = (this.tiles[x][y].type);

			}

		}

		//Return the array with Y X coordinates of every tiletype
		return mapTypeList;

	},

	//TODO: Update documentation on this function
	/**
	 * Check if a single room overlaps a room that is already on the map and if it's inside the maps boundaries
	 * @protected
	 *
	 * @param {Roguelike.Room} room - The room object that has to be checked
	 *
	 * @return {Boolean} True when the room intersects with an existing room, false when it's not intersecting
	 */
	roomFits: function(room) {

		if(room.x1 < 1 || room.x2 > this.settings.tilesX - 1 || room.y1 < 1 || room.y2 > this.settings.tilesY - 1) {

			return false;

		}

		//Loop through every room in the list
		for(var i = 0; i < this.allRooms.length; i++) {

			//Check if the room intersects with the current room
			if(room.x1 <= this.allRooms[i].x2 && room.x2 >= this.allRooms[i].x1 && room.y1 <= this.allRooms[i].y2 && room.y2 >= this.allRooms[i].y1) {

				return false;

			}

		}
		//If the room doesn't intersect another room, return true
		return true;

	}

};
<commit_msg>Fixed "//TODO: Update documentation on this function".<commit_after>/**
 * Map constructor
 *
 * @class Roguelike.Map
 * @classdesc The object that holds all the rooms, corridors and tiles
 *
 * @param {Roguelike.Game} game - Reference to the current game object
 */
Roguelike.Map = function(game) {

	/**
	 * @property {Roguelike.Game} game - Reference to the current game object
	 */
	this.game = game;

	/**
	 * @property {Roguelike.Group} entities - Holds all the entities of this game
	 */
	this.entities = null;

	/**
	 * @property {Object} settings - The empty settings object
	 */
	this.settings = {};

	/**
	 * @property {Array} rooms - An array that holds all room objects
	 */
	this.rooms = [];

	/**
	 * @property {Array} tiles - An array that holds all tile objects
	 */
	this.tiles = [];

	/**
	 * @property {Array} objects - An array that holds all objects that are on the map
	 */
	this.objects = [];

	/**
	 * @property {Roguelike.Vector2} entrance - An object that holds the position of the entrance of this map
	 */
	this.entrance = null;

	/**
	 * @property {Roguelike.Vector2} exit - An object that holds the position of the exit of this map
	 */
	this.exit = null;

	this.allRooms = [];

	this.mediumRooms = [];

	/**
	 * @property {Array} objects - An array that holds all objects that are on the map
	 */
	this.roomsToExit = [];

	//Initialize itself
	this.initialize();

};

Roguelike.Map.prototype = {

	/**
	 * Initialize the layout of the map, filling it with empty tiles
	 * @protected
	 */
	initialize: function() {

		//TODO: Make this dynamic on the depth of the dungeon, this will allow the generator to make more complicated maps the deeper you go
		//Define settings
		this.settings = {
			tilesX: 60, //The number of horizontal tiles on this map
			tilesY: 40, //The number of vertical tiles on this map
			tileSize: 16, //The width and height of a single tile
			maxRooms: 15, //The maximum number of rooms on this map
			minRoomWidth: 5, //The minimum width of a single room
			maxRoomWidth: 8, //The maximum width of a single room
			minRoomHeight: 5, //The minimum height of a single room
			maxRoomHeight: 8, //The maximum height of a single room
			roomSpacing: 1, //The length of a corridor, 0 for no corridors
			maxMainRooms: 15,
			maxMediumRooms: 5
		};

		//Loop through every horizontal row
		for(var x = 0; x < this.settings.tilesX; x++) {

			//Initialize this row
			this.tiles[x] = [];

			//Loop through every vertical row
			for(var y = 0; y < this.settings.tilesY; y++) {

				//Initialize this position by setting it to zero, and blocking light
				this.tiles[x][y] = new Roguelike.Tile(0, true, 0, 0);

			}

		}

	},

	/**
	 * Function that returns an array with only the tiletypes of every position
	 * Used for EasyStar Pathfinding
	 * @protected
	 *
	 * @return {Array} Array with only the tiletypes of every position on the map
	 */
	typeList: function() {

		//Define variables
		var mapTypeList = [];

		//Loop through every horizontal row
		for(var y = 0; y < this.settings.tilesY; y++) {

			//Initialize this row
			mapTypeList.push([]);

			//Loop through every vertical row
			for(var x = 0; x < this.settings.tilesX; x++) {

				//Initialize this position by setting it to zero, and blocking light
				mapTypeList[y][x] = (this.tiles[x][y].type);

			}

		}

		//Return the array with Y X coordinates of every tiletype
		return mapTypeList;

	},

	/**
	 * Check if a single room overlaps a room that is already on the map and if it's inside the maps boundaries
	 * @protected
	 *
	 * @param {Roguelike.Room} room - The room object that has to be checked
	 *
	 * @return {Boolean} True when the room intersects with an existing room, false when it's not intersecting
	 */
	roomFits: function(room) {

		//Check if the room fits inside the boundaries of this map. If not we can't place it.
		if(room.x1 < 1 || room.x2 > this.settings.tilesX - 1 || room.y1 < 1 || room.y2 > this.settings.tilesY - 1) {

			return false;

		}

		//Loop through every room in the list
		for(var i = 0; i < this.allRooms.length; i++) {

			//Check if the room intersects with the current room
			if(room.x1 <= this.allRooms[i].x2 && room.x2 >= this.allRooms[i].x1 && room.y1 <= this.allRooms[i].y2 && room.y2 >= this.allRooms[i].y1) {

				return false;

			}

		}
		//If the room doesn't intersect another room, return true
		return true;

	}

};
<|endoftext|>


<commit_before>/**
 * Map constructor
 *
 * @class Roguelike.Map
 * @classdesc The object that holds all the rooms, corridors and tiles
 *
 * @property {Roguelike.Game} game - Reference to the current game object
 */
Roguelike.Map = function(game) {

	/**
	 * @property {Roguelike.Game} game - Reference to the current game object
	 */
	this.game = game;

	/**
	 * @property {Roguelike.Group} entities - Holds all the entities of this game
	 */
	this.entities = null;

	/**
	 * @property {Number} tilesX - The number of horizontal tiles on this map
	 */
	this.tilesX = game.settings.tilesX;

	/**
	 * @property {Number} tilesY - The number of vertical tiles on this map
	 */
	this.tilesY = game.settings.tilesY;

	/**
	 * @property {Number} maxRooms - The maximum number of rooms allowed on this map
	 */
	this.maxRooms = game.settings.maxRooms;

	/**
	 * @property {Array} rooms - An array that holds all room objects
	 */
	this.rooms = [];

	/**
	 * @property {Array} tiles - An array that holds all tile objects
	 */
	this.tiles = [];

	/**
	 * @property {Array} objects - An array that holds all objects that are on the map
	 */
	this.objects = [];

	/**
	 * @property {Number} tileSize - The width and height of a single tile on the map
	 */
	this.tileSize = game.settings.tileSize;

	/**
	 * @property {Number} minRoomWidth - The minimum width of a room on this map
	 */
	this.minRoomWidth = game.settings.minRoomWidth;

	/**
	 * @property {Number} maxRoomWidth - The maximum width of a room on this map
	 */
	this.maxRoomWidth = game.settings.maxRoomWidth;

	/**
	 * @property {Number} minRoomHeight - The minimum heigth of a room on this map
	 */
	this.minRoomHeight = game.settings.minRoomHeight;

	/**
	 * @property {Number} maxRoomHeight - The maximum heigth of a room on this map
	 */
	this.maxRoomHeight = game.settings.maxRoomHeight;

	/**
	 * @property {Roguelike.MapFactory} mapFactory - The room factory is responsible for creating rooms and corridors on this map
	 */
	this.mapFactory = null;

	/**
	 * @property {entrance} object - An object that holds the position of the entrance of this map
	 */
	this.entrance = null;

	/**
	 * @property {exit} object - An object that holds the position of the exit of this map
	 */
	this.exit = null;

	//Initialize itself
	this.initialize();

};

Roguelike.Map.prototype = {

	/**
	 * Initialize the layout of the map, filling it with empty tiles
	 * @protected
	 */
	initialize: function() {

		//Create the map factory
		this.mapFactory = new Roguelike.MapFactory(this.game);

		//Loop through every horizontal row
		for(var x = 0; x < this.tilesX; x++) {

			//Initialize this row
			this.tiles[x] = [];

			//Loop through every vertical row
			for(var y = 0; y < this.tilesY; y++) {

				//Initialize this position by setting it to zero, and blocking light
				this.tiles[x][y] = new Roguelike.Tile(0, true, 0, 0);

			}

		}

	},

	/**
	 * Function that returns an array with only the tiletypes of every position
	 * Used for EasyStar Pathfinding
	 * @protected
	 *
	 * @return {Array} Array with only the tiletypes of every position on the map
	 */
	typeList: function() {

		//Define variables
		var mapTypeList = [];

		//Loop through every horizontal row
		for(var y = 0; y < this.tilesY; y++) {

			//Initialize this row
			mapTypeList.push([]);

			//Loop through every vertical row
			for(var x = 0; x < this.tilesX; x++) {

				//Initialize this position by setting it to zero, and blocking light
				mapTypeList[y][x] = (this.tiles[x][y].type);

			}

		}

		//Return the array with Y X coordinates of every tiletype
		return mapTypeList;

	},

	/**
	 * Check if a single room overlaps a room that is allready on the map
	 * @protected
	 *
	 * @param {Roguelike.Room} room - The room object that has to be checked
	 *
	 * @return {Boolean} True when the room intersects with an existing room, false when it's not intersecting
	 */
	roomIntersectsWith: function(room) {

		//Loop through every room in the list
		for(var i = 0; i < this.rooms.length; i++) {

			//Check if the room intersects with the current room
			if(room.x1 <= this.rooms[i].x2 && room.x2 >= this.rooms[i].x1 && room.y1 <= this.rooms[i].y2 && room.y2 >= this.rooms[i].y1) {
				return true;
			}

		}
		//If the room doesn't intersect another room, return false
		return false;

	},

	/**
	 * Add all the rooms from the room list to the map, get the tiles from each room's layout
	 * @protected
	 */
	addRooms: function() {

		//Loop through each room in the list
		for(var i = 0; i < this.rooms.length; i++) {

			//Loop through every horizontal row
			for(var x = this.rooms[i].x1; x < this.rooms[i].x2; x++) {

				//What is the current Y position in the layout of the current room
				var layoutXPos = this.rooms[i].x2 - x - 1;

				//Loop through every vertical row
				for(var y = this.rooms[i].y1; y < this.rooms[i].y2; y++) {

					//What is the current X position in the layout of the current room
					var layoutYPos = this.rooms[i].y2 - y - 1;

					//Get the current tile object
					var currentTile = this.rooms[i].layout[layoutXPos][layoutYPos];

					//Place the tile that is on the layout on this position on the map
					this.tiles[x][y] = currentTile;

				}

			}

		}

	}

};
<commit_msg>The map now holds a settings object instead of a lot of properties with settings.<commit_after>/**
 * Map constructor
 *
 * @class Roguelike.Map
 * @classdesc The object that holds all the rooms, corridors and tiles
 *
 * @param {Roguelike.Game} game - Reference to the current game object
 */
Roguelike.Map = function(game) {

	/**
	 * @property {Roguelike.Game} game - Reference to the current game object
	 */
	this.game = game;

	/**
	 * @property {Roguelike.Group} entities - Holds all the entities of this game
	 */
	this.entities = null;

	/**
	 * @property {Object} settings - The empty settings object
	 */
	this.settings = {};

	/**
	 * @property {Array} rooms - An array that holds all room objects
	 */
	this.rooms = [];

	/**
	 * @property {Array} tiles - An array that holds all tile objects
	 */
	this.tiles = [];

	/**
	 * @property {Array} objects - An array that holds all objects that are on the map
	 */
	this.objects = [];

	/**
	 * @property {Roguelike.Vector2} entrance - An object that holds the position of the entrance of this map
	 */
	this.entrance = null;

	/**
	 * @property {Roguelike.Vector2} exit - An object that holds the position of the exit of this map
	 */
	this.exit = null;

	/**
	 * @property {Array} objects - An array that holds all objects that are on the map
	 */
	this.roomsToExit = [];

	//Initialize itself
	this.initialize();

};

Roguelike.Map.prototype = {

	/**
	 * Initialize the layout of the map, filling it with empty tiles
	 * @protected
	 */
	initialize: function() {

		//TODO: Make this dynamic on the depth of the dungeon, this will allow the generator to make more complicated maps the deeper you go
		//Define settings
		this.settings = {
			tilesX: 60, //The number of horizontal tiles on this map
			tilesY: 40, //The number of vertical tiles on this map
			tileSize: 16, //The width and height of a single tile
			maxRooms: 15, //The maximum number of rooms on this map
			minRoomWidth: 6, //The minimum width of a single room
			maxRoomWidth: 10, //The maximum width of a single room
			minRoomHeight: 6, //The minimum height of a single room
			maxRoomHeight: 10, //The maximum height of a single room
			corridorLength: 5, //The lengt of a corridor, 0 for no corridors
		};

		//Loop through every horizontal row
		for(var x = 0; x < this.settings.tilesX; x++) {

			//Initialize this row
			this.tiles[x] = [];

			//Loop through every vertical row
			for(var y = 0; y < this.settings.tilesY; y++) {

				//Initialize this position by setting it to zero, and blocking light
				this.tiles[x][y] = new Roguelike.Tile(0, true, 0, 0);

			}

		}

	},

	/**
	 * Function that returns an array with only the tiletypes of every position
	 * Used for EasyStar Pathfinding
	 * @protected
	 *
	 * @return {Array} Array with only the tiletypes of every position on the map
	 */
	typeList: function() {

		//Define variables
		var mapTypeList = [];

		//Loop through every horizontal row
		for(var y = 0; y < this.tilesY; y++) {

			//Initialize this row
			mapTypeList.push([]);

			//Loop through every vertical row
			for(var x = 0; x < this.tilesX; x++) {

				//Initialize this position by setting it to zero, and blocking light
				mapTypeList[y][x] = (this.tiles[x][y].type);

			}

		}

		//Return the array with Y X coordinates of every tiletype
		return mapTypeList;

	},

	/**
	 * Check if a single room overlaps a room that is allready on the map
	 * @protected
	 *
	 * @param {Roguelike.Room} room - The room object that has to be checked
	 *
	 * @return {Boolean} True when the room intersects with an existing room, false when it's not intersecting
	 */
	roomIntersectsWith: function(room) {

		//Loop through every room in the list
		for(var i = 0; i < this.rooms.length; i++) {

			//Check if the room intersects with the current room
			if(room.x1 <= this.rooms[i].x2 && room.x2 >= this.rooms[i].x1 && room.y1 <= this.rooms[i].y2 && room.y2 >= this.rooms[i].y1) {
				return true;
			}

		}
		//If the room doesn't intersect another room, return false
		return false;

	}

};
<|endoftext|>


<commit_before><commit_msg>typecheck<commit_after>/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */ /*global define */

var timeCluster = function(list, timeframe, timefield) {
    "use strict";
    var self    = this;
    this.list   = [];

    this.sort = function(elems) {
        function compare(a,b) {
            if (a.time < b.time) { return -1; }
            if (a.time > b.time) { return 1;  }
            return 0;
        }
        elems.sort(compare);
};

    this.check_timeframe = function() {

    };

    this.init = function init() {
        var type, time, timestamp, date;

        if (Array.isArray(list) === false) {
                console.log("error: array expected");
                return;
        }

        if (list.length === 0) {
            console.log("warning - the array is empty");
            return;
            }

        type = typeof(list[0]);

        if (type !== "object") {
            console.log("the array contains " + type + "s instead of objects");
            return;
            }

        time = timefield || "time";

        if (! list[0][time])
            {
            console.log("the object has no property " + time);
            return;
            }

       timestamp = list[0][time];
       date = new Date(timestamp);
       if (date == "Invalid Date")
            {
            console.log("Invalid date - It seems that the field does not contain timestamps");
            return;
            }

        /// everything is ok ///
        self.sort(list);

        };

    self.init();

};

module.exports = exports = timeCluster;

<|endoftext|>


<commit_before>/**
 * Created by apizzimenti on 5/19/16.
 */

"use strict";

/**
 * @author Anthony Pizzimenti
 *
 * @desc Provides an easy way to specify debugging within the Phaser game.
 *
 * @param game {object} Phaser game instance.
 *
 * @property game {game} Phaser game instance.
 * @property x {number} Middle of the Phaser game window.
 * @property y {number} Starting height to display debug information.
 * @property color {string} Hexadecimal color code.
 * @property on {boolean} Turns the debug information on and off.
 *
 * @class {object} Debug
 * @this Debug
 * @constructor
 */

function Debug (game) {

    this.game = game;
    this.x = this.game.width / 2;
    this.y = 20;
    this.color = "#FFF";
    this.on = false;

    var graphics = game.add.graphics(0, 0),
        _this = this;

    graphics.fixedToCamera = true;
    graphics.lineStyle(1, 0xFFFFFF, 0);
    graphics.beginFill(0, 0xFFFFFF, 0);
    this.graphics = graphics;

    this.button = graphics.drawRect(20, 50, 62, 25);
    this.button.inputEnabled = true;
    this.button.input.useHandCursor = true;

    this.text = this.game.add.text(25, 50, "debug", {
        font: "Courier",
        fontSize: 20,
        fill: "white"
    });

    this.text.fixedToCamera = true;

    this.button.events.onInputDown.add(() => {
        this._switch();
    });
}

/**
 * @author Anthony Pizzimenti
 *
 * @desc Writes the current FPS to the game window.
 *
 * @this Debug
 */

Debug.prototype.fps = function () {

    if (this.on) {
        this.game.debug.text(this.game.time.fps, this.x, this.y, this.color);
    }
};

/**
 * @author Anthony Pizzimenti
 *
 * @desc Writes the current mouse position to the game window.
 *
 * @param mouse {Mouse} Mouse object.
 *
 * @this Debug
 *
 * @see mouseTrack
 */

Debug.prototype.mousePos = function (mouse) {

    if (this.on) {
        this.game.debug.text(`${mouse.row}, ${mouse.col}`, this.x, this.y + 20, this.color);
    }
};

/**
 * @author Anthony Pizzimenti
 *
 * @desc Displays debug information and bodies for one or more sprites.
 *
 * @param sprites {Player | Animal | Item}
 *
 * @this Debug
 */

Debug.prototype.sprite = function (sprites) {

    if (this.on) {
        var debugSprite = (sprite) => {

            try {

                var s = sprite.sprite;

                this.game.debug.body(s, "#FFFFFF", false);

                if (s.tile) {
                    this.game.debug.body(s.tile.top, "#FF0000", false);
                }

                if (s.tile) {
                    for (var tile in s.tile) {
                        if (s.tile.hasOwnProperty(tile) && tile !== "top") {
                            this.game.debug.body(s.tile[tile], "#FFDD00", false);
                        }
                    }
                }
            } catch (e) {
                console.warn(`${sprite.type} is not yet loaded`);
            }
        };

        if (Array.isArray(sprites)) {

            for (var sprite of sprites) {
                debugSprite(sprite);
            }

        } else {
            debugSprite(sprites);
        }
    }
};

/**
 * @author Anthony Pizzimenti
 *
 * @desc Displays blocked tiles" debug bodies.
 *
 * @param tiles {sprite[]} An array of tile sprites.
 *
 * @this Debug
 */

Debug.prototype.tiles = function (tiles) {

    if (this.on) {
        for (var i = 0; i < tiles.length; i++) {
            for (var j = 0; j < tiles[0].length; j++) {
                var tile = tiles[i][j];

                if (tile.blocked) {
                    this.game.debug.body(tiles[i][j], "#FFDD00", false);
                }
            }
        }
    }
};

/**
 * @author Anthony Pizzimenti
 *
 * @desc Allows for future implementation of a _button on/off switch for displaying debug info.
 *
 * @private
 *
 * @this Debug
 */

Debug.prototype._switch = function () {
    this.on = !this.on;
};<commit_msg>comment Debug object<commit_after>/**
 * Created by apizzimenti on 5/19/16.
 */

"use strict";

/**
 * @author Anthony Pizzimenti
 *
 * @desc Provides an easy way to specify debugging within the Phaser game.
 *
 * @param game {object} Phaser game instance.
 *
 * @property game {game} Phaser game instance.
 * @property x {number} Middle of the Phaser game window.
 * @property y {number} Starting height to display debug information.
 * @property color {string} Hexadecimal color code.
 * @property on {boolean} Turns the debug information on and off.
 *
 * @class {object} Debug
 * @this Debug
 * @constructor
 */

function Debug (game) {

    this.game = game;

    // gets middle screen position
    this.x = this.game.width / 2;

    this.y = 20;
    this.color = "#FFF";
    this.on = false;

    // add graphics and assign _this = this to preserve context
    var graphics = game.add.graphics(0, 0),
        _this = this;

    // fixes graphics to camera and assigns line and fill styles
    graphics.fixedToCamera = true;
    graphics.lineStyle(1, 0xFFFFFF, 0);
    graphics.beginFill(0, 0xFFFFFF, 0);

    this.graphics = graphics;

    // draws a button wireframe
    this.button = graphics.drawRect(20, 50, 62, 25);

    // enable mouse clicks and hand cursor
    this.button.inputEnabled = true;
    this.button.input.useHandCursor = true;

    // add text to the button area
    this.text = this.game.add.text(25, 50, "debug", {
        font: "Courier",
        fontSize: 20,
        fill: "white"
    });

    // fix *text* to camera
    this.text.fixedToCamera = true;

    // add event listener for the button click; call _switch() on callback
    this.button.events.onInputDown.add(() => {
        this._switch();
    });
}

/**
 * @author Anthony Pizzimenti
 *
 * @desc Writes the current FPS to the game window.
 *
 * @this Debug
 */

Debug.prototype.fps = function () {

    if (this.on) {
        this.game.debug.text(this.game.time.fps, this.x, this.y, this.color);
    }
};

/**
 * @author Anthony Pizzimenti
 *
 * @desc Writes the current mouse position to the game window.
 *
 * @param mouse {Mouse} Mouse object.
 *
 * @this Debug
 *
 * @see mouseTrack
 */

Debug.prototype.mousePos = function (mouse) {

    if (this.on) {
        this.game.debug.text(`${mouse.row}, ${mouse.col}`, this.x, this.y + 20, this.color);
    }
};

/**
 * @author Anthony Pizzimenti
 *
 * @desc Displays debug information and bodies for one or more sprites.
 *
 * @param sprites {Player | Animal | Item}
 *
 * @this Debug
 */

Debug.prototype.sprite = function (sprites) {

    if (this.on) {

        var debugSprite = (sprite) => {

            // try to write sprite wireframes to the game window;
            try {

                var s = sprite.sprite;

                this.game.debug.body(s, "#FFFFFF", false);

                if (s.tile) {
                    this.game.debug.body(s.tile.top, "#FF0000", false);
                }

                if (s.tile) {
                    for (var tile in s.tile) {
                        if (s.tile.hasOwnProperty(tile) && tile !== "top") {
                            this.game.debug.body(s.tile[tile], "#FFDD00", false);
                        }
                    }
                }
            } catch (e) {
                // if they aren't loaded yet, send a warning to the console window
                console.warn(`${sprite.type} is not yet loaded`);
            }
        };

        // check if sprites is an array or a single sprite
        if (Array.isArray(sprites)) {

            for (var sprite of sprites) {
                debugSprite(sprite);
            }

        } else {
            debugSprite(sprites);
        }
    }
};

/**
 * @author Anthony Pizzimenti
 *
 * @desc Displays blocked tiles" debug bodies.
 *
 * @param tiles {sprite[]} An array of tile sprites.
 *
 * @this Debug
 */

Debug.prototype.tiles = function (tiles) {

    if (this.on) {
        for (var i = 0; i < tiles.length; i++) {
            for (var j = 0; j < tiles[0].length; j++) {
                var tile = tiles[i][j];

                if (tile.blocked) {
                    this.game.debug.body(tiles[i][j], "#FFDD00", false);
                }
            }
        }
    }
};

/**
 * @author Anthony Pizzimenti
 *
 * @desc Allows for future implementation of a _button on/off switch for displaying debug info.
 *
 * @private
 *
 * @this Debug
 */

Debug.prototype._switch = function () {
    this.on = !this.on;
};<|endoftext|>


<commit_before>'use strict';

const Promise = require('./promise');

/**
 * The transaction object is used to identify a running transaction.
 * It is created by calling `Sequelize.transaction()`.
 * To run a query under a transaction, you should pass the transaction in the options object.
 *
 * @class Transaction
 * @see {@link Sequelize.transaction}
 */
class Transaction {
  /**
   * Creates a new transaction instance
   *
   * @param {Sequelize} sequelize A configured sequelize Instance
   * @param {Object} options An object with options
   * @param {string} options.type=true Sets the type of the transaction.
   * @param {string} options.isolationLevel=true Sets the isolation level of the transaction.
   * @param {string} options.deferrable Sets the constraints to be deferred or immediately checked.
   */
  constructor(sequelize, options) {
    this.sequelize = sequelize;
    this.savepoints = [];
    this._afterCommitHooks = [];

    // get dialect specific transaction options
    const generateTransactionId = this.sequelize.dialect.QueryGenerator.generateTransactionId;

    this.options = Object.assign({
      type: sequelize.options.transactionType,
      isolationLevel: sequelize.options.isolationLevel,
      readOnly: false
    }, options || {});

    this.parent = this.options.transaction;
    this.id = this.parent ? this.parent.id : generateTransactionId();

    if (this.parent) {
      this.id = this.parent.id;
      this.parent.savepoints.push(this);
      this.name = `${this.id}-sp-${this.parent.savepoints.length}`;
    } else {
      this.id = this.name = generateTransactionId();
    }

    delete this.options.transaction;
  }

  /**
   * Commit the transaction
   *
   * @returns {Promise}
   */
  commit() {
    if (this.finished) {
      return Promise.reject(new Error(`Transaction cannot be committed because it has been finished with state: ${this.finished}`));
    }

    this._clearCls();

    return this
      .sequelize
      .getQueryInterface()
      .commitTransaction(this, this.options)
      .finally(() => {
        this.finished = 'commit';
        if (!this.parent) {
          return this.cleanup();
        }
        return null;
      }).tap(
        () => Promise.each(
          this._afterCommitHooks,
          hook => Promise.resolve(hook.apply(this, [this])))
      );
  }

  /**
   * Rollback (abort) the transaction
   *
   * @returns {Promise}
   */
  rollback() {
    if (this.finished) {
      return Promise.reject(new Error(`Transaction cannot be rolled back because it has been finished with state: ${this.finished}`));
    }

    if (!this.connection) {
      return Promise.reject(new Error('Transaction cannot be rolled back because it never started'));
    }

    this._clearCls();

    return this
      .sequelize
      .getQueryInterface()
      .rollbackTransaction(this, this.options)
      .finally(() => {
        if (!this.parent) {
          return this.cleanup();
        }
        return this;
      });
  }

  prepareEnvironment(useCLS) {
    let connectionPromise;

    if (typeof useCLS === 'undefined') {
      useCLS = true;
    }

    if (this.parent) {
      connectionPromise = Promise.resolve(this.parent.connection);
    } else {
      const acquireOptions = { uuid: this.id };
      if (this.options.readOnly) {
        acquireOptions.type = 'SELECT';
      }
      connectionPromise = this.sequelize.connectionManager.getConnection(acquireOptions);
    }

    return connectionPromise
      .then(connection => {
        this.connection = connection;
        this.connection.uuid = this.id;
      })
      .then(() => {
        return this.begin()
          .then(() => this.setDeferrable())
          .then(() => this.setIsolationLevel())
          .catch(setupErr => this.rollback().finally(() => {
            throw setupErr;
          }));
      })
      .tap(() => {
        if (useCLS && this.sequelize.constructor._cls) {
          this.sequelize.constructor._cls.set('transaction', this);
        }
        return null;
      });
  }

  begin() {
    return this
      .sequelize
      .getQueryInterface()
      .startTransaction(this, this.options);
  }

  setDeferrable() {
    if (this.options.deferrable) {
      return this
        .sequelize
        .getQueryInterface()
        .deferConstraints(this, this.options);
    }
  }

  setIsolationLevel() {
    return this
      .sequelize
      .getQueryInterface()
      .setIsolationLevel(this, this.options.isolationLevel, this.options);
  }

  cleanup() {
    const res = this.sequelize.connectionManager.releaseConnection(this.connection);
    this.connection.uuid = undefined;
    return res;
  }

  _clearCls() {
    const cls = this.sequelize.constructor._cls;

    if (cls) {
      if (cls.get('transaction') === this) {
        cls.set('transaction', null);
      }
    }
  }

  /**
   * A hook that is run after a transaction is committed
   *
   * @param {Function} fn   A callback function that is called with the committed transaction
   * @name afterCommit
   * @memberof Sequelize.Transaction
   */
  afterCommit(fn) {
    if (!fn || typeof fn !== 'function') {
      throw new Error('"fn" must be a function');
    }
    this._afterCommitHooks.push(fn);
  }

  /**
   * Types can be set per-transaction by passing `options.type` to `sequelize.transaction`.
   * Default to `DEFERRED` but you can override the default type by passing `options.transactionType` in `new Sequelize`.
   * Sqlite only.
   *
   * Pass in the desired level as the first argument:
   *
   * @example
   * return sequelize.transaction({type: Sequelize.Transaction.TYPES.EXCLUSIVE}, transaction => {
   *   // your transactions
   * }).then(result => {
   *   // transaction has been committed. Do something after the commit if required.
   * }).catch(err => {
   *   // do something with the err.
   * });
   *
   * @property DEFERRED
   * @property IMMEDIATE
   * @property EXCLUSIVE
   */
  static get TYPES() {
    return {
      DEFERRED: 'DEFERRED',
      IMMEDIATE: 'IMMEDIATE',
      EXCLUSIVE: 'EXCLUSIVE'
    };
  }

  /**
   * Isolation levels can be set per-transaction by passing `options.isolationLevel` to `sequelize.transaction`.
   * Default to `REPEATABLE_READ` but you can override the default isolation level by passing `options.isolationLevel` in `new Sequelize`.
   *
   * Pass in the desired level as the first argument:
   *
   * @example
   * return sequelize.transaction({isolationLevel: Sequelize.Transaction.ISOLATION_LEVELS.SERIALIZABLE}, transaction => {
   *   // your transactions
   * }).then(result => {
   *   // transaction has been committed. Do something after the commit if required.
   * }).catch(err => {
   *   // do something with the err.
   * });
   *
   * @property READ_UNCOMMITTED
   * @property READ_COMMITTED
   * @property REPEATABLE_READ
   * @property SERIALIZABLE
   */
  static get ISOLATION_LEVELS() {
    return {
      READ_UNCOMMITTED: 'READ UNCOMMITTED',
      READ_COMMITTED: 'READ COMMITTED',
      REPEATABLE_READ: 'REPEATABLE READ',
      SERIALIZABLE: 'SERIALIZABLE'
    };
  }

  /**
   * Possible options for row locking. Used in conjunction with `find` calls:
   *
   * @example
   * // t1 is a transaction
   * Model.findAll({
   *   where: ...,
   *   transaction: t1,
   *   lock: t1.LOCK...
   * });
   *
   * @example
Postgres also supports specific locks while eager loading by using OF:

   * UserModel.findAll({
   *   where: ...,
   *   include: [TaskModel, ...],
   *   transaction: t1,
   *   lock: {
   *     level: t1.LOCK...,
   *     of: UserModel
   *   }
   * });
   *
   * # UserModel will be locked but TaskModel won't!
   *
   * @example
You can also skip locked rows:

   * // t1 is a transaction
   * Model.findAll({
   *   where: ...,
   *   transaction: t1,
   *   lock: true,
   *   skipLocked: true
   * });
   * # The query will now return any rows that aren't locked by another transaction
   *
   * @returns {Object}
   * @property UPDATE
   * @property SHARE
   * @property KEY_SHARE Postgres 9.3+ only
   * @property NO_KEY_UPDATE Postgres 9.3+ only
   */
  static get LOCK() {
    return {
      UPDATE: 'UPDATE',
      SHARE: 'SHARE',
      KEY_SHARE: 'KEY SHARE',
      NO_KEY_UPDATE: 'NO KEY UPDATE'
    };
  }

  /**
   * Please {@link Transaction.LOCK}
   */
  get LOCK() {
    return Transaction.LOCK;
  }
}

module.exports = Transaction;
module.exports.Transaction = Transaction;
module.exports.default = Transaction;
<commit_msg>docs(transaction): default isolation level #10111<commit_after>'use strict';

const Promise = require('./promise');

/**
 * The transaction object is used to identify a running transaction.
 * It is created by calling `Sequelize.transaction()`.
 * To run a query under a transaction, you should pass the transaction in the options object.
 *
 * @class Transaction
 * @see {@link Sequelize.transaction}
 */
class Transaction {
  /**
   * Creates a new transaction instance
   *
   * @param {Sequelize} sequelize A configured sequelize Instance
   * @param {Object} options An object with options
   * @param {string} options.type=true Sets the type of the transaction.
   * @param {string} options.isolationLevel=true Sets the isolation level of the transaction.
   * @param {string} options.deferrable Sets the constraints to be deferred or immediately checked.
   */
  constructor(sequelize, options) {
    this.sequelize = sequelize;
    this.savepoints = [];
    this._afterCommitHooks = [];

    // get dialect specific transaction options
    const generateTransactionId = this.sequelize.dialect.QueryGenerator.generateTransactionId;

    this.options = Object.assign({
      type: sequelize.options.transactionType,
      isolationLevel: sequelize.options.isolationLevel,
      readOnly: false
    }, options || {});

    this.parent = this.options.transaction;
    this.id = this.parent ? this.parent.id : generateTransactionId();

    if (this.parent) {
      this.id = this.parent.id;
      this.parent.savepoints.push(this);
      this.name = `${this.id}-sp-${this.parent.savepoints.length}`;
    } else {
      this.id = this.name = generateTransactionId();
    }

    delete this.options.transaction;
  }

  /**
   * Commit the transaction
   *
   * @returns {Promise}
   */
  commit() {
    if (this.finished) {
      return Promise.reject(new Error(`Transaction cannot be committed because it has been finished with state: ${this.finished}`));
    }

    this._clearCls();

    return this
      .sequelize
      .getQueryInterface()
      .commitTransaction(this, this.options)
      .finally(() => {
        this.finished = 'commit';
        if (!this.parent) {
          return this.cleanup();
        }
        return null;
      }).tap(
        () => Promise.each(
          this._afterCommitHooks,
          hook => Promise.resolve(hook.apply(this, [this])))
      );
  }

  /**
   * Rollback (abort) the transaction
   *
   * @returns {Promise}
   */
  rollback() {
    if (this.finished) {
      return Promise.reject(new Error(`Transaction cannot be rolled back because it has been finished with state: ${this.finished}`));
    }

    if (!this.connection) {
      return Promise.reject(new Error('Transaction cannot be rolled back because it never started'));
    }

    this._clearCls();

    return this
      .sequelize
      .getQueryInterface()
      .rollbackTransaction(this, this.options)
      .finally(() => {
        if (!this.parent) {
          return this.cleanup();
        }
        return this;
      });
  }

  prepareEnvironment(useCLS) {
    let connectionPromise;

    if (typeof useCLS === 'undefined') {
      useCLS = true;
    }

    if (this.parent) {
      connectionPromise = Promise.resolve(this.parent.connection);
    } else {
      const acquireOptions = { uuid: this.id };
      if (this.options.readOnly) {
        acquireOptions.type = 'SELECT';
      }
      connectionPromise = this.sequelize.connectionManager.getConnection(acquireOptions);
    }

    return connectionPromise
      .then(connection => {
        this.connection = connection;
        this.connection.uuid = this.id;
      })
      .then(() => {
        return this.begin()
          .then(() => this.setDeferrable())
          .then(() => this.setIsolationLevel())
          .catch(setupErr => this.rollback().finally(() => {
            throw setupErr;
          }));
      })
      .tap(() => {
        if (useCLS && this.sequelize.constructor._cls) {
          this.sequelize.constructor._cls.set('transaction', this);
        }
        return null;
      });
  }

  begin() {
    return this
      .sequelize
      .getQueryInterface()
      .startTransaction(this, this.options);
  }

  setDeferrable() {
    if (this.options.deferrable) {
      return this
        .sequelize
        .getQueryInterface()
        .deferConstraints(this, this.options);
    }
  }

  setIsolationLevel() {
    return this
      .sequelize
      .getQueryInterface()
      .setIsolationLevel(this, this.options.isolationLevel, this.options);
  }

  cleanup() {
    const res = this.sequelize.connectionManager.releaseConnection(this.connection);
    this.connection.uuid = undefined;
    return res;
  }

  _clearCls() {
    const cls = this.sequelize.constructor._cls;

    if (cls) {
      if (cls.get('transaction') === this) {
        cls.set('transaction', null);
      }
    }
  }

  /**
   * A hook that is run after a transaction is committed
   *
   * @param {Function} fn   A callback function that is called with the committed transaction
   * @name afterCommit
   * @memberof Sequelize.Transaction
   */
  afterCommit(fn) {
    if (!fn || typeof fn !== 'function') {
      throw new Error('"fn" must be a function');
    }
    this._afterCommitHooks.push(fn);
  }

  /**
   * Types can be set per-transaction by passing `options.type` to `sequelize.transaction`.
   * Default to `DEFERRED` but you can override the default type by passing `options.transactionType` in `new Sequelize`.
   * Sqlite only.
   *
   * Pass in the desired level as the first argument:
   *
   * @example
   * return sequelize.transaction({type: Sequelize.Transaction.TYPES.EXCLUSIVE}, transaction => {
   *   // your transactions
   * }).then(result => {
   *   // transaction has been committed. Do something after the commit if required.
   * }).catch(err => {
   *   // do something with the err.
   * });
   *
   * @property DEFERRED
   * @property IMMEDIATE
   * @property EXCLUSIVE
   */
  static get TYPES() {
    return {
      DEFERRED: 'DEFERRED',
      IMMEDIATE: 'IMMEDIATE',
      EXCLUSIVE: 'EXCLUSIVE'
    };
  }

  /**
   * Isolation levels can be set per-transaction by passing `options.isolationLevel` to `sequelize.transaction`.
   * Sequelize uses the default isolation level of the database, you can override this by passing `options.isolationLevel` in Sequelize constructor options.
   *
   * Pass in the desired level as the first argument:
   *
   * @example
   * return sequelize.transaction({isolationLevel: Sequelize.Transaction.ISOLATION_LEVELS.SERIALIZABLE}, transaction => {
   *   // your transactions
   * }).then(result => {
   *   // transaction has been committed. Do something after the commit if required.
   * }).catch(err => {
   *   // do something with the err.
   * });
   *
   * @property READ_UNCOMMITTED
   * @property READ_COMMITTED
   * @property REPEATABLE_READ
   * @property SERIALIZABLE
   */
  static get ISOLATION_LEVELS() {
    return {
      READ_UNCOMMITTED: 'READ UNCOMMITTED',
      READ_COMMITTED: 'READ COMMITTED',
      REPEATABLE_READ: 'REPEATABLE READ',
      SERIALIZABLE: 'SERIALIZABLE'
    };
  }

  /**
   * Possible options for row locking. Used in conjunction with `find` calls:
   *
   * @example
   * // t1 is a transaction
   * Model.findAll({
   *   where: ...,
   *   transaction: t1,
   *   lock: t1.LOCK...
   * });
   *
   * @example
Postgres also supports specific locks while eager loading by using OF:

   * UserModel.findAll({
   *   where: ...,
   *   include: [TaskModel, ...],
   *   transaction: t1,
   *   lock: {
   *     level: t1.LOCK...,
   *     of: UserModel
   *   }
   * });
   *
   * # UserModel will be locked but TaskModel won't!
   *
   * @example
You can also skip locked rows:

   * // t1 is a transaction
   * Model.findAll({
   *   where: ...,
   *   transaction: t1,
   *   lock: true,
   *   skipLocked: true
   * });
   * # The query will now return any rows that aren't locked by another transaction
   *
   * @returns {Object}
   * @property UPDATE
   * @property SHARE
   * @property KEY_SHARE Postgres 9.3+ only
   * @property NO_KEY_UPDATE Postgres 9.3+ only
   */
  static get LOCK() {
    return {
      UPDATE: 'UPDATE',
      SHARE: 'SHARE',
      KEY_SHARE: 'KEY SHARE',
      NO_KEY_UPDATE: 'NO KEY UPDATE'
    };
  }

  /**
   * Please {@link Transaction.LOCK}
   */
  get LOCK() {
    return Transaction.LOCK;
  }
}

module.exports = Transaction;
module.exports.Transaction = Transaction;
module.exports.default = Transaction;
<|endoftext|>


<commit_before>const recast = require("recast");
const b = recast.types.builders;
const JsDocTransformer = require('./jsdoc_transformer');

class Transformer {
  constructor(fileContents) {
    this.ast = recast.parse(fileContents);
  }

  /**
   * @param identifier
   * @param namespace
   * @return {Transformer}
   */
  addGoogRequire(identifier, namespace) {
    const body = this.ast.program.body;
    body.splice(1, 0, this.buildGoogRequire(identifier, namespace));
    return this;
  }

  injectConstructor(injectableName, namespace, shortNs) {
    return this.addConstructorParam(injectableName, '!' + shortNs)
        .addGoogRequire(shortNs, namespace);
  }

  /**
   *
   * @param {string} identifier
   * @param {string} type
   * @return {Transformer}
   */
  addConstructorParam(identifier, type) {
    const path = this.findConstructor();
    if (path) {
      // Add the parameter.
      path.get('value')
          .get('params')
          .push(b.identifier(identifier));

      // Add variable to the body of the constructor.
      const es = b.expressionStatement(
          b.assignmentExpression(
              '=',
              b.memberExpression(
                  b.thisExpression(),
                  b.identifier(identifier + '_')
              ),
              b.identifier(identifier)
          )
      );

      es.comments = [b.commentBlock(`* @private {${type}} `)];

      path.value.value.body.body.unshift(es);
    }
    path.node.comments[0].value = this.injectJsDoc(path, identifier, type);

    return this;
  }

  injectJsDoc(path, identifier, type) {
    // Remove the first two spaces of each line.
    const formattedJsDoc = path.node.comments[0].value
        .split('\n')
        .map(line => line.replace(/^  /, ''))
        .join('\n');

    return new JsDocTransformer(formattedJsDoc)
        .addParam(identifier, type)
        .toString();
  }

  findConstructor() {
    let constructorMethodDefinition = null;

    recast.visit(this.ast, {
      visitMethodDefinition: function(path) {
        if (path.value.kind === 'constructor') {
          constructorMethodDefinition = path;
          return false;
        }
        this.traverse(path);
      }
    });

    return constructorMethodDefinition;
  }

  /**
   *
   * @param serviceName
   * @param className
   * @param namespace
   * @return {Transformer}
   */
  addService(serviceName, className, namespace) {
    this.addGoogRequire(className, namespace);

    const angularModule = this.findAngularModule();

    const id = angularModule.parent.get('id');
    const expressionStatement = b.expressionStatement(
        b.callExpression(
            // <moduleName>.service(...)
            b.memberExpression(id.node, b.identifier('service')),
            // ('<serviceName>', <className>)
            [b.literal(serviceName), b.identifier(className)]
        )
    );
    angularModule.parent.parent.insertAfter(expressionStatement);
    return this;
  }

  /**
   * @param moduleName
   * @return {Transformer}
   */
  addModule(moduleName) {
    // Find the call expression to get the array of dependencies in the
    // angular.module('abc, [<this array>]).
    this.findAngularModule()
        .get('arguments', 1)
        .get('elements')
        .push(this.newMemberExpression(moduleName, 'name'));

    return this;
  }

  /**
   * Creates const <identifier> = goog.require('<namespace>');
   * @param identifier
   * @param namespace
   * @return {*}
   */
  buildGoogRequire(identifier, namespace) {
    return b.variableDeclaration('const', [
      b.variableDeclarator(b.identifier(identifier),
          b.callExpression(
              this.newMemberExpression('goog', 'require'),
              [b.literal(namespace)]
          )
      )
    ]);
  }

  /**
   * Returns the call expression for the angular module.
   * @return {*}
   */
  findAngularModule() {
    let angularModulePath = null;

    recast.visit(this.ast, {
      lastIdentifier: null,
      visitIdentifier: function(path) {
        const name = path.value.name;

        // Look for two consecutive identifiers: angular.module
        if (this.visitor.lastIdentifier === 'angular' && name === 'module') {
          angularModulePath = path.parent.parent;
          return false;
        }
        this.visitor.lastIdentifier = name;
        this.traverse(path);
      }
    });

    return angularModulePath;
  }

  /**
   * Creates member expressions with multiple identifiers. e.g. goog.require,
   * angular.module, etc.
   * @param identifiers
   * @return {*}
   */
  newMemberExpression(...identifiers) {
    return b.memberExpression.apply(null, identifiers.map(b.identifier));
  }

  toString() {
    return recast.print(this.ast, {quote: 'single'}).code;
  }
}

module.exports = Transformer;
<commit_msg>use multi-line regex<commit_after>const recast = require('recast');
const JsDocTransformer = require('./jsdoc_transformer');

const b = recast.types.builders;

class Transformer {
  constructor(fileContents) {
    this.ast = recast.parse(fileContents);
  }

  /**
   * @param identifier
   * @param namespace
   * @return {Transformer}
   */
  addGoogRequire(identifier, namespace) {
    const body = this.ast.program.body;
    body.splice(1, 0, this.buildGoogRequire(identifier, namespace));
    return this;
  }

  injectConstructor(injectableName, namespace, shortNs) {
    return this.addConstructorParam(injectableName, '!' + shortNs)
        .addGoogRequire(shortNs, namespace);
  }

  /**
   *
   * @param {string} identifier
   * @param {string} type
   * @return {Transformer}
   */
  addConstructorParam(identifier, type) {
    const path = this.findConstructor();
    if (path) {
      // Add the parameter.
      path.get('value')
          .get('params')
          .push(b.identifier(identifier));

      // Add variable to the body of the constructor.
      const es = b.expressionStatement(
          b.assignmentExpression(
              '=',
              b.memberExpression(
                  b.thisExpression(),
                  b.identifier(identifier + '_')
              ),
              b.identifier(identifier)
          )
      );

      es.comments = [b.commentBlock(`* @private {${type}} `)];

      path.value.value.body.body.unshift(es);
    }
    path.node.comments[0].value = this.injectJsDoc(path, identifier, type);

    return this;
  }

  injectJsDoc(path, identifier, type) {
    // Remove the first two spaces of each line.
    const formattedJsDoc = path.node.comments[0].value.replace(/^ {2}/mg, '');

    return new JsDocTransformer(formattedJsDoc)
        .addParam(identifier, type)
        .toString();
  }

  findConstructor() {
    let constructorMethodDefinition = null;

    recast.visit(this.ast, {
      visitMethodDefinition: function(path) {
        if (path.value.kind === 'constructor') {
          constructorMethodDefinition = path;
          return false;
        }
        this.traverse(path);
      }
    });

    return constructorMethodDefinition;
  }

  /**
   *
   * @param serviceName
   * @param className
   * @param namespace
   * @return {Transformer}
   */
  addService(serviceName, className, namespace) {
    this.addGoogRequire(className, namespace);

    const angularModule = this.findAngularModule();

    const id = angularModule.parent.get('id');
    const expressionStatement = b.expressionStatement(
        b.callExpression(
            // <moduleName>.service(...)
            b.memberExpression(id.node, b.identifier('service')),
            // ('<serviceName>', <className>)
            [b.literal(serviceName), b.identifier(className)]
        )
    );
    angularModule.parent.parent.insertAfter(expressionStatement);
    return this;
  }

  /**
   * @param moduleName
   * @return {Transformer}
   */
  addModule(moduleName) {
    // Find the call expression to get the array of dependencies in the
    // angular.module('abc, [<this array>]).
    this.findAngularModule()
        .get('arguments', 1)
        .get('elements')
        .push(this.newMemberExpression(moduleName, 'name'));

    return this;
  }

  /**
   * Creates const <identifier> = goog.require('<namespace>');
   * @param identifier
   * @param namespace
   * @return {*}
   */
  buildGoogRequire(identifier, namespace) {
    return b.variableDeclaration('const', [
      b.variableDeclarator(b.identifier(identifier),
          b.callExpression(
              this.newMemberExpression('goog', 'require'),
              [b.literal(namespace)]
          )
      )
    ]);
  }

  /**
   * Returns the call expression for the angular module.
   * @return {*}
   */
  findAngularModule() {
    let angularModulePath = null;

    recast.visit(this.ast, {
      lastIdentifier: null,
      visitIdentifier: function(path) {
        const name = path.value.name;

        // Look for two consecutive identifiers: angular.module
        if (this.visitor.lastIdentifier === 'angular' && name === 'module') {
          angularModulePath = path.parent.parent;
          return false;
        }
        this.visitor.lastIdentifier = name;
        this.traverse(path);
      }
    });

    return angularModulePath;
  }

  /**
   * Creates member expressions with multiple identifiers. e.g. goog.require,
   * angular.module, etc.
   * @param identifiers
   * @return {*}
   */
  newMemberExpression(...identifiers) {
    return b.memberExpression.apply(null, identifiers.map(b.identifier));
  }

  toString() {
    return recast.print(this.ast, {quote: 'single'}).code;
  }
}

module.exports = Transformer;
<|endoftext|>


<commit_before>/**
 * Fetch an HTTP url to a local file.
 **/

var request = require("request")
  , fs = require("graceful-fs")
  , npm = require("../npm.js")
  , url = require("url")
  , log = require("npmlog")
  , path = require("path")
  , mkdir = require("mkdirp")
  , chownr = require("chownr")
  , regHost

module.exports = fetch

function fetch (remote, local, headers, cb) {
  if (typeof cb !== "function") cb = headers, headers = {}
  log.verbose("fetch", "to=", local)
  mkdir(path.dirname(local), function (er, made) {
    if (er) return cb(er)
    fetch_(remote, local, headers, cb)
  })
}

function fetch_ (remote, local, headers, cb) {
  var fstr = fs.createWriteStream(local, { mode : npm.modes.file })
  var response = null
  var calledback = false
  fstr.on("error", function (er) {
    fs.close(fstr.fd, function () {})
    if (calledback) return
    calledback = true
    cb(fstr._ERROR = er)
  })
  fstr.on("open", function () {
    var req = makeRequest(remote, fstr, headers)
    req.on("response", function (res) {
      log.http(res.statusCode, remote)
      response = res
    })
  })
  fstr.on("close", function () {
    if (calledback) return
    calledback = true
    if (response && response.statusCode && response.statusCode >= 400) {
      var er = new Error(response.statusCode + " "
                        + require("http").STATUS_CODES[response.statusCode])
      cb(fstr._ERROR = er, response)
    } else {
      cb(null, response)
    }
  })
}

function makeRequest (remote, fstr, headers) {
  remote = url.parse(remote)
  log.http("GET", remote.href)
  regHost = regHost || url.parse(npm.config.get("registry")).host

  if (remote.host === regHost && npm.config.get("always-auth")) {
    remote.auth = new Buffer( npm.config.get("_auth")
                            , "base64" ).toString("utf8")
    if (!remote.auth) return fstr.emit("error", new Error(
      "Auth required and none provided. Please run 'npm adduser'"))
  }

  var proxy = npm.config.get( remote.protocol === "https:"
                            ? "https-proxy"
                            : "proxy")

  var opts = { url: remote
             , proxy: proxy
             , strictSSL: npm.config.get("strict-ssl")
             , ca: remote.host === regHost ? npm.config.get("ca") : undefined
             , headers: { "user-agent": npm.config.get("user-agent") }}
  var req = request(opts)
  req.on("error", function (er) {
    fstr.emit("error", er)
  })
  req.pipe(fstr)
  return req;
}
<commit_msg>Set https-proxy to http by default<commit_after>/**
 * Fetch an HTTP url to a local file.
 **/

var request = require("request")
  , fs = require("graceful-fs")
  , npm = require("../npm.js")
  , url = require("url")
  , log = require("npmlog")
  , path = require("path")
  , mkdir = require("mkdirp")
  , chownr = require("chownr")
  , regHost

module.exports = fetch

function fetch (remote, local, headers, cb) {
  if (typeof cb !== "function") cb = headers, headers = {}
  log.verbose("fetch", "to=", local)
  mkdir(path.dirname(local), function (er, made) {
    if (er) return cb(er)
    fetch_(remote, local, headers, cb)
  })
}

function fetch_ (remote, local, headers, cb) {
  var fstr = fs.createWriteStream(local, { mode : npm.modes.file })
  var response = null
  var calledback = false
  fstr.on("error", function (er) {
    fs.close(fstr.fd, function () {})
    if (calledback) return
    calledback = true
    cb(fstr._ERROR = er)
  })
  fstr.on("open", function () {
    var req = makeRequest(remote, fstr, headers)
    req.on("response", function (res) {
      log.http(res.statusCode, remote)
      response = res
    })
  })
  fstr.on("close", function () {
    if (calledback) return
    calledback = true
    if (response && response.statusCode && response.statusCode >= 400) {
      var er = new Error(response.statusCode + " "
                        + require("http").STATUS_CODES[response.statusCode])
      cb(fstr._ERROR = er, response)
    } else {
      cb(null, response)
    }
  })
}

function makeRequest (remote, fstr, headers) {
  remote = url.parse(remote)
  log.http("GET", remote.href)
  regHost = regHost || url.parse(npm.config.get("registry")).host

  if (remote.host === regHost && npm.config.get("always-auth")) {
    remote.auth = new Buffer( npm.config.get("_auth")
                            , "base64" ).toString("utf8")
    if (!remote.auth) return fstr.emit("error", new Error(
      "Auth required and none provided. Please run 'npm adduser'"))
  }

  var proxy
  if (remote.protocol !== "https:" || !(proxy = npm.config.get("https-proxy"))) {
    proxy = npm.config.get("proxy")
  }

  var opts = { url: remote
             , proxy: proxy
             , strictSSL: npm.config.get("strict-ssl")
             , ca: remote.host === regHost ? npm.config.get("ca") : undefined
             , headers: { "user-agent": npm.config.get("user-agent") }}
  var req = request(opts)
  req.on("error", function (er) {
    fstr.emit("error", er)
  })
  req.pipe(fstr)
  return req;
}
<|endoftext|>


<commit_before>showHide = function(selector) {
  d3.select(selector).select('.hide').on('click', function(){
    d3.select(selector)
      .classed('visible', false)
      .classed('hidden', true);
  });

  d3.select(selector).select('.show').on('click', function(){
    d3.select(selector)
      .classed('visible', true)
      .classed('hidden', false);
  });
}

voronoiMap = function(map, url, initialSelections) {
  var pointTypes = d3.map(),
      points = [],
      lastSelectedPoint;

  var voronoi = d3.geom.voronoi()
      .x(function(d) { return d.x; })
      .y(function(d) { return d.y; });

  var selectPoint = function() {
    d3.selectAll('.selected').classed('selected', false);

    var cell = d3.select(this),
        point = cell.datum();

    lastSelectedPoint = point;
    cell.classed('selected', true);

    d3.select('#selected h1')
      .html('')
      .append('a')
        .text(point.name)
        .attr('href', point.url)
        .attr('target', '_blank')
  }

  var drawPointTypeSelection = function() {
    showHide('#selections')
    labels = d3.select('#toggles').selectAll('input')
      .data(pointTypes.values())
      .enter().append("label");

    labels.append("input")
      .attr('type', 'checkbox')
      .property('checked', function(d) {
        return initialSelections === undefined || initialSelections.has(d.type)
      })
      .attr("value", function(d) { return d.type; })
      .on("change", drawWithLoading);

    labels.append("span")
      .attr('class', 'key')
      .style('background-color', function(d) { return '#' + d.color; });

    labels.append("span")
      .text(function(d) { return d.type; });
  }

  var selectedTypes = function() {
    return d3.selectAll('#toggles input[type=checkbox]')[0].filter(function(elem) {
      return elem.checked;
    }).map(function(elem) {
      return elem.value;
    })
  }

  var pointsFilteredToSelectedTypes = function() {
    var currentSelectedTypes = d3.set(selectedTypes());
    return points.filter(function(item){
      return currentSelectedTypes.has(item.type);
    });
  }

  var drawWithLoading = function(e){
    d3.select('#loading').classed('visible', true);
    if (e && e.type == 'viewreset') {
      d3.select('#overlay').remove();
    }
    setTimeout(function(){
      draw();
      d3.select('#loading').classed('visible', false);
    }, 0);
  }

  var draw = function() {
    d3.select('#overlay').remove();

    var bounds = map.getBounds(),
        topLeft = map.latLngToLayerPoint(bounds.getNorthWest()),
        bottomRight = map.latLngToLayerPoint(bounds.getSouthEast()),
        existing = d3.set(),
        drawLimit = bounds.pad(0.4);

    filteredPoints = pointsFilteredToSelectedTypes().filter(function(d) {
      var latlng = new L.LatLng(d.latitude, d.longitude);

      if (!drawLimit.contains(latlng)) { return false };

      var point = map.latLngToLayerPoint(latlng);

      key = point.toString();
      if (existing.has(key)) { return false };
      existing.add(key);

      d.x = point.x;
      d.y = point.y;
      return true;
    });

    voronoi(filteredPoints).forEach(function(d) { d.point.cell = d; });

    var svg = d3.select(map.getPanes().overlayPane).append("svg")
      .attr('id', 'overlay')
      .attr("class", "leaflet-zoom-hide")
      .style("width", map.getSize().x + 'px')
      .style("height", map.getSize().y + 'px')
      .style("margin-left", topLeft.x + "px")
      .style("margin-top", topLeft.y + "px");

    var g = svg.append("g")
      .attr("transform", "translate(" + (-topLeft.x) + "," + (-topLeft.y) + ")");

    var svgPoints = g.attr("class", "points")
      .selectAll("g")
        .data(filteredPoints)
      .enter().append("g")
        .attr("class", "point")
        .attr('data-name', function(d) { return d.name } );

    var buildPathFromPoint = function(point) {
      return "M" + point.cell.join("L") + "Z";
    }

    svgPoints.append("path")
      .attr("class", "point-cell")
      .attr("d", buildPathFromPoint)
      .on('click', selectPoint)
      .classed("selected", function(d) { return lastSelectedPoint == d} );

    svgPoints.append("circle")
      .attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; })
      .style('fill', function(d) { return '#' + d.color } )
      .attr("r", 2);
  }

  var mapLayer = {
    onAdd: function(map) {
      map.on('viewreset moveend', drawWithLoading);
      drawWithLoading();
    }
  };

  showHide('#about');

  map.on('ready', function() {
    d3.csv(url, function(csv) {
      points = csv;
      points.forEach(function(point) {
        pointTypes.set(point.type, {type: point.type, color: point.color});
      })
      drawPointTypeSelection();
      map.addLayer(mapLayer);
    })
  });
}<commit_msg>Don't set the name on elements.<commit_after>showHide = function(selector) {
  d3.select(selector).select('.hide').on('click', function(){
    d3.select(selector)
      .classed('visible', false)
      .classed('hidden', true);
  });

  d3.select(selector).select('.show').on('click', function(){
    d3.select(selector)
      .classed('visible', true)
      .classed('hidden', false);
  });
}

voronoiMap = function(map, url, initialSelections) {
  var pointTypes = d3.map(),
      points = [],
      lastSelectedPoint;

  var voronoi = d3.geom.voronoi()
      .x(function(d) { return d.x; })
      .y(function(d) { return d.y; });

  var selectPoint = function() {
    d3.selectAll('.selected').classed('selected', false);

    var cell = d3.select(this),
        point = cell.datum();

    lastSelectedPoint = point;
    cell.classed('selected', true);

    d3.select('#selected h1')
      .html('')
      .append('a')
        .text(point.name)
        .attr('href', point.url)
        .attr('target', '_blank')
  }

  var drawPointTypeSelection = function() {
    showHide('#selections')
    labels = d3.select('#toggles').selectAll('input')
      .data(pointTypes.values())
      .enter().append("label");

    labels.append("input")
      .attr('type', 'checkbox')
      .property('checked', function(d) {
        return initialSelections === undefined || initialSelections.has(d.type)
      })
      .attr("value", function(d) { return d.type; })
      .on("change", drawWithLoading);

    labels.append("span")
      .attr('class', 'key')
      .style('background-color', function(d) { return '#' + d.color; });

    labels.append("span")
      .text(function(d) { return d.type; });
  }

  var selectedTypes = function() {
    return d3.selectAll('#toggles input[type=checkbox]')[0].filter(function(elem) {
      return elem.checked;
    }).map(function(elem) {
      return elem.value;
    })
  }

  var pointsFilteredToSelectedTypes = function() {
    var currentSelectedTypes = d3.set(selectedTypes());
    return points.filter(function(item){
      return currentSelectedTypes.has(item.type);
    });
  }

  var drawWithLoading = function(e){
    d3.select('#loading').classed('visible', true);
    if (e && e.type == 'viewreset') {
      d3.select('#overlay').remove();
    }
    setTimeout(function(){
      draw();
      d3.select('#loading').classed('visible', false);
    }, 0);
  }

  var draw = function() {
    d3.select('#overlay').remove();

    var bounds = map.getBounds(),
        topLeft = map.latLngToLayerPoint(bounds.getNorthWest()),
        bottomRight = map.latLngToLayerPoint(bounds.getSouthEast()),
        existing = d3.set(),
        drawLimit = bounds.pad(0.4);

    filteredPoints = pointsFilteredToSelectedTypes().filter(function(d) {
      var latlng = new L.LatLng(d.latitude, d.longitude);

      if (!drawLimit.contains(latlng)) { return false };

      var point = map.latLngToLayerPoint(latlng);

      key = point.toString();
      if (existing.has(key)) { return false };
      existing.add(key);

      d.x = point.x;
      d.y = point.y;
      return true;
    });

    voronoi(filteredPoints).forEach(function(d) { d.point.cell = d; });

    var svg = d3.select(map.getPanes().overlayPane).append("svg")
      .attr('id', 'overlay')
      .attr("class", "leaflet-zoom-hide")
      .style("width", map.getSize().x + 'px')
      .style("height", map.getSize().y + 'px')
      .style("margin-left", topLeft.x + "px")
      .style("margin-top", topLeft.y + "px");

    var g = svg.append("g")
      .attr("transform", "translate(" + (-topLeft.x) + "," + (-topLeft.y) + ")");

    var svgPoints = g.attr("class", "points")
      .selectAll("g")
        .data(filteredPoints)
      .enter().append("g")
        .attr("class", "point");

    var buildPathFromPoint = function(point) {
      return "M" + point.cell.join("L") + "Z";
    }

    svgPoints.append("path")
      .attr("class", "point-cell")
      .attr("d", buildPathFromPoint)
      .on('click', selectPoint)
      .classed("selected", function(d) { return lastSelectedPoint == d} );

    svgPoints.append("circle")
      .attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; })
      .style('fill', function(d) { return '#' + d.color } )
      .attr("r", 2);
  }

  var mapLayer = {
    onAdd: function(map) {
      map.on('viewreset moveend', drawWithLoading);
      drawWithLoading();
    }
  };

  showHide('#about');

  map.on('ready', function() {
    d3.csv(url, function(csv) {
      points = csv;
      points.forEach(function(point) {
        pointTypes.set(point.type, {type: point.type, color: point.color});
      })
      drawPointTypeSelection();
      map.addLayer(mapLayer);
    })
  });
}<|endoftext|>


<commit_before>'use strict';

var crypto = require('crypto'),
  gm = require('gm').subClass({
    imageMagick: true
  }), // Enable ImageMagick integration.
  async = require('async'),
  objectAssign = require('object-assign');

  // TODO: REMOVE THIS DEBUG GLOBAL!
  // this.options aren't being passed around to prototypes :(
  var options = {
    replace: true,
    debug: true,
    watermarkImagePath: './example/ABL_watermark_new.png',
    relativeSize: 10,
    opacity: 40
  };

function Watermarker(options) {
  if (!(this instanceof Watermarker)) {
    return new Watermarker(options);
  }
  var defaultOptions = {
    replace: true,
    debug: false,
    opacity: 50,
    relativeSize: 5
  };

  this.options = objectAssign(defaultOptions, options || {});
  // TODO: validate these options
}

function calculateGeometry(boundingBox, maxSide) {
  // TODO: handle non-square watermark images
  if (typeof boundingBox.width !== 'number' || typeof boundingBox.height !== 'number') {
    throw new Error('BoundingBox width or height is not a number');
  }
  return 'x' + maxSide + '+' + (boundingBox.width - maxSide) + '+' + (boundingBox.height - maxSide);
}

function verifyFileTypeFromPath(path, type) {
  var typeMatch = path.match(/\.([^.]*)$/);
  if (!typeMatch) {
    throw new Error('Could not infer filetype from path');
  }

  var imageType = typeMatch[1];
  return imageType.toLowerCase() !== type.toLowerCase();
}

Watermarker.prototype.watermark = function (image, next) {
  // if (!(image && image.Body instanceof Buffer)) {
  //   console.log('image:', image, image.Body instanceof Buffer);
  //   return next('image buffer is not a buffer!');
  // }

  if (!(image && image.ContentType)) {
    return next('image type is missing!');
  }

  // ContentType: 'image/jpeg', ContentType: 'image/jpg', ContentType: 'image/png'
  // if (image.ContentType !== 'png' && image.ContentType !== 'jpg') {
  //   return next('image type is not jpg or png!');
  // }

  async.waterfall([
    async.apply(_resizeWatermarkImage, image),
    _applyWatermark
  ], next);
}.bind(Watermarker);

//Watermarker.prototype.watermark

Watermarker.prototype._resizeWatermarkImage = _resizeWatermarkImage;

function _resizeWatermarkImage(image, next) {
  if (verifyFileTypeFromPath(options.watermarkImagePath, 'png')) {
    return next('Watermark image is not a png');
  }
  gm(image.Body).size(function (err, size) {
    if (err) {
      return next(err);
    }
    var watermarkSide = Math.sqrt(size.width * size.height * (options.relativeSize / 100));

    next(null, image, calculateGeometry(size, watermarkSide));
  });
};

Watermarker.prototype._applyWatermark = _applyWatermark;

function _applyWatermark(image, geometry, next) {
  console.log('applying watermark');
  gm(image.Body)
    .composite(TEMP_IMAGE_PATH)
    .geometry(geometry)
    .dissolve(options.opacity)
    .toBuffer('jpg', function (err, buffer) { // TODO: Remove debug image filetype!
      if (err) {
        next(err);
      } else {
        next(null, buffer, image.ContentType);
      }
    });
}

module.exports = Watermarker;
<commit_msg>Use correct image path<commit_after>'use strict';

var crypto = require('crypto'),
  gm = require('gm').subClass({
    imageMagick: true
  }), // Enable ImageMagick integration.
  async = require('async'),
  objectAssign = require('object-assign');

  // TODO: REMOVE THIS DEBUG GLOBAL!
  // this.options aren't being passed around to prototypes :(
  var options = {
    replace: true,
    debug: true,
    watermarkImagePath: './example/ABL_watermark_new.png',
    relativeSize: 10,
    opacity: 40
  };

function Watermarker(options) {
  if (!(this instanceof Watermarker)) {
    return new Watermarker(options);
  }
  var defaultOptions = {
    replace: true,
    debug: false,
    opacity: 50,
    relativeSize: 5
  };

  this.options = objectAssign(defaultOptions, options || {});
  // TODO: validate these options
}

function calculateGeometry(boundingBox, maxSide) {
  // TODO: handle non-square watermark images
  if (typeof boundingBox.width !== 'number' || typeof boundingBox.height !== 'number') {
    throw new Error('BoundingBox width or height is not a number');
  }
  return 'x' + maxSide + '+' + (boundingBox.width - maxSide) + '+' + (boundingBox.height - maxSide);
}

function verifyFileTypeFromPath(path, type) {
  var typeMatch = path.match(/\.([^.]*)$/);
  if (!typeMatch) {
    throw new Error('Could not infer filetype from path');
  }

  var imageType = typeMatch[1];
  return imageType.toLowerCase() !== type.toLowerCase();
}

Watermarker.prototype.watermark = function (image, next) {
  // if (!(image && image.Body instanceof Buffer)) {
  //   console.log('image:', image, image.Body instanceof Buffer);
  //   return next('image buffer is not a buffer!');
  // }

  if (!(image && image.ContentType)) {
    return next('image type is missing!');
  }

  // ContentType: 'image/jpeg', ContentType: 'image/jpg', ContentType: 'image/png'
  // if (image.ContentType !== 'png' && image.ContentType !== 'jpg') {
  //   return next('image type is not jpg or png!');
  // }

  async.waterfall([
    async.apply(_resizeWatermarkImage, image),
    _applyWatermark
  ], next);
}.bind(Watermarker);

//Watermarker.prototype.watermark

Watermarker.prototype._resizeWatermarkImage = _resizeWatermarkImage;

function _resizeWatermarkImage(image, next) {
  if (verifyFileTypeFromPath(options.watermarkImagePath, 'png')) {
    return next('Watermark image is not a png');
  }
  gm(image.Body).size(function (err, size) {
    if (err) {
      return next(err);
    }
    var watermarkSide = Math.sqrt(size.width * size.height * (options.relativeSize / 100));

    next(null, image, calculateGeometry(size, watermarkSide));
  });
};

Watermarker.prototype._applyWatermark = _applyWatermark;

function _applyWatermark(image, geometry, next) {
  console.log('applying watermark');
  gm(image.Body)
    .composite(options.watermarkImagePath)
    .geometry(geometry)
    .dissolve(options.opacity)
    .toBuffer('jpg', function (err, buffer) { // TODO: Remove debug image filetype!
      if (err) {
        next(err);
      } else {
        next(null, buffer, image.ContentType);
      }
    });
}

module.exports = Watermarker;
<|endoftext|>