<commit_before>		//初始化引擎
		init(30,"mylegend",320,480,main,LEvent.INIT);
		//进度条显示层，背景层，方块绘制层，预览层
		var loadingLayer,backLayer,graphicsLayer,nextLayer;
		//存放图片对象的属性
		var imglist = {};
		//图片数据
		var imgData = new Array(
			{name:"backImage",path:"./image/backImage.png"},
			{name:"block1",path:"./image/block1.png"},
			{name:"block2",path:"./image/block2.png"},
			{name:"block3",path:"./image/block3.png"},
			{name:"block4",path:"./image/block4.png"}
			);
		//用于生成方块
		var box;
		//方块坐标数组初始化
		var map;
		var nodelist;
		var bitmapdataList;
		//方块区域起始位置
		var START_X1=15,START_Y1=20,START_X2=228,START_Y2=65;
		//预览方块和当前方块
		var nextBox,nowBox;
		var pointBox ={x:0,y:0};
		var speed=15,speedIndex=0,speedMax=15;
		var point=0,pointText;
		//消除层数相关
		var del=0,delText;
		//控制单元
		var myKey = {
			keyControl:null,
			step:1,
			stepindex:0,
			isTouchDown:false,
			touchX:0,
			touchY:0,
			touchMove:false
		};
		//main函数
		function main(){
			map =[
				[0,0,0,0,0,0,0,0,0,0],
				[0,0,0,0,0,0,0,0,0,0],
				[0,0,0,0,0,0,0,0,0,0],
				[0,0,0,0,0,0,0,0,0,0],
				[0,0,0,0,0,0,0,0,0,0],
				[0,0,0,0,0,0,0,0,0,0],
				[0,0,0,0,0,0,0,0,0,0],
				[0,0,0,0,0,0,0,0,0,0],
				[0,0,0,0,0,0,0,0,0,0],
				[0,0,0,0,0,0,0,0,0,0],
				[0,0,0,0,0,0,0,0,0,0],
				[0,0,0,0,0,0,0,0,0,0],
				[0,0,0,0,0,0,0,0,0,0],
				[0,0,0,0,0,0,0,0,0,0],
				[0,0,0,0,0,0,0,0,0,0],
				[0,0,0,0,0,0,0,0,0,0],
				[0,0,0,0,0,0,0,0,0,0],
				[0,0,0,0,0,0,0,0,0,0],
				[0,0,0,0,0,0,0,0,0,0],
				[0,0,0,0,0,0,0,0,0,0]
			];
			box = new Box();
			//背景层初始化
			backLayer = new LSprite();
			//在背景层描绘背景
			backLayer.graphics.drawRect(2,"brown",[0,0,350,480],true,"black");
			addChild(backLayer);
			//进度条显示层初始化
			loadingLayer = new LoadingSample1();
			backLayer.addChild(loadingLayer);
			//利用LLoadManage类：进度条的读取与显示
			LLoadManage.load(
				imgData,
				function(progress){
					loadingLayer.setProgress(progress);
			    },
			    function(result){
			    	imglist = result;
					backLayer.removeChild(loadingLayer);
					loadingLayer= null;
					gameInit();
			    }
			);
			//gameInit();
		}
		//游戏标题画面初始化
		function gameInit(){
			//显示游戏标题
			var title = new LTextField();
			title.x = 100;
			title.y = 100;
			title.text = "俄罗斯方块";
			title.size = 30;
			title.color ="white";
			backLayer.addChild(title);
			//提示信息
			backLayer.graphics.drawRect(1,"white",[50,250,250,30]);
			var infoText = new LTextField();
			infoText.x = 75;
			infoText.y = 250;
			infoText.size = 25;
			infoText.text = "点击页面开始游戏";
			infoText.color = "white";
			backLayer.addChild(infoText);
			//添加鼠标点击事件侦听
			infoText.addEventListener(LMouseEvent.MOUSE_UP,gameStart);
		}
		//游戏画面初始化
		function gameStart(event){
			//背景层清空
			backLayer.die();
			backLayer.removeAllChild();
			var bitmap = new LBitmap(new LBitmapData(imglist["backImage"]));
			backLayer.addChild(bitmap);
			//获得新方块
			getNewBox();
			//在屏幕上添加方块
			addBox();
			//添加循环播放事件
			backLayer.addEventListener(LEvent.ENTER_FRAME, onframe);
			//添加键盘事件用于控制方块移动
			LEvent.addEventListener(LGlobal.window,LKeyboardEvent.KEY_DOWN,onkeydown);
			LEvent.addEventListener(LGlobal.window,LKeyboardEvent.KEY_UP,onkeyup);
		}
		//键盘按下事件
		function onkeydown(event){
			if(myKey.keyControl != null){
				return;
			}
			if(event.keyCode == 37){
				//left
				myKey.keyControl = "left";
			}else if(event.keyCode == 38){
				//up
				myKey.keyControl = "up";
			}else if(event.keyCode == 39){
				//right
				myKey.keyControl = "right";
			}else if(event.keyCode == 40){
				//down
				myKey.keyControl = "down";
			}
		}
		//键盘弹起事件
		function onkeyup(event){
			//弹起后myKey属性恢复默认
			myKey.keyControl = null;
			myKey.stepindex = 0;
		}
		//循环实现方块下落
		function onframe(){
			//首先移除当前下落的方块
			removeBox();
			if(myKey.keyControl != null && myKey.stepindex-- < 0){
				myKey.stepindex = myKey.step;
				switch(myKey.keyControl){
					case "left":
						if(checkBox(-1,0)){
							pointBox.x-=1;
						}
						break;
					case "right":
						if(checkBox(1,0)){
							pointBox.x+=1;
						}
						break;
					case "down":
						if(checkBox(0,1)){
							pointBox.y+=1;
						}
						break;
					case "up":
						changeBox();
						break;
				}
			}
			if(speedIndex++ > speed){
				speedIndex = 0;
				if(checkBox(0,1)){
					pointBox.y++;
				}else{
					//无法下移
					addBox();
					if(pointBox.y<0){
						gameOver();
						return;
					}
					delBox();
					getNewBox();
				}
			}
			addBox();
			drawMap();
		}
		//方块变形
		function changeBox(){
			var saveBox = nowBox;
			nowBox =[
				[0,0,0,0],
				[0,0,0,0],
				[0,0,0,0],
				[0,0,0,0]
			];
			var i,j;
			for(i=0;i<saveBox.length;i++){
				for(j=0;j<saveBox[0].length;j++){
					nowBox[i][j] = saveBox[3-j][i];
				}
			}
			if (!checkBox(0,0)){
				nowBox = saveBox;
			}
		}
		//绘制所有的方块
		function drawMap(){
			var i,j;
			for(i=0;i<map.length;i++){
				for(j=0;j<map[0].length;j++){
					if(nodelist[i][j]["index"] >=0){
						nodelist[i][j]["bitmap"].bitmapData =bitmapdataList[nodelist[i][j]["index"]];
					}else{
						nodelist[i][j]["bitmap"].bitmapData = null;
					}
				}
			}
		}
		//判断是否可移动
		function checkBox(nx,ny){
			var i,j;
			if(pointBox.y < 0){
				//防止方块下落之前，就已向左或向右移到屏幕之外
				if(pointBox.x + nx < 0 || pointBox.x + nx > map[0].length - 4){
					return false;
				}
			}
			//遍历nowBox数组
			for(i=0;i<nowBox.length;i++){
				for(j=0;j<nowBox[0].length;j++){
					//判断方块网格是否进入map
					if(i+pointBox.y+ny<0){
						continue;
					}else if(i+pointBox.y+ny>=map.length||j+pointBox.x+nx>=map[0].length||j+pointBox.x+nx<0){
						//超出网格范围时
						if(nowBox[i][j] ==0){
							continue;
						}else{
							return false;
						}
					}
					if(nowBox[i][j] > 0 && map[i+pointBox.y+ny][j+pointBox.x+nx]>0){
						return false;
					}
				}
			}
			return true;
		}
		//移除方块
		function removeBox(){
			var i,j;
			for(i=0;i<nowBox.length;i++){
				for(j=0;j<nowBox[0].length;j++){
					if(i+pointBox.y<0||i+pointBox.y>=map.length||j+pointBox.x<0||j+pointBox.x>=map[0].length){
						continue;
					}
					map[i+pointBox.y][j+pointBox.x]=map[i+pointBox.y][j+pointBox.x]-nowBox[i][j];
					nodelist[i+pointBox.y][j+pointBox.x]["index"] = map[i+pointBox.y][j+pointBox.x] -1;
				}
			}
		}
		//将当前方块添加至游戏界面
		function addBox(){
			var i,j;
			for(i=0;i<nowBox.length;i++){
				for(j=0;j<nowBox[0].length;j++){
					if(i+pointBox.y<0||i+pointBox.y>=map.length||j+pointBox.x<0||j+pointBox.x>=map[i].length){
						continue;
					}
					map[i+pointBox.y][j+pointBox.x]=nowBox[i][j]+map[i+pointBox.y][j+pointBox.x];
					nodelist[i+pointBox.y][j+pointBox.x]["index"] = map[i+pointBox.y][j+pointBox.x] -1;
				}
			}
		}
		//获得新方块
		function getNewBox(){
			if(nextBox ==null){
				nextBox = box.getBox();
			}
			nowBox = nextBox;
			//当前下落方块的坐标
			pointBox.x=3;
			pointBox.y=-4;
			nextBox = box.getBox();
			nextLayer.removeAllChild();
			//将nextBox显示在预览层
			var i,j,bitmap;
			for(i=0;i<nextBox.length;i++){
				for(j=0;j<nextBox[0].length;j++){
					if(nextBox[i][j]===0){
						continue;
					}
					bitmap =new LBitmap(bitmapdataList[nextBox[i][j]-1]);
					bitmap.x= bitmap.getWidth()*j+START_X2;
					bitmap.y= bitmap.getHeight()*i+START_Y2;
					nextLayer.addChild(bitmap);
				}
			}
		}
		//消除整行方块
		function moveLine(line){
			var i;
			for(i = line;i>1;i--){
				for(j = 0; j<map[0].length; j++){
					map[i][j] = map[i-1][j];
					nodelist[i][j].index = nodelist[i-1][j].index;
				}
			}
			for(j=0;j<map[0].length;j++){
				map[0][j]= 0;
				nodelist[0][j].index= -1;
			}
		}
		//消除可消除的方块
		function delBox(){
			var i,j,count;
			for(i=pointBox.y;i<(pointBox.y+4);i++){
				if(i<0||i>=map.length)
					continue;
				for(j=0;j<map[0].length;j++){
					if(map[i][j]==0){
						break;
					}
					if(j==map[0].length-1){
						moveLine(i);
						count++;
					}
				}
			}
		}
		//游戏结束
		function gameOver(){
			backLayer.die();
			var over = new LTextField();
			over.color ="red";
			over.size = 40;
			over.text = "Game Over";
			over.x =(LGlobal.width - over.getWidth())*0.5;
			over.y =200;
			backLayer.addChild(over);
		}

<commit_msg>初始化预览层<commit_after>		//初始化引擎
		init(30,"mylegend",320,480,main,LEvent.INIT);
		//进度条显示层，背景层，方块绘制层，预览层
		var loadingLayer,backLayer,graphicsLayer,nextLayer;
		//存放图片对象的属性
		var imglist = {};
		//图片数据
		var imgData = new Array(
			{name:"backImage",path:"./image/backImage.png"},
			{name:"block1",path:"./image/block1.png"},
			{name:"block2",path:"./image/block2.png"},
			{name:"block3",path:"./image/block3.png"},
			{name:"block4",path:"./image/block4.png"}
			);
		//用于生成方块
		var box;
		//方块坐标数组初始化
		var map;
		var nodelist;
		var bitmapdataList;
		//方块区域起始位置
		var START_X1=15,START_Y1=20,START_X2=228,START_Y2=65;
		//预览方块和当前方块
		var nextBox,nowBox;
		var pointBox ={x:0,y:0};
		var speed=15,speedIndex=0,speedMax=15;
		var point=0,pointText;
		//消除层数相关
		var del=0,delText;
		//控制单元
		var myKey = {
			keyControl:null,
			step:1,
			stepindex:0,
			isTouchDown:false,
			touchX:0,
			touchY:0,
			touchMove:false
		};
		//main函数
		function main(){
			map =[
				[0,0,0,0,0,0,0,0,0,0],
				[0,0,0,0,0,0,0,0,0,0],
				[0,0,0,0,0,0,0,0,0,0],
				[0,0,0,0,0,0,0,0,0,0],
				[0,0,0,0,0,0,0,0,0,0],
				[0,0,0,0,0,0,0,0,0,0],
				[0,0,0,0,0,0,0,0,0,0],
				[0,0,0,0,0,0,0,0,0,0],
				[0,0,0,0,0,0,0,0,0,0],
				[0,0,0,0,0,0,0,0,0,0],
				[0,0,0,0,0,0,0,0,0,0],
				[0,0,0,0,0,0,0,0,0,0],
				[0,0,0,0,0,0,0,0,0,0],
				[0,0,0,0,0,0,0,0,0,0],
				[0,0,0,0,0,0,0,0,0,0],
				[0,0,0,0,0,0,0,0,0,0],
				[0,0,0,0,0,0,0,0,0,0],
				[0,0,0,0,0,0,0,0,0,0],
				[0,0,0,0,0,0,0,0,0,0],
				[0,0,0,0,0,0,0,0,0,0]
			];
			box = new Box();
			//背景层初始化
			backLayer = new LSprite();
			//在背景层描绘背景
			backLayer.graphics.drawRect(2,"brown",[0,0,350,480],true,"black");
			addChild(backLayer);
			//进度条显示层初始化
			loadingLayer = new LoadingSample1();
			backLayer.addChild(loadingLayer);
			//利用LLoadManage类：进度条的读取与显示
			LLoadManage.load(
				imgData,
				function(progress){
					loadingLayer.setProgress(progress);
			    },
			    function(result){
			    	imglist = result;
					backLayer.removeChild(loadingLayer);
					loadingLayer= null;
					gameInit();
			    }
			);
			//gameInit();
		}
		//游戏标题画面初始化
		function gameInit(){
			//显示游戏标题
			var title = new LTextField();
			title.x = 100;
			title.y = 100;
			title.text = "俄罗斯方块";
			title.size = 30;
			title.color ="white";
			backLayer.addChild(title);
			//提示信息
			backLayer.graphics.drawRect(1,"white",[50,250,250,30]);
			var infoText = new LTextField();
			infoText.x = 75;
			infoText.y = 250;
			infoText.size = 25;
			infoText.text = "点击页面开始游戏";
			infoText.color = "white";
			backLayer.addChild(infoText);
			//添加鼠标点击事件侦听
			infoText.addEventListener(LMouseEvent.MOUSE_UP,gameStart);
		}
		//游戏画面初始化
		function gameStart(event){
			//背景层清空
			backLayer.die();
			backLayer.removeAllChild();
			var bitmap = new LBitmap(new LBitmapData(imglist["backImage"]));
			backLayer.addChild(bitmap);
			//预览层初始化
			nextLayer = new LSprite();
			backLayer.addChild(nextLayer);
			bitmapdataList = [
				new LBitmapData(imglist["block1"]),
				new LBitmapData(imglist["block2"]),
				new LBitmapData(imglist["block3"]),
				new LBitmapData(imglist["block4"])
			];
			//获得新方块
			getNewBox();
			//在屏幕上添加方块
			addBox();
			//添加循环播放事件
			backLayer.addEventListener(LEvent.ENTER_FRAME, onframe);
			//添加键盘事件用于控制方块移动
			LEvent.addEventListener(LGlobal.window,LKeyboardEvent.KEY_DOWN,onkeydown);
			LEvent.addEventListener(LGlobal.window,LKeyboardEvent.KEY_UP,onkeyup);
		}
		//键盘按下事件
		function onkeydown(event){
			if(myKey.keyControl != null){
				return;
			}
			if(event.keyCode == 37){
				//left
				myKey.keyControl = "left";
			}else if(event.keyCode == 38){
				//up
				myKey.keyControl = "up";
			}else if(event.keyCode == 39){
				//right
				myKey.keyControl = "right";
			}else if(event.keyCode == 40){
				//down
				myKey.keyControl = "down";
			}
		}
		//键盘弹起事件
		function onkeyup(event){
			//弹起后myKey属性恢复默认
			myKey.keyControl = null;
			myKey.stepindex = 0;
		}
		//循环实现方块下落
		function onframe(){
			//首先移除当前下落的方块
			removeBox();
			if(myKey.keyControl != null && myKey.stepindex-- < 0){
				myKey.stepindex = myKey.step;
				switch(myKey.keyControl){
					case "left":
						if(checkBox(-1,0)){
							pointBox.x-=1;
						}
						break;
					case "right":
						if(checkBox(1,0)){
							pointBox.x+=1;
						}
						break;
					case "down":
						if(checkBox(0,1)){
							pointBox.y+=1;
						}
						break;
					case "up":
						changeBox();
						break;
				}
			}
			if(speedIndex++ > speed){
				speedIndex = 0;
				if(checkBox(0,1)){
					pointBox.y++;
				}else{
					//无法下移
					addBox();
					if(pointBox.y<0){
						gameOver();
						return;
					}
					delBox();
					getNewBox();
				}
			}
			addBox();
			drawMap();
		}
		//方块变形
		function changeBox(){
			var saveBox = nowBox;
			nowBox =[
				[0,0,0,0],
				[0,0,0,0],
				[0,0,0,0],
				[0,0,0,0]
			];
			var i,j;
			for(i=0;i<saveBox.length;i++){
				for(j=0;j<saveBox[0].length;j++){
					nowBox[i][j] = saveBox[3-j][i];
				}
			}
			if (!checkBox(0,0)){
				nowBox = saveBox;
			}
		}
		//绘制所有的方块
		function drawMap(){
			var i,j;
			for(i=0;i<map.length;i++){
				for(j=0;j<map[0].length;j++){
					if(nodelist[i][j]["index"] >=0){
						nodelist[i][j]["bitmap"].bitmapData =bitmapdataList[nodelist[i][j]["index"]];
					}else{
						nodelist[i][j]["bitmap"].bitmapData = null;
					}
				}
			}
		}
		//判断是否可移动
		function checkBox(nx,ny){
			var i,j;
			if(pointBox.y < 0){
				//防止方块下落之前，就已向左或向右移到屏幕之外
				if(pointBox.x + nx < 0 || pointBox.x + nx > map[0].length - 4){
					return false;
				}
			}
			//遍历nowBox数组
			for(i=0;i<nowBox.length;i++){
				for(j=0;j<nowBox[0].length;j++){
					//判断方块网格是否进入map
					if(i+pointBox.y+ny<0){
						continue;
					}else if(i+pointBox.y+ny>=map.length||j+pointBox.x+nx>=map[0].length||j+pointBox.x+nx<0){
						//超出网格范围时
						if(nowBox[i][j] ==0){
							continue;
						}else{
							return false;
						}
					}
					if(nowBox[i][j] > 0 && map[i+pointBox.y+ny][j+pointBox.x+nx]>0){
						return false;
					}
				}
			}
			return true;
		}
		//移除方块
		function removeBox(){
			var i,j;
			for(i=0;i<nowBox.length;i++){
				for(j=0;j<nowBox[0].length;j++){
					if(i+pointBox.y<0||i+pointBox.y>=map.length||j+pointBox.x<0||j+pointBox.x>=map[0].length){
						continue;
					}
					map[i+pointBox.y][j+pointBox.x]=map[i+pointBox.y][j+pointBox.x]-nowBox[i][j];
					nodelist[i+pointBox.y][j+pointBox.x]["index"] = map[i+pointBox.y][j+pointBox.x] -1;
				}
			}
		}
		//将当前方块添加至游戏界面
		function addBox(){
			var i,j;
			for(i=0;i<nowBox.length;i++){
				for(j=0;j<nowBox[0].length;j++){
					if(i+pointBox.y<0||i+pointBox.y>=map.length||j+pointBox.x<0||j+pointBox.x>=map[i].length){
						continue;
					}
					map[i+pointBox.y][j+pointBox.x]=nowBox[i][j]+map[i+pointBox.y][j+pointBox.x];
					nodelist[i+pointBox.y][j+pointBox.x]["index"] = map[i+pointBox.y][j+pointBox.x] -1;
				}
			}
		}
		//获得新方块
		function getNewBox(){
			if(nextBox ==null){
				nextBox = box.getBox();
			}
			nowBox = nextBox;
			//当前下落方块的坐标
			pointBox.x=3;
			pointBox.y=-4;
			nextBox = box.getBox();
			nextLayer.removeAllChild();
			//将nextBox显示在预览层
			var i,j,bitmap;
			for(i=0;i<nextBox.length;i++){
				for(j=0;j<nextBox[0].length;j++){
					if(nextBox[i][j]===0){
						continue;
					}
					bitmap =new LBitmap(bitmapdataList[nextBox[i][j]-1]);
					bitmap.x= bitmap.getWidth()*j+START_X2;
					bitmap.y= bitmap.getHeight()*i+START_Y2;
					nextLayer.addChild(bitmap);
				}
			}
		}
		//消除整行方块
		function moveLine(line){
			var i;
			for(i = line;i>1;i--){
				for(j = 0; j<map[0].length; j++){
					map[i][j] = map[i-1][j];
					nodelist[i][j].index = nodelist[i-1][j].index;
				}
			}
			for(j=0;j<map[0].length;j++){
				map[0][j]= 0;
				nodelist[0][j].index= -1;
			}
		}
		//消除可消除的方块
		function delBox(){
			var i,j,count;
			for(i=pointBox.y;i<(pointBox.y+4);i++){
				if(i<0||i>=map.length)
					continue;
				for(j=0;j<map[0].length;j++){
					if(map[i][j]==0){
						break;
					}
					if(j==map[0].length-1){
						moveLine(i);
						count++;
					}
				}
			}
		}
		//游戏结束
		function gameOver(){
			backLayer.die();
			var over = new LTextField();
			over.color ="red";
			over.size = 40;
			over.text = "Game Over";
			over.x =(LGlobal.width - over.getWidth())*0.5;
			over.y =200;
			backLayer.addChild(over);
		}

<|endoftext|>


<commit_before>
/* Game namespace */
var game = {

	// an object where to store game information
	data : {
		//adding variables that we need now and for the future
		//assigning values to these variables
		score : 0,
		option1: "",
		option2: "",
		enemyBaseHealth: 1,
		playerBaseHealth: 1,
		enemyCreepHealth: 10,
		playerHealth: 10,
		enemyCreepAttack: 1,
		playerAttack: 5,
		//orcBaseDamage: 10,
		//orcBaseHealth: 100,
		//orcBaseSpeed: 3,
		//orcBaseDefense: 0,
		gloopHealth: 5,
		gloopAttack: 5,
		gloopAttackTimer: 1000,
		gloopMoveSpeed: 5,
		playerAttackTimer: 1000,
		enemyCreepAttackTimer: 1000,
		playerMoveSpeed: 5,
		creepMoveSpeed: 5,
		gameTimeManager: "",
		heroDeathManager: "",
		spearTimer: 15,
		player: "",
		exp: 0,
		gold: 0,
		ability1: 0,
		ability2: 0,
		ability3: 0,
		skill1: 0,
		skill2: 0,
		skill3: 0,
		exp1: 0,
		exp2: 0,
		exp3: 0,
		exp4: 0,
		win: "",
		pausePos: "",
		buyscreen: "",
		buytext: "",
		minmap: "",
		miniPlayer: "",
		pause: ""
	},

	// Run on page load.
	"onload" : function () {
	// Initialize the video.
	//changes and sets width and height of screen
	if (!me.video.init("screen",  me.video.CANVAS, 1067, 600, true, '1.0')) {
		alert("Your browser does not support HTML5 canvas.");
		return;
	}

	// add "#debug" to the URL to enable the debug Panel
	if (document.location.hash === "#debug") {
		window.onReady(function () {
			me.plugin.register.defer(this, debugPanel, "debug");
		});
	}

	//sets SPENDEXP screen with a random value of 112
	me.state.SPENDEXP = 112;

	me.state.LOAD = 113;
	me.state.NEW = 114;
	me.state.PAUSE = 115;

	// Initialize the audio.
	me.audio.init("mp3,ogg");

	// Set a callback to run when loading is complete.
	me.loader.onload = this.loaded.bind(this);

	// Load the resources.
	me.loader.preload(game.resources);

	// Initialize melonJS and display a loading screen.
	me.state.change(me.state.LOADING);
},

	// Run on game resources loaded.
	"loaded" : function () {
		//adding player to pool of objects that you can use
		//true says you can make multiple instances of the player
		me.pool.register("player", game.PlayerEntity, true);

		//registering both bases (show up on screen)
		me.pool.register("PlayerBase", game.PlayerBaseEntity);
		me.pool.register("EnemyBase", game.EnemyBaseEntity);
		//registering EnemyCreep class
		me.pool.register("EnemyCreep", game.EnemyCreep, true);

		me.pool.register("Gloop", game.Gloop, true);
		//registering GameManager class, dont need to set to true cuz only one of them
		me.pool.register("GameTimerManager", game.GameTimerManager);
		//registering HeroDeathManager class
		me.pool.register("HeroDeathManager", game.HeroDeathManager);
		//registering ExperienceManager class
		me.pool.register("ExperienceManager", game.ExperienceManager);
		//registering SpendGold class
		me.pool.register("SpendGold", game.SpendGold);
		//registering spear class
		me.pool.register("spear", game.SpearThrow);
		//registering minmap class
		me.pool.register("MinMap", game.MinMap, true);
		me.pool.register("miniplayer", game.MiniPlayerLocation, true);

		me.state.set(me.state.MENU, new game.TitleScreen());
		me.state.set(me.state.PLAY, new game.PlayScreen());
		//new SPENDEXP file
		me.state.set(me.state.SPENDEXP, new game.SpendExp());
		//new LoadProfle file
		me.state.set(me.state.LOAD, new game.LoadProfile());
		//new NewProfile file
		me.state.set(me.state.NEW, new game.NewProfile());

		me.state.set(me.state.PAUSE, new game.pause());

		// Start the game.
		//when game first starts...goes to title screen
		me.state.change(me.state.MENU);
	}
};
<commit_msg>changed creep health...Gloop works completely<commit_after>
/* Game namespace */
var game = {

	// an object where to store game information
	data : {
		//adding variables that we need now and for the future
		//assigning values to these variables
		score : 0,
		option1: "",
		option2: "",
		enemyBaseHealth: 1,
		playerBaseHealth: 1,
		enemyCreepHealth: 1,
		playerHealth: 10,
		enemyCreepAttack: 1,
		playerAttack: 5,
		//orcBaseDamage: 10,
		//orcBaseHealth: 100,
		//orcBaseSpeed: 3,
		//orcBaseDefense: 0,
		gloopHealth: 5,
		gloopAttack: 5,
		gloopAttackTimer: 1000,
		gloopMoveSpeed: 5,
		playerAttackTimer: 1000,
		enemyCreepAttackTimer: 1000,
		playerMoveSpeed: 5,
		creepMoveSpeed: 5,
		gameTimeManager: "",
		heroDeathManager: "",
		spearTimer: 15,
		player: "",
		exp: 0,
		gold: 0,
		ability1: 0,
		ability2: 0,
		ability3: 0,
		skill1: 0,
		skill2: 0,
		skill3: 0,
		exp1: 0,
		exp2: 0,
		exp3: 0,
		exp4: 0,
		win: "",
		pausePos: "",
		buyscreen: "",
		buytext: "",
		minmap: "",
		miniPlayer: "",
		pause: ""
	},

	// Run on page load.
	"onload" : function () {
	// Initialize the video.
	//changes and sets width and height of screen
	if (!me.video.init("screen",  me.video.CANVAS, 1067, 600, true, '1.0')) {
		alert("Your browser does not support HTML5 canvas.");
		return;
	}

	// add "#debug" to the URL to enable the debug Panel
	if (document.location.hash === "#debug") {
		window.onReady(function () {
			me.plugin.register.defer(this, debugPanel, "debug");
		});
	}

	//sets SPENDEXP screen with a random value of 112
	me.state.SPENDEXP = 112;

	me.state.LOAD = 113;
	me.state.NEW = 114;
	me.state.PAUSE = 115;

	// Initialize the audio.
	me.audio.init("mp3,ogg");

	// Set a callback to run when loading is complete.
	me.loader.onload = this.loaded.bind(this);

	// Load the resources.
	me.loader.preload(game.resources);

	// Initialize melonJS and display a loading screen.
	me.state.change(me.state.LOADING);
},

	// Run on game resources loaded.
	"loaded" : function () {
		//adding player to pool of objects that you can use
		//true says you can make multiple instances of the player
		me.pool.register("player", game.PlayerEntity, true);

		//registering both bases (show up on screen)
		me.pool.register("PlayerBase", game.PlayerBaseEntity);
		me.pool.register("EnemyBase", game.EnemyBaseEntity);
		//registering EnemyCreep class
		me.pool.register("EnemyCreep", game.EnemyCreep, true);

		me.pool.register("Gloop", game.Gloop, true);
		//registering GameManager class, dont need to set to true cuz only one of them
		me.pool.register("GameTimerManager", game.GameTimerManager);
		//registering HeroDeathManager class
		me.pool.register("HeroDeathManager", game.HeroDeathManager);
		//registering ExperienceManager class
		me.pool.register("ExperienceManager", game.ExperienceManager);
		//registering SpendGold class
		me.pool.register("SpendGold", game.SpendGold);
		//registering spear class
		me.pool.register("spear", game.SpearThrow);
		//registering minmap class
		me.pool.register("MinMap", game.MinMap, true);
		me.pool.register("miniplayer", game.MiniPlayerLocation, true);

		me.state.set(me.state.MENU, new game.TitleScreen());
		me.state.set(me.state.PLAY, new game.PlayScreen());
		//new SPENDEXP file
		me.state.set(me.state.SPENDEXP, new game.SpendExp());
		//new LoadProfle file
		me.state.set(me.state.LOAD, new game.LoadProfile());
		//new NewProfile file
		me.state.set(me.state.NEW, new game.NewProfile());

		me.state.set(me.state.PAUSE, new game.pause());

		// Start the game.
		//when game first starts...goes to title screen
		me.state.change(me.state.MENU);
	}
};
<|endoftext|>


<commit_before>var Alexa = require('alexa-sdk');
#var http = require('http');
#var calDates = require("./cal-dates");

// global variables for reference
var alexa;  // alexa SDK
var APP_ID = undefined;
var skillName = "Seattle Public Schools Calendar";

// Various messages based on intents/events
var welcomeMsg = "You can ask if SPS is in session today. Search for school holidays by date";
var helpMsg = "Here are some things you can say: Is school in session today? Is there school on the 19th of March?";
var helpDescpMsg = "Here are some things you can say: Is there school today";
var noDataMsg = "There is no information found for that date. Would you like to search again?";
var shutdownMsg = "Okay see you later";

// Output for Alexa
var output = "":

// TODO create handler functions

exports.handler = function(event, context, callback) {
  alexa = Alexa.handler(event, context);
  alexa.appId = APP_ID;
  //alexa.registerHandlers(handlers); TODO create handlers
  alexa.execute();
};
<commit_msg>Created various utility functions for dates<commit_after>var Alexa = require('alexa-sdk');
#var http = require('http');
#var calDates = require("./cal-dates");

// global variables for reference
var alexa;  // alexa SDK
var APP_ID = undefined;
var skillName = "Seattle Public Schools Calendar";

// Various messages based on intents/events
var welcomeMsg = "You can ask if SPS is in session today. Search for school holidays by date";
var helpMsg = "Here are some things you can say: Is school in session today? Is there school on the 19th of March?";
var helpDescpMsg = "Here are some things you can say: Is there school today";
var noDataMsg = "There is no information found for that date. Would you like to search again?";
var shutdownMsg = "Okay see you later";

// Output for Alexa
var output = "":

// TODO create handler functions

// Checks if string is empty, null, undefined or blank
function isEmpty(str) {
  return (!str || 0 === str.length || /^\s*$/.test(str));
}

// Converts ISO to CCYYMMDD, which is calendar event key in hashmap
function iso2key(isoDate) {
  var key = '';

  if (isEmpty(isoDate)) {
    return key;
  }

  var date = new Date(isoDate);
  if (isNaN(date) {
    return key;
  }

  key = date.toISOString().substring(0, 10).replace(/-/g, '');
  return key;
}

// Gets the current date and returns object of {iso: string date, key: iso hashmap key}
function getToday() {
  var isoDate = new Date().toISOString();

  var today = {
    iso: isoDate,
    key: iso2key(isoDate)
  };

  return today;
}

// Converts an ISO date to date object for
function iso2obj(isoDate) {
  if (isEmpty(isoDate) {
    return undefined;
  }

  var d = new Date(isoDate);

  var obj = {
    day: fd,
    date: 23,
    month: kj,
    year: kj,
  };

  return obj
}

function getOrdinal(num) {
  if (isNaN(num)) {
    return '';
  }

  num = Math.abs(num);

  if (num > 3 && num < 21) {
    return 'th';
  }

  switch (num % 10) {
    case 1: return 'st';
    case 2: return 'nd';
    case 3: return 'rd';
    default: return 'th';
  }
}

function isoObj2String(isoObj) {
  if (isoObj === undefined) {
    return '';
  }
  return isoObj.day + " the " + isoObj.date + getOrdinal(isoObj.date) + " of " + isoObj.month + " " + isoObj.year;
}

exports.handler = function(event, context, callback) {
  alexa = Alexa.handler(event, context);
  alexa.appId = APP_ID;
  //alexa.registerHandlers(handlers); TODO create handlers
  alexa.execute();
};

<|endoftext|>


<commit_before>import Proto from 'uberproto';
import errors from 'feathers-errors';
import filter from 'feathers-query-filters';
import * as msgs from './msgs';
import * as utils from './utils';

// import makeDebug from 'debug';
// const debug = makeDebug('feathers-couchdb-nano');

const DEFAULT_LIMIT = 100;
const DEFAULT_SKIP = 0;

class Service {
  constructor (options = {}) {
    if (!options.connection || !options.connection.use) {
      throw new Error(msgs.NANO_INSTANCE_REQUIRED);
    }

    if (!options.db) {
      throw new Error(msgs.DB_NAME_REQUIRED);
    }

    if (!options.name) {
      throw new Error(msgs.DOC_NAME_REQUIRED);
    }

    this.nano = options.connection;
    this.db = this.nano.use(options.db);
    this.events = options.events || [];
    this.paginate = options.paginate || {};
    this.docType = options.name.toString().toLowerCase();
    this.idField = options.id || '_id';
    this.includeDocs = !!(options.includeDocs || false);
  }

  extend (obj) {
    return Proto.extend(obj, this);
  }

  find (params = {}) {
    const paginate = params.paginate || this.paginate;
    const result = this._find(params, where => filter(where, paginate));

    return result
      .then(page => {
        if (paginate.default) {
          return page;
        }

        return page.data;
      })
      .catch(utils.errorHandler);
  }

  get (id, params) {
    return this._get(id)
      .then(data => this._toFeathersFormat(data))
      .catch(utils.errorHandler);
  }

  create (data, params) {
    return this._getUuid()
      .then(uuid => this._addDocId(data, uuid))
      .then(data => this._insert(this._toCouchFormat(data)))
      .catch(utils.errorHandler);
  }

  patch (id, data, params) {
    const rev = data._rev;

    if (!id) {
      return Promise.reject(new errors.BadRequest(msgs.DOC_ID_REQUIRED));
    }

    if (!rev) {
      return Promise.reject(new errors.BadRequest(msgs.DOC_REV_REQUIRED));
    }

    return this._insert(this._toCouchFormat(data))
      .catch(utils.errorHandler);
  }

  update (id, data, params) {
    if (!Array.isArray(data)) {
      return Promise.reject(new errors.BadRequest(msgs.UPDATE_ARRAY_REQUIRED));
    }
  }

  remove (id, params) {
    return this._get(id)
      .then(data => this._remove(data))
      .catch(utils.errorHandler);
  }

  setup (app, path) {}

  /////////////////////
  // Internal methods

  _find (params, getFilter = filter) {
    const { filters, query } = getFilter(params.query || {});
    const [design, view] = utils.getViewFromQuery(query.q);

    const options = {
      include_docs: query.include_docs || this.includeDocs,
      limit: filters.$limit || (query.paginate || {}).default || DEFAULT_LIMIT,
      skip: filters.$skip || DEFAULT_SKIP
    };

    return new Promise((resolve, reject) => {
      const callback = (err, body) => {
        const rows = body && body.rows;
        let data = [];

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

        for (let i = 0, n = rows.length; i < n; i++) {
          data[i] = this._toFeathersFormat(rows[i]);
        }

        resolve({
          data,
          limit: options.limit,
          skip: body.offset,
          total: data.length
        });
      };

      // Use design doc.
      if (design && view) {
        return this.db.view(design, view, options, callback);
      }

      options.startkey = this.docType;

      return this.db.list(options, callback);
    });
  }

  _get (id, params) {
    return new Promise((resolve, reject) => {
      return this.db.get(id, (err, body) => {
        if (err) {
          return reject(err);
        }

        resolve(body);
      });
    });
  }

  _insert (data) {
    return new Promise((resolve, reject) => {
      return this.db.insert(data, (err, body) => {
        if (err) {
          return reject(err);
        }

        resolve(body);
      });
    });
  }

  _remove (data, params) {
    const id = data._id;
    const rev = data._rev;

    return new Promise((resolve, reject) => {
      if (!id) {
        return reject(new errors.BadRequest(msgs.DOC_ID_REQUIRED));
      }

      if (!rev) {
        return reject(new errors.BadRequest(msgs.DOC_REV_REQUIRED));
      }

      return this.db.destroy(id, rev, (err, body) => {
        if (err) {
          return reject(err);
        }

        resolve(body);
      });
    });
  }

  /////////////////////
  // Instance helpers

  // Construct doc id for doc filtering and type determination.
  _addDocId (data, uuid) {
    data._id = `${this.docType}-${uuid}`;

    return Promise.resolve(data);
  }

  // Generate and return single doc uuid.
  _getUuid () {
    return Promise.resolve(this._uuids().then(ids => ids[0]));
  }

  // Format data for Feathers.
  _toFeathersFormat (item) {
    const obj = item.doc || item.value || (utils.isPlainObject(item.key) && item.key) || item;
    let data = Object.assign({}, obj.data || obj);

    data._rev = obj._rev;
    data[this.idField] = item._id || item.id;

    return data;
  }

  // Format data for CouchDB.
  _toCouchFormat (item) {
    const id = item[this.idField] || item._id || item.id;
    let data = Object.assign({}, item);

    delete data.id;
    delete data._id;

    return { data, _id: id, _rev: item._rev };
  }

  // Get one or more CouchDB uuids.
  //
  // Note: Included in future versions nano library.
  // https://github.com/apache/couchdb-nano/blob/master/lib/nano.js#L366
  _uuids (count = 1) {
    const nano = this.nano;

    return new Promise((resolve, reject) => {
      const callback = (err, body) => {
        if (err) {
          return reject(err);
        }

        resolve(body.uuids);
      };

      nano.relax({
        method: 'GET',
        path: '_uuids',
        qs: { count: count }
      }, callback);
    });
  }
}

export default function init (options) {
  return new Service(options);
}

init.Service = Service;
<commit_msg>Refactor to use ES6 destructuring.<commit_after>import Proto from 'uberproto';
import errors from 'feathers-errors';
import filter from 'feathers-query-filters';
import * as msgs from './msgs';
import * as utils from './utils';

// import makeDebug from 'debug';
// const debug = makeDebug('feathers-couchdb-nano');

const DEFAULT_LIMIT = 100;
const DEFAULT_SKIP = 0;

class Service {
  constructor ({ connection, db, name, id = '_id', paginate = {}, events = [], includeDocs = false } = {}) {
    if (!connection || !connection.use) {
      throw new Error(msgs.NANO_INSTANCE_REQUIRED);
    }

    if (!db) {
      throw new Error(msgs.DB_NAME_REQUIRED);
    }

    if (!name) {
      throw new Error(msgs.DOC_NAME_REQUIRED);
    }

    this.nano = connection;
    this.db = this.nano.use(db);
    this.events = events;
    this.paginate = paginate;
    this.docType = name.toString().toLowerCase();
    this.idField = id;
    this.includeDocs = !!(includeDocs);
  }

  extend (obj) {
    return Proto.extend(obj, this);
  }

  find (params = {}) {
    const paginate = params.paginate || this.paginate;
    const result = this._find(params, where => filter(where, paginate));

    return result
      .then(page => {
        if (paginate.default) {
          return page;
        }

        return page.data;
      })
      .catch(utils.errorHandler);
  }

  get (id, params) {
    return this._get(id)
      .then(data => this._toFeathersFormat(data))
      .catch(utils.errorHandler);
  }

  create (data, params) {
    return this._getUuid()
      .then(uuid => this._addDocId(data, uuid))
      .then(data => this._insert(this._toCouchFormat(data)))
      .catch(utils.errorHandler);
  }

  patch (id, data, params) {
    const rev = data._rev;

    if (!id) {
      return Promise.reject(new errors.BadRequest(msgs.DOC_ID_REQUIRED));
    }

    if (!rev) {
      return Promise.reject(new errors.BadRequest(msgs.DOC_REV_REQUIRED));
    }

    return this._insert(this._toCouchFormat(data))
      .catch(utils.errorHandler);
  }

  update (id, data, params) {
    if (!Array.isArray(data)) {
      return Promise.reject(new errors.BadRequest(msgs.UPDATE_ARRAY_REQUIRED));
    }
  }

  remove (id, params) {
    return this._get(id)
      .then(data => this._remove(data))
      .catch(utils.errorHandler);
  }

  setup (app, path) {}

  /// //////////////////
  // Internal methods

  _find (params, getFilter = filter) {
    const { filters, query } = getFilter(params.query || {});
    const [design, view] = utils.getViewFromQuery(query.q);

    const options = {
      include_docs: query.include_docs || this.includeDocs,
      limit: filters.$limit || (query.paginate || {}).default || DEFAULT_LIMIT,
      skip: filters.$skip || DEFAULT_SKIP
    };

    return new Promise((resolve, reject) => {
      const callback = (err, body) => {
        const rows = body && body.rows;
        let data = [];

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

        for (let i = 0, n = rows.length; i < n; i++) {
          data[i] = this._toFeathersFormat(rows[i]);
        }

        resolve({
          data,
          limit: options.limit,
          skip: body.offset,
          total: data.length
        });
      };

      // Use design doc.
      if (design && view) {
        return this.db.view(design, view, options, callback);
      }

      options.startkey = this.docType;

      return this.db.list(options, callback);
    });
  }

  _get (id, params) {
    return new Promise((resolve, reject) => {
      return this.db.get(id, (err, body) => {
        if (err) {
          return reject(err);
        }

        resolve(body);
      });
    });
  }

  _insert (data) {
    return new Promise((resolve, reject) => {
      return this.db.insert(data, (err, body) => {
        if (err) {
          return reject(err);
        }

        resolve(body);
      });
    });
  }

  _remove (data, params) {
    const id = data._id;
    const rev = data._rev;

    return new Promise((resolve, reject) => {
      if (!id) {
        return reject(new errors.BadRequest(msgs.DOC_ID_REQUIRED));
      }

      if (!rev) {
        return reject(new errors.BadRequest(msgs.DOC_REV_REQUIRED));
      }

      return this.db.destroy(id, rev, (err, body) => {
        if (err) {
          return reject(err);
        }

        resolve(body);
      });
    });
  }

  /// //////////////////
  // Instance helpers

  // Construct doc id for doc filtering and type determination.
  _addDocId (data, uuid) {
    data._id = `${this.docType}-${uuid}`;

    return Promise.resolve(data);
  }

  // Generate and return single doc uuid.
  _getUuid () {
    return Promise.resolve(this._uuids().then(ids => ids[0]));
  }

  // Format data for Feathers.
  _toFeathersFormat (item) {
    const obj = item.doc || item.value || (utils.isPlainObject(item.key) && item.key) || item;
    let data = Object.assign({}, obj.data || obj);

    data._rev = obj._rev;
    data[this.idField] = item._id || item.id;

    return data;
  }

  // Format data for CouchDB.
  _toCouchFormat (item) {
    const id = item[this.idField] || item._id || item.id;
    let data = Object.assign({}, item);

    delete data.id;
    delete data._id;

    return { data, _id: id, _rev: item._rev };
  }

  // Get one or more CouchDB uuids.
  //
  // Note: Included in future versions nano library.
  // https://github.com/apache/couchdb-nano/blob/master/lib/nano.js#L366
  _uuids (count = 1) {
    const nano = this.nano;

    return new Promise((resolve, reject) => {
      const callback = (err, body) => {
        if (err) {
          return reject(err);
        }

        resolve(body.uuids);
      };

      nano.relax({
        method: 'GET',
        path: '_uuids',
        qs: { count: count }
      }, callback);
    });
  }
}

export default function init (options) {
  return new Service(options);
}

init.Service = Service;
<|endoftext|>


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

'use strict';

async function main(parent = 'projects/my-project') {
  // [START secretmanager_list_secrets]
  /**
   * TODO(developer): Uncomment these variables before running the sample.
   */
  // const parent = 'projects/my-project';

  // Imports the Secret Manager library
  const {SecretManagerServiceClient} = require('@google-cloud/secret-manager');

  // Instantiates a client
  const client = new SecretManagerServiceClient();

  async function listSecrets() {
    const [secrets] = await client.listSecrets({
      parent: parent,
    });

    secrets.forEach(secret => {
      const policy = secret.replication.replication;
      console.log(`${secret.name} (${policy})`);
    });
  }

  listSecrets();
  // [END secretmanager_list_secrets]
}

const args = process.argv.slice(2);
main(...args).catch(console.error);
<commit_msg>docs: update samples for correct types (#205)<commit_after>// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

'use strict';

async function main(parent = 'projects/my-project') {
  // [START secretmanager_list_secrets]
  /**
   * TODO(developer): Uncomment these variables before running the sample.
   */
  // const parent = 'projects/my-project';

  // Imports the Secret Manager library
  const {SecretManagerServiceClient} = require('@google-cloud/secret-manager');

  // Instantiates a client
  const client = new SecretManagerServiceClient();

  async function listSecrets() {
    const [secrets] = await client.listSecrets({
      parent: parent,
    });

    secrets.forEach(secret => {
      const policy = secret.replication.userManaged
        ? secret.replication.userManaged
        : secret.replication.automatic;
      console.log(`${secret.name} (${policy})`);
    });
  }

  listSecrets();
  // [END secretmanager_list_secrets]
}

const args = process.argv.slice(2);
main(...args).catch(console.error);
<|endoftext|>


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

module.exports = AABB;

/**
 * Axis aligned bounding box class.
 * @class AABB
 * @constructor
 * @param {Object} [options]
 * @param {Vec3}   [options.upperBound]
 * @param {Vec3}   [options.lowerBound]
 */
function AABB(options){
    options = options || {};

    /**
     * The lower bound of the bounding box.
     * @property lowerBound
     * @type {Array}
     */
    this.lowerBound = new Vec3();
    if(options.lowerBound){
        this.lowerBound.copy(options.lowerBound);
    }

    /**
     * The upper bound of the bounding box.
     * @property upperBound
     * @type {Array}
     */
    this.upperBound = new Vec3();
    if(options.upperBound){
        this.upperBound.copy(options.upperBound);
    }
}

var tmp = new Vec3();

/**
 * Set the AABB bounds from a set of points.
 * @method setFromPoints
 * @param {Array} points An array of Vec3's.
 * @param {Vec3} position
 * @param {Quaternion} quaternion
 * @param {number} skinSize
 * @return {AABB} The self object
 */
AABB.prototype.setFromPoints = function(points, position, quaternion, skinSize){
    var l = this.lowerBound,
        u = this.upperBound,
        q = quaternion;

    // Set to the first point
    l.copy(points[0]);
    if(q){
        q.vmult(l, l);
    }
    u.copy(l);

    for(var i = 1; i<points.length; i++){
        var p = points[i];

        if(q){
            q.vmult(p, tmp);
            p = tmp;
        }

        if(p.x > u.x){ u.x = p.x; }
        if(p.x < l.x){ l.x = p.x; }
        if(p.y > u.y){ u.y = p.y; }
        if(p.y < l.y){ l.y = p.y; }
        if(p.z > u.z){ u.z = p.z; }
        if(p.z < l.z){ l.z = p.z; }
    }

    // Add offset
    if (position) {
        position.vadd(l, l);
        position.vadd(u, u);
    }

    if(skinSize){
        l.x -= skinSize;
        l.y -= skinSize;
        l.z -= skinSize;
        u.x += skinSize;
        u.y += skinSize;
        u.z += skinSize;
    }

    return this;
};

/**
 * Copy bounds from an AABB to this AABB
 * @method copy
 * @param  {AABB} aabb Source to copy from
 */
AABB.prototype.copy = function(aabb){
    this.lowerBound.copy(aabb.lowerBound);
    this.upperBound.copy(aabb.upperBound);
};

/**
 * Extend this AABB so that it covers the given AABB too.
 * @method extend
 * @param  {AABB} aabb
 */
AABB.prototype.extend = function(aabb){
    // Extend lower bound
    var l = aabb.lowerBound.x;
    if(this.lowerBound.x > l){
        this.lowerBound.x = l;
    }

    // Upper
    var u = aabb.upperBound.x;
    if(this.upperBound.x < u){
        this.upperBound.x = u;
    }

    // Extend lower bound
    var l = aabb.lowerBound.y;
    if(this.lowerBound.y > l){
        this.lowerBound.y = l;
    }

    // Upper
    var u = aabb.upperBound.y;
    if(this.upperBound.y < u){
        this.upperBound.y = u;
    }

    // Extend lower bound
    var l = aabb.lowerBound.z;
    if(this.lowerBound.z > l){
        this.lowerBound.z = l;
    }

    // Upper
    var u = aabb.upperBound.z;
    if(this.upperBound.z < u){
        this.upperBound.z = u;
    }
};

/**
 * Returns true if the given AABB overlaps this AABB.
 * @method overlaps
 * @param  {AABB} aabb
 * @return {Boolean}
 */
AABB.prototype.overlaps = function(aabb){
    var l1 = this.lowerBound,
        u1 = this.upperBound,
        l2 = aabb.lowerBound,
        u2 = aabb.upperBound;

    //      l2        u2
    //      |---------|
    // |--------|
    // l1       u1

    return ((l2.x <= u1.x && u1.x <= u2.x) || (l1.x <= u2.x && u2.x <= u1.x)) &&
           ((l2.y <= u1.y && u1.y <= u2.y) || (l1.y <= u2.y && u2.y <= u1.y)) &&
           ((l2.z <= u1.z && u1.z <= u2.z) || (l1.z <= u2.z && u2.z <= u1.z));
};

AABB.prototype.getCorners = function(a, b, c, d, e, f, g, h){
    var l = this.lowerBound,
        u = this.upperBound;

    a.copy(l);
    b.set( u.x, l.y, l.z );
    c.set( u.x, u.y, l.z );
    d.set( l.x, u.y, u.z );
    e.set( u.x, l.y, l.z );
    f.set( l.x, u.y, l.z );
    g.set( l.x, l.y, u.z );
    h.copy(u);
};

var transformIntoFrame_corners = [
    new Vec3(),
    new Vec3(),
    new Vec3(),
    new Vec3(),
    new Vec3(),
    new Vec3(),
    new Vec3(),
    new Vec3()
];

/**
 * Get the representation of an AABB in another frame.
 * @method toLocalFrame
 * @param  {Transform} frame
 * @param  {AABB} target
 * @return {AABB} The "target" AABB object.
 */
AABB.prototype.toLocalFrame = function(frame, target){

    var corners = transformIntoFrame_corners;
    var a = corners[0];
    var b = corners[1];
    var c = corners[2];
    var d = corners[3];
    var e = corners[4];
    var f = corners[5];
    var g = corners[6];
    var h = corners[7];

    // Get corners in current frame
    this.getCorners(a, b, c, d, e, f, g, h);

    // Transform them to new local frame
    for(var i=0; i !== 8; i++){
        var corner = corners[i];
        frame.pointToLocal(corner, corner);
    }

    return target.setFromPoints(corners);
};

/**
 * Get the representation of an AABB in the global frame.
 * @method toWorldFrame
 * @param  {Transform} frame
 * @param  {AABB} target
 * @return {AABB} The "target" AABB object.
 */
AABB.prototype.toWorldFrame = function(frame, target){

    var corners = transformIntoFrame_corners;
    var a = corners[0];
    var b = corners[1];
    var c = corners[2];
    var d = corners[3];
    var e = corners[4];
    var f = corners[5];
    var g = corners[6];
    var h = corners[7];

    // Get corners in current frame
    this.getCorners(a, b, c, d, e, f, g, h);

    // Transform them to new local frame
    for(var i=0; i !== 8; i++){
        var corner = corners[i];
        frame.pointToWorld(corner, corner);
    }

    return target.setFromPoints(corners);
};
<commit_msg>Update AABB.js<commit_after>var Vec3 = require('../math/Vec3');
var Utils = require('../utils/Utils');

module.exports = AABB;

/**
 * Axis aligned bounding box class.
 * @class AABB
 * @constructor
 * @param {Object} [options]
 * @param {Vec3}   [options.upperBound]
 * @param {Vec3}   [options.lowerBound]
 */
function AABB(options){
    options = options || {};

    /**
     * The lower bound of the bounding box.
     * @property lowerBound
     * @type {Array}
     */
    this.lowerBound = new Vec3();
    if(options.lowerBound){
        this.lowerBound.copy(options.lowerBound);
    }

    /**
     * The upper bound of the bounding box.
     * @property upperBound
     * @type {Array}
     */
    this.upperBound = new Vec3();
    if(options.upperBound){
        this.upperBound.copy(options.upperBound);
    }
}

var tmp = new Vec3();

/**
 * Set the AABB bounds from a set of points.
 * @method setFromPoints
 * @param {Array} points An array of Vec3's.
 * @param {Vec3} position
 * @param {Quaternion} quaternion
 * @param {number} skinSize
 * @return {AABB} The self object
 */
AABB.prototype.setFromPoints = function(points, position, quaternion, skinSize){
    var l = this.lowerBound,
        u = this.upperBound,
        q = quaternion;

    // Set to the first point
    l.copy(points[0]);
    if(q){
        q.vmult(l, l);
    }
    u.copy(l);

    for(var i = 1; i<points.length; i++){
        var p = points[i];

        if(q){
            q.vmult(p, tmp);
            p = tmp;
        }

        if(p.x > u.x){ u.x = p.x; }
        if(p.x < l.x){ l.x = p.x; }
        if(p.y > u.y){ u.y = p.y; }
        if(p.y < l.y){ l.y = p.y; }
        if(p.z > u.z){ u.z = p.z; }
        if(p.z < l.z){ l.z = p.z; }
    }

    // Add offset
    if (position) {
        position.vadd(l, l);
        position.vadd(u, u);
    }

    if(skinSize){
        l.x -= skinSize;
        l.y -= skinSize;
        l.z -= skinSize;
        u.x += skinSize;
        u.y += skinSize;
        u.z += skinSize;
    }

    return this;
};

/**
 * Copy bounds from an AABB to this AABB
 * @method copy
 * @param  {AABB} aabb Source to copy from
 */
AABB.prototype.copy = function(aabb){
    this.lowerBound.copy(aabb.lowerBound);
    this.upperBound.copy(aabb.upperBound);
};

/**
 * Extend this AABB so that it covers the given AABB too.
 * @method extend
 * @param  {AABB} aabb
 */
AABB.prototype.extend = function(aabb){
    // Extend lower bound
    var l = aabb.lowerBound.x;
    if(this.lowerBound.x > l){
        this.lowerBound.x = l;
    }

    // Upper
    var u = aabb.upperBound.x;
    if(this.upperBound.x < u){
        this.upperBound.x = u;
    }

    // Extend lower bound
    var l = aabb.lowerBound.y;
    if(this.lowerBound.y > l){
        this.lowerBound.y = l;
    }

    // Upper
    var u = aabb.upperBound.y;
    if(this.upperBound.y < u){
        this.upperBound.y = u;
    }

    // Extend lower bound
    var l = aabb.lowerBound.z;
    if(this.lowerBound.z > l){
        this.lowerBound.z = l;
    }

    // Upper
    var u = aabb.upperBound.z;
    if(this.upperBound.z < u){
        this.upperBound.z = u;
    }
};

/**
 * Returns true if the given AABB overlaps this AABB.
 * @method overlaps
 * @param  {AABB} aabb
 * @return {Boolean}
 */
AABB.prototype.overlaps = function(aabb){
    var l1 = this.lowerBound,
        u1 = this.upperBound,
        l2 = aabb.lowerBound,
        u2 = aabb.upperBound;

    //      l2        u2
    //      |---------|
    // |--------|
    // l1       u1

    return ((l2.x <= u1.x && u1.x <= u2.x) || (l1.x <= u2.x && u2.x <= u1.x)) &&
           ((l2.y <= u1.y && u1.y <= u2.y) || (l1.y <= u2.y && u2.y <= u1.y)) &&
           ((l2.z <= u1.z && u1.z <= u2.z) || (l1.z <= u2.z && u2.z <= u1.z));
};

/**
 * @method getCorners
 * @param {Vec3} a
 * @param {Vec3} b
 * @param {Vec3} c
 * @param {Vec3} d
 * @param {Vec3} e
 * @param {Vec3} f
 * @param {Vec3} g
 * @param {Vec3} h
 */
AABB.prototype.getCorners = function(a, b, c, d, e, f, g, h){
    var l = this.lowerBound,
        u = this.upperBound;

    a.copy(l);
    b.set( u.x, l.y, l.z );
    c.set( u.x, u.y, l.z );
    d.set( l.x, u.y, u.z );
    e.set( u.x, l.y, l.z );
    f.set( l.x, u.y, l.z );
    g.set( l.x, l.y, u.z );
    h.copy(u);
};

var transformIntoFrame_corners = [
    new Vec3(),
    new Vec3(),
    new Vec3(),
    new Vec3(),
    new Vec3(),
    new Vec3(),
    new Vec3(),
    new Vec3()
];

/**
 * Get the representation of an AABB in another frame.
 * @method toLocalFrame
 * @param  {Transform} frame
 * @param  {AABB} target
 * @return {AABB} The "target" AABB object.
 */
AABB.prototype.toLocalFrame = function(frame, target){

    var corners = transformIntoFrame_corners;
    var a = corners[0];
    var b = corners[1];
    var c = corners[2];
    var d = corners[3];
    var e = corners[4];
    var f = corners[5];
    var g = corners[6];
    var h = corners[7];

    // Get corners in current frame
    this.getCorners(a, b, c, d, e, f, g, h);

    // Transform them to new local frame
    for(var i=0; i !== 8; i++){
        var corner = corners[i];
        frame.pointToLocal(corner, corner);
    }

    return target.setFromPoints(corners);
};

/**
 * Get the representation of an AABB in the global frame.
 * @method toWorldFrame
 * @param  {Transform} frame
 * @param  {AABB} target
 * @return {AABB} The "target" AABB object.
 */
AABB.prototype.toWorldFrame = function(frame, target){

    var corners = transformIntoFrame_corners;
    var a = corners[0];
    var b = corners[1];
    var c = corners[2];
    var d = corners[3];
    var e = corners[4];
    var f = corners[5];
    var g = corners[6];
    var h = corners[7];

    // Get corners in current frame
    this.getCorners(a, b, c, d, e, f, g, h);

    // Transform them to new local frame
    for(var i=0; i !== 8; i++){
        var corner = corners[i];
        frame.pointToWorld(corner, corner);
    }

    return target.setFromPoints(corners);
};
<|endoftext|>


<commit_before>/*global State */

function Grid(w, h, s) {
    this.w = w; this.h = h; this.s = s || 8;
    this.done = false;
    this.fore = new Uint32Array(w * h);
    this.back = new Uint32Array(w * h);
    for (var y = 0; y < h; y++) {
        for (var x = 0; x < w; x++) {
            if (y === 0 || x === 0 || y === h - 1 || x === w - 1) {
                this.set(x, y, State.WALL);
            } else {
                this.set(x, y, Math.random() < 0.2 ? State.WALL : State.OPEN);
            }
        }
    }
    this.set(1, 1, State.BEGIN);
    this.set(w - 2, h - 2, State.END);
    this.swap();
}

Grid.prototype.swap = function() {
    var tmp = this.fore;
    this.fore = this.back;
    this.back = tmp;
    return this;
};

Grid.prototype.get = function(x, y) {
    if (x < 0 || x >= this.w || y < 0 || y > this.h) {
        return State.WALL;
    } else {
        return this.fore[y * this.w + x];
    }
};

Grid.prototype.set = function(x, y, value) {
    this.back[y * this.w + x] = value;
    return value;
};

Grid.prototype.step = function(count) {
    count = count || 1;
    var states = [null, null, null, null];
    while (count-- > 0 && !this.done) {
        var changes = 0;
        for (var y = 0; y < this.h; y++) {
            for (var x = 0; x < this.w; x++) {
                states[0] = this.get(x + 0, y + -1); // N
                states[1] = this.get(x + 1, y +  0); // E
                states[2] = this.get(x + 0, y +  1); // S
                states[3] = this.get(x +-1, y +  0); // W
                var current = this.get(x, y),
                    next = State.next(current, states);
                if (current !== next) changes++;
                this.set(x, y, next);
            }
        }
        this.swap();
        if (changes === 0) this.done = true;
    }
    return this;
};

Grid.prototype.draw = function(canvas) {
    var w = this.w, h = this.h, s = this.s;
    var ctx = canvas.getContext('2d');
    ctx.fillStyle = 'purple';
    ctx.fillRect(0, 0, w * s, h * s); // debug
    for (var y = 0; y < this.h; y++) {
        for (var x = 0; x < this.w; x++) {
            ctx.fillStyle = State.color(this.get(x, y));
            ctx.fillRect(s * x, s * y, s, s);
        }
    }
    return this;
};

Grid.prototype.animate = function(canvas) {
    var _this = this;
    window.setTimeout(function() {
        if (!_this.done) {
            _this.step().draw(canvas);
        }
        _this.animate(canvas);
    }, 50);
    return this;
};
<commit_msg>Remove outer wall.<commit_after>/*global State */

function Grid(w, h, s) {
    this.w = w; this.h = h; this.s = s || 8;
    this.done = false;
    this.fore = new Uint32Array(w * h);
    this.back = new Uint32Array(w * h);
    for (var y = 0; y < h; y++) {
        for (var x = 0; x < w; x++) {
            this.set(x, y, Math.random() < 0.2 ? State.WALL : State.OPEN);
        }
    }
    this.set(0, 0, State.BEGIN);
    this.set(w - 1, h - 1, State.END);
    this.swap();
}

Grid.prototype.swap = function() {
    var tmp = this.fore;
    this.fore = this.back;
    this.back = tmp;
    return this;
};

Grid.prototype.get = function(x, y) {
    if (x < 0 || x >= this.w || y < 0 || y > this.h) {
        return State.WALL;
    } else {
        return this.fore[y * this.w + x];
    }
};

Grid.prototype.set = function(x, y, value) {
    this.back[y * this.w + x] = value;
    return value;
};

Grid.prototype.step = function(count) {
    count = count || 1;
    var states = [null, null, null, null];
    while (count-- > 0 && !this.done) {
        var changes = 0;
        for (var y = 0; y < this.h; y++) {
            for (var x = 0; x < this.w; x++) {
                states[0] = this.get(x + 0, y + -1); // N
                states[1] = this.get(x + 1, y +  0); // E
                states[2] = this.get(x + 0, y +  1); // S
                states[3] = this.get(x +-1, y +  0); // W
                var current = this.get(x, y),
                    next = State.next(current, states);
                if (current !== next) changes++;
                this.set(x, y, next);
            }
        }
        this.swap();
        if (changes === 0) this.done = true;
    }
    return this;
};

Grid.prototype.draw = function(canvas) {
    var w = this.w, h = this.h, s = this.s;
    var ctx = canvas.getContext('2d');
    ctx.fillStyle = 'purple';
    ctx.fillRect(0, 0, w * s, h * s); // debug
    for (var y = 0; y < this.h; y++) {
        for (var x = 0; x < this.w; x++) {
            ctx.fillStyle = State.color(this.get(x, y));
            ctx.fillRect(s * x, s * y, s, s);
        }
    }
    return this;
};

Grid.prototype.animate = function(canvas) {
    var _this = this;
    window.setTimeout(function() {
        if (!_this.done) {
            _this.step().draw(canvas);
        }
        _this.animate(canvas);
    }, 50);
    return this;
};
<|endoftext|>


<commit_before>export const rules = {
  'no-unresolved': require('./rules/no-unresolved')
, 'named': require('./rules/named')
, 'default': require('./rules/default')
, 'namespace': require('./rules/namespace')
, 'no-named-as-default': require('./rules/no-named-as-default')

, 'no-errors': require('./rules/no-errors')
, 'no-require': require('./rules/no-require')

, 'export': require('./rules/export')

, 'no-duplicates': require('./rules/no-duplicates')
, 'imports-first': require('./rules/imports-first')

  // removed
, 'no-reassign': function () { return {} }
  // should remove this undocumented alias
, 'exists': require('./rules/no-unresolved')
}

export const rulesConfig = {
  'no-unresolved': 2
, 'named': 2
, 'namespace': 2
, 'default': 2
, 'no-named-as-default': 2
, 'export': 2

  // warnings
, 'no-duplicates': 1

  // optional
, 'imports-first': 0
, 'no-errors': 0
, 'no-require': 0

  // removed
, 'no-reassign': 0
}
<commit_msg>removed legacy rule exports<commit_after>export const rules = {
  'no-unresolved': require('./rules/no-unresolved')
, 'named': require('./rules/named')
, 'default': require('./rules/default')
, 'namespace': require('./rules/namespace')
, 'no-named-as-default': require('./rules/no-named-as-default')

, 'no-errors': require('./rules/no-errors')
, 'no-require': require('./rules/no-require')

, 'export': require('./rules/export')

, 'no-duplicates': require('./rules/no-duplicates')
, 'imports-first': require('./rules/imports-first')
}

export const rulesConfig = {
  'no-unresolved': 2
, 'named': 2
, 'namespace': 2
, 'default': 2
, 'no-named-as-default': 2
, 'export': 2

  // warnings
, 'no-duplicates': 1

  // optional
, 'imports-first': 0
, 'no-errors': 0
, 'no-require': 0

  // removed
, 'no-reassign': 0
}
<|endoftext|>


<commit_before>// our modules
import {api, config} from '../utils';

export const certsCmd = async () => {
  const token = config.token;
  const task = 'certifications';

  const certsResponse = await api({token, task});
  const certs = certsResponse.body
    .filter(cert => cert.status === 'certified')
    .reduce((acc, cert) => {
      /* eslint-disable no-param-reassign */
      acc[cert.project.id] = {
        name: cert.project.name,
        price: cert.project.price,
      };
      return acc;
    }, {});
  config.save({certs}).then(() => process.exit(0));
};
<commit_msg>Fix certs.js<commit_after>// our modules
import {Config, Api} from '../utils';

const config = new Config();
const api = new Api(config.token);

export const certsCmd = async () => {
  const certifications = await api.call({task: 'certifications'});
  config.certs = certifications.body
    .filter(cert => cert.status === 'certified')
    .reduce((acc, cert) => {
      /* eslint-disable no-param-reassign */
      acc[cert.project.id] = {
        name: cert.project.name,
        price: cert.project.price,
      };
      return acc;
    }, {});
  config.save();
  console.log(`Certifications saved:\n${JSON.stringify(config.certs, null, 2)}`);
  process.exit(0);
};
<|endoftext|>


<commit_before>import 'scrollingelement';

const canUseDOM = !!(
  typeof window !== 'undefined' &&
  window.document &&
  window.document.createElement
);

class DisableScroll {
  constructor() {
    this.options = {
      disableWheel: true,
      disableScroll: true,
      disableKeys: true,
      keyboardKeys: [32, 33, 34, 35, 36, 37, 38, 39, 40],
      authorizedInInputs: [32, 37, 38, 39, 40]
      // space: 32, page up: 33, page down: 34, end: 35, home: 36
      // left: 37, up: 38, right: 39, down: 40
    };

    this.element = canUseDOM ? document.scrollingElement : null;
    this.lockToScrollPos = [0, 0];
  }

  /**
   * Disable Page Scroll
   * @external Node
   *
   * @param {HTMLElement} [element] - DOM Element, usually document.body
   * @param {object} [options] - Change the initial options
   */
  on(element, options) {
    if (!canUseDOM) return;

    this.element = element || this.element;
    this.options = {
      ...this.options,
      ...options,
    };

    const { disableKeys, disableScroll, disableWheel } = this.options;

    /* istanbul ignore else */
    if (disableWheel) {
      document.addEventListener('wheel', this.handleWheel);
      document.addEventListener('touchmove', this.handleWheel);
    }

    /* istanbul ignore else */
    if (disableScroll) {
      this.lockToScrollPos = [
        this.element.scrollLeft || this.element.scrollX,
        this.element.scrollTop || this.element.scrollY
      ];
      document.addEventListener('scroll', this.handleScroll);
    }

    /* istanbul ignore else */
    if (disableKeys) {
      document.addEventListener('keydown', this.handleKeydown);
    }
  }

  /**
   * Re-enable page scrolls
   */
  off() {
    if (!canUseDOM) return;

    document.removeEventListener('wheel', this.handleWheel);
    document.removeEventListener('touchmove', this.handleWheel);
    document.removeEventListener('scroll', this.handleScroll);
    document.removeEventListener('keydown', this.handleKeydown);
  }

  handleWheel = (e) => {
    e.preventDefault();
  };

  handleScroll = () => {
    window.scrollTo(...this.lockToScrollPos);
  };

  handleKeydown = (e) => {
    let keys = this.options.keyboardKeys;

    /* istanbul ignore else */
    if (['INPUT', 'TEXTAREA'].includes(e.target.tagName)) {
      keys = this.options.authorizedInInputs;
    }

    /* istanbul ignore else */
    if (keys.includes(e.keyCode)) {
      e.preventDefault();
    }
  }
}

export default new DisableScroll();
<commit_msg>Fix lint errors<commit_after>import 'scrollingelement';

const canUseDOM = !!(
  typeof window !== 'undefined'
  && window.document
  && window.document.createElement
);

class DisableScroll {
  constructor() {
    this.options = {
      disableWheel: true,
      disableScroll: true,
      disableKeys: true,
      keyboardKeys: [32, 33, 34, 35, 36, 37, 38, 39, 40],
      authorizedInInputs: [32, 37, 38, 39, 40]
      // space: 32, page up: 33, page down: 34, end: 35, home: 36
      // left: 37, up: 38, right: 39, down: 40
    };

    this.element = canUseDOM ? document.scrollingElement : null;
    this.lockToScrollPos = [0, 0];
  }

  /**
   * Disable Page Scroll
   * @external Node
   *
   * @param {HTMLElement} [element] - DOM Element, usually document.body
   * @param {object} [options] - Change the initial options
   */
  on(element, options) {
    if (!canUseDOM) return;

    this.element = element || this.element;
    this.options = {
      ...this.options,
      ...options,
    };

    const { disableKeys, disableScroll, disableWheel } = this.options;

    /* istanbul ignore else */
    if (disableWheel) {
      document.addEventListener('wheel', this.handleWheel);
      document.addEventListener('touchmove', this.handleWheel);
    }

    /* istanbul ignore else */
    if (disableScroll) {
      this.lockToScrollPos = [
        this.element.scrollLeft || this.element.scrollX,
        this.element.scrollTop || this.element.scrollY
      ];
      document.addEventListener('scroll', this.handleScroll);
    }

    /* istanbul ignore else */
    if (disableKeys) {
      document.addEventListener('keydown', this.handleKeydown);
    }
  }

  /**
   * Re-enable page scrolls
   */
  off() {
    if (!canUseDOM) return;

    document.removeEventListener('wheel', this.handleWheel);
    document.removeEventListener('touchmove', this.handleWheel);
    document.removeEventListener('scroll', this.handleScroll);
    document.removeEventListener('keydown', this.handleKeydown);
  }

  handleWheel = (e) => {
    e.preventDefault();
  };

  handleScroll = () => {
    window.scrollTo(...this.lockToScrollPos);
  };

  handleKeydown = (e) => {
    let keys = this.options.keyboardKeys;

    /* istanbul ignore else */
    if (['INPUT', 'TEXTAREA'].includes(e.target.tagName)) {
      keys = this.options.authorizedInInputs;
    }

    /* istanbul ignore else */
    if (keys.includes(e.keyCode)) {
      e.preventDefault();
    }
  }
}

export default new DisableScroll();
<|endoftext|>


<commit_before>// @flow
const _ = require('lodash');
const handlers = require('./handlers');

const errorParser = response => (err) => {
  if (err.code === 100) {
    response(null, { error: err.message, ok: false });
  } else {
    response(err);
  }
};

const handlerAdder = seneca => (item) => {
  seneca.add(item.pattern, (msg, response) => {
    const successHandler = data => response(null, data);
    const errorHandler = errorParser(response);
    Promise.resolve(item.handler(msg, successHandler))
      .then(() => undefined)
      .catch(errorHandler);
  });
};

const plugin = (function startHandlers() {
  _.each(handlers, handlerAdder(this));
});
const pins = () => _.map(handlers, 'pattern');
const start = () => ({
  plugin,
  pins: pins(),
});

module.exports = { start };
<commit_msg>no error handling<commit_after>// @flow
const _ = require('lodash');
const handlers = require('./handlers');

const handlerAdder = seneca => (item) => {
  seneca.add(item.pattern, (msg, response) => {
    const successHandler = data => response(null, data);
    Promise.resolve(item.handler(msg, successHandler))
      .then(() => undefined)
      .catch(err => response(err));
  });
};

const plugin = (function startHandlers() {
  _.each(handlers, handlerAdder(this));
});
const pins = () => _.map(handlers, 'pattern');
const start = () => ({
  plugin,
  pins: pins(),
});

module.exports = { start };
<|endoftext|>


<commit_before>(function(){

var HTTPResponse = function() {
    this._output = false;
    this._ct = false; /* Content-type - the only header which must be present */
}

HTTPResponse.prototype.write = function(str) {
    if (!this._output) {
		this._output = true;
		if (!this._ct) { this.header({"Content-type":"text/html"}); }
		System.stdout("\n");
    }
    System.stdout(str);
}

HTTPResponse.prototype.cookie = function(name, value, expires, path, domain, secure, httponly) {
    if (expires && !(expires instanceof Date)) { return false; }
    var arr = [];
    arr.push(encodeURIComponent(name)+"="+encodeURIComponent(value));
    if (expires) { arr.push("expires="+expires.toGMTString()); }
    if (path) { arr.push("path="+path); }
    if (domain) { arr.push("domain="+domain); }
    if (secure) { arr.push("secure"); }
    if (httponly) { arr.push("httponly"); }

    var str = arr.join("; ");
    this.header({"Set-Cookie":str});
    return true;
}

HTTPResponse.prototype.error = function(txt) {
    this.write("
Error: "+txt+"
");
}

HTTPResponse.prototype.header = function(h) {
    for (var p in h) {
	if (p.match(/content-type/i)) { this._ct = true; }
	if (p.match(/location/i)) { this.header({"Status":"302 Found"}); }
	var str = p+": "+h[p]+"\n";
	System.stdout(str);
    }
}

HTTPResponse.prototype.escape = function(str) {
	if (str === null || !str.toString) { return ""; }
    return str.toString().replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"); // "
}

HTTPResponse.prototype.dump = function(obj, depth) {
    var d = depth || 0;
    if (!d) { this.write("
\n"); }
    for (var p in obj) {
		var val = obj[p];
		if (val === null) { val = "[null]"; }
		for (var i=0;i<2*d;i++) { this.write(" "); }
		this.write(p+": "+this.escape(val)+"\n");
		if (typeof(val) == "object") {
	    	arguments.callee.call(this, val, d+1);
		}
    }
    if (!d) { this.write("
\n"); }
}

var HTTPRequest = function() {
    this.get = {};
    this.post = {};
    this.cookie = {};
    this.files = {};

    this.method = null;
    if (System.env["REQUEST_METHOD"]) { this.method = System.env["REQUEST_METHOD"].toUpperCase(); }
    if (!this.method) { return; }

    this._parseCookie();
    this._parseQS(System.env["QUERY_STRING"], this.get);
    if (this.method == "POST") { this._parsePOST(); }
}

HTTPRequest.prototype.header = function(name) {
    var n = "HTTP_" + name.toUpperCase().replace(/-/g,"_");
    return (n in System.env ? System.env[n] : null);
}

HTTPRequest.prototype._parseCookie = function() {
    if (!("HTTP_COOKIE" in System.env)) { return; }
    var all = System.env["HTTP_COOKIE"].split("; ");
    for (var i=0;i<all.length;i++) {
	var row = all[i];
	var eq = row.indexOf("=");
	var name = row.substring(0,eq);
	var value = row.substring(eq+1);
	if (!this.cookie[name]) { this.cookie[name] = unescape(value); }
    }
}

HTTPRequest.prototype._decode = function(str) {
    var s = str;
    var err = false;
    try {
		s = decodeURIComponent(str);
    } catch(e) {
	//	response.error("Cannot urldecode string");
    } finally {
		return s;
    }
}

HTTPRequest.prototype._parseQS = function(qs, output) {
    if (!qs) { return; }
    var parts = qs.split("&");
    for (var i=0;i<parts.length;i++) {
	var item = parts[i];
	if (!item) { continue; }
	var eq = item.indexOf("=");
	var name = "";
	var value = "";

	if (eq == -1) {
	    name = item;
	} else {
	    name = item.substring(0,eq);
	    value = item.substring(eq+1);
	}
	if (name.substring(name.length-2) == "[]") { name = name.substring(0,name.length-2); }

	name = this._decode(name);
	value = this._decode(value);

	this._addField(output, name, value);
    }
}

HTTPRequest.prototype._parsePOST = function() {
    var ct = System.env["CONTENT_TYPE"] || "";
    var length = parseInt(System.env["CONTENT_LENGTH"], 10);
    if (!length) { return false; }

    if (System.env["CONTENT_TYPE"] == "application/x-www-form-urlencoded") {
		var data = System.stdin(length);
		this._parseQS(data, this.post);
    } else if (ct.match(/boundary/)) {
		var arr = System.stdin(length, true);
		var str = String.fromCharCode.apply(this, arr); /* convert from array to string */
		this._parseMultipart(ct, str, false);
    } else {
		return false;
    }
    return true;
}

HTTPRequest.prototype._addField = function(output, name, value) {
    if (!(name in output)) {
        output[name] = value;
    } else if (output[name] instanceof Array) {
        output[name].push(value);
    } else {
	output[name] = [output[name], value];
    }
}

HTTPRequest.prototype._parseMultipart = function(header, data, name) {
    var boundary = header.match(/boundary=(.*)/); /* find boundary */
    boundary = boundary[1];
    var start = "--"+boundary+"\r\n";
    var end = "--"+boundary+"--";
    var parts = data.split(start); /* split by boundary */
    for (var i=0;i<parts.length;i++) { /* all multipart parts */
		var item = parts[i].substring(0, parts[i].length-2);
		if (item == "" || item == "--") { continue; }

		var lines = item.split("\r\n");
		var done = false;
		var obj = {
			headers:{},
			data:""
		};
		for (var j=0;j<lines.length;j++) {
			if (lines[j] == end) { continue; }
			if (done) { /* data */
			obj.data += (obj.data.length ? "\r\n" : "")+lines[j];
			} else { /* headers */
			if (lines[j] == "") { done = true; continue; } /* headers done */
			var r = lines[j].match(/([^:]+): *(.*)/);
			var name = r[1].replace(/-/g,"_").toUpperCase();
			var value = r[2];
			obj.headers[name] = value;
			}
		}
		this._processMultipart(obj, name); /* content parsed, decide how to handle it */
    }
}

HTTPRequest.prototype._processMultipart = function(obj, n) {
    var name = n;
    var cd = obj.headers["CONTENT_DISPOSITION"] || "";
    var ct = obj.headers["CONTENT_TYPE"] || "";
    var r = cd.match(/ name="(.*?)"/i); /* form field name */
    if (r) { name = r[1]; }
    if (ct.match(/multipart\/mixed/i)) { /* recursive processing */
		this._parseMultipart(ct, obj.data, name);
    } else { /* no recursion: either file or form field */
        var r = cd.match(/filename="(.*?)"/i);
		if (r) { /* file */
			obj.originalName = r[1];
			this._addField(this.files, name, obj);
		} else { /* form field */
			var utf = Util.utf8encode(obj.data);
			this._addField(this.post, name, utf);
		}
	}
}

var HTTPSession = function() {
    this._data = {};
    this._id = null;
    this._file = null;

    this._name = Config.sessionCookie || "V8SID";
    this._path = Config.sessionPath || "/tmp";
    this._domain = Config.sessionDomain || "/";
    if (this._path.charAt(this._path.length-1) != "/") { this._path += "/"; }
    this._lifetime = Config.sessionTime || 60*60;
    this._gc();

    var ok = false;
    if (request.cookie[this._name]) { /* cookie here */
	var id = request.cookie[this._name];
	var f = new File(this._fileName(id));
	if (f.exists()) { /* matching file */
	    this._id = id;
	    this._file = f;
	    this._load();
	    ok = true;
	}
    }
    if (!ok) {
	this.setId();
	this.clear();
    }

    var self = this;
    var callback = function() { self.save(); }
    onexit(callback);
}

HTTPSession.prototype.set = function(name, value) {
    this._data[name] = value;
}

HTTPSession.prototype.get = function(name) {
    return this._data[name] || null;
}

HTTPSession.prototype.clear = function() {
    this._data = {};
    if (this._file.exists()) { this._file.remove(); }
}

HTTPSession.prototype.save = function() {
    var propcnt = 0;
    for (var p in this._data) { propcnt++; }
    if (propcnt == 0) {
	if (this._file.exists()) { this._file.remove(); }
	return;
    }
    var str = Util.serialize(this._data);
    this._file.open("w").write(str).close();
}

HTTPSession.prototype.getId = function() {
    return this._id;
}

HTTPSession.prototype.setId = function(id) {
    this._id = id || this._newId();
    this._cookie();
    this._file = new File(this._fileName(this._id));
}

HTTPSession.prototype._newId = function() {
    var str = "";
    for (var i=0;i<3;i++) {
	str += Math.random().toString();
    }
    return Util.sha1(str);
}

HTTPSession.prototype._fileName = function(id) {
    return this._path + Util.sha1(id);
}

HTTPSession.prototype._gc = function() {
    var d = new Directory(this._path);
    var files = d.listFiles();
    var now = Math.round(new Date().getTime()/1000);
    for (var i=0;i<files.length;i++) {
	var file = new File(this._path + files[i]);
	var data = file.stat();
	if (now - data.atime > this._lifetime && now - data.mtime > this._lifetime) {
	    try { file.remove(); } catch(e) { }
	}
    }
}

HTTPSession.prototype._cookie = function() {
    var d = new Date();
    d.setFullYear(100+d.getFullYear());
    response.cookie(this._name, this._id, d, this._domain);
}

HTTPSession.prototype._load = function() {
    var str = this._file.open("r").read();
    this._file.close();
    this._data = Util.unserialize(str);
}

this.response = new HTTPResponse();
this.request = new HTTPRequest();
this.session = new HTTPSession();

})();
<commit_msg>response.dump second argument<commit_after>(function(){

var HTTPResponse = function() {
    this._output = false;
    this._ct = false; /* Content-type - the only header which must be present */
}

HTTPResponse.prototype.write = function(str) {
    if (!this._output) {
		this._output = true;
		if (!this._ct) { this.header({"Content-type":"text/html"}); }
		System.stdout("\n");
    }
    System.stdout(str);
}

HTTPResponse.prototype.cookie = function(name, value, expires, path, domain, secure, httponly) {
    if (expires && !(expires instanceof Date)) { return false; }
    var arr = [];
    arr.push(encodeURIComponent(name)+"="+encodeURIComponent(value));
    if (expires) { arr.push("expires="+expires.toGMTString()); }
    if (path) { arr.push("path="+path); }
    if (domain) { arr.push("domain="+domain); }
    if (secure) { arr.push("secure"); }
    if (httponly) { arr.push("httponly"); }

    var str = arr.join("; ");
    this.header({"Set-Cookie":str});
    return true;
}

HTTPResponse.prototype.error = function(txt) {
    this.write("
Error: "+txt+"
");
}

HTTPResponse.prototype.header = function(h) {
    for (var p in h) {
	if (p.match(/content-type/i)) { this._ct = true; }
	if (p.match(/location/i)) { this.header({"Status":"302 Found"}); }
	var str = p+": "+h[p]+"\n";
	System.stdout(str);
    }
}

HTTPResponse.prototype.escape = function(str) {
	if (str === null || !str.toString) { return ""; }
    return str.toString().replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"); // "
}

HTTPResponse.prototype.dump = function(obj, nowrite, depth) {
	var result = "";
    var d = depth || 0;

    if (!d) { result += "
\n"; }
    for (var p in obj) {
		var val = obj[p];
		if (val === null) { val = "[null]"; }
		for (var i=0;i<2*d;i++) { result += " "; }
		result += p+": "+this.escape(val)+"\n";
		if (typeof(val) == "object") {
	    	result += arguments.callee.call(this, val, nowrite, d+1);
		}
    }
    if (!d) { result += "
\n"; }
	if (!nowrite) { this.write(result); }
	return result;
}

var HTTPRequest = function() {
    this.get = {};
    this.post = {};
    this.cookie = {};
    this.files = {};

    this.method = null;
    if (System.env["REQUEST_METHOD"]) { this.method = System.env["REQUEST_METHOD"].toUpperCase(); }
    if (!this.method) { return; }

    this._parseCookie();
    this._parseQS(System.env["QUERY_STRING"], this.get);
    if (this.method == "POST") { this._parsePOST(); }
}

HTTPRequest.prototype.header = function(name) {
    var n = "HTTP_" + name.toUpperCase().replace(/-/g,"_");
    return (n in System.env ? System.env[n] : null);
}

HTTPRequest.prototype._parseCookie = function() {
    if (!("HTTP_COOKIE" in System.env)) { return; }
    var all = System.env["HTTP_COOKIE"].split("; ");
    for (var i=0;i<all.length;i++) {
	var row = all[i];
	var eq = row.indexOf("=");
	var name = row.substring(0,eq);
	var value = row.substring(eq+1);
	if (!this.cookie[name]) { this.cookie[name] = unescape(value); }
    }
}

HTTPRequest.prototype._decode = function(str) {
    var s = str;
    var err = false;
    try {
		s = decodeURIComponent(str);
    } catch(e) {
	//	response.error("Cannot urldecode string");
    } finally {
		return s;
    }
}

HTTPRequest.prototype._parseQS = function(qs, output) {
    if (!qs) { return; }
    var parts = qs.split("&");
    for (var i=0;i<parts.length;i++) {
	var item = parts[i];
	if (!item) { continue; }
	var eq = item.indexOf("=");
	var name = "";
	var value = "";

	if (eq == -1) {
	    name = item;
	} else {
	    name = item.substring(0,eq);
	    value = item.substring(eq+1);
	}
	if (name.substring(name.length-2) == "[]") { name = name.substring(0,name.length-2); }

	name = this._decode(name);
	value = this._decode(value);

	this._addField(output, name, value);
    }
}

HTTPRequest.prototype._parsePOST = function() {
    var ct = System.env["CONTENT_TYPE"] || "";
    var length = parseInt(System.env["CONTENT_LENGTH"], 10);
    if (!length) { return false; }

    if (System.env["CONTENT_TYPE"] == "application/x-www-form-urlencoded") {
		var data = System.stdin(length);
		this._parseQS(data, this.post);
    } else if (ct.match(/boundary/)) {
		var arr = System.stdin(length, true);
		var str = String.fromCharCode.apply(this, arr); /* convert from array to string */
		this._parseMultipart(ct, str, false);
    } else {
		return false;
    }
    return true;
}

HTTPRequest.prototype._addField = function(output, name, value) {
    if (!(name in output)) {
        output[name] = value;
    } else if (output[name] instanceof Array) {
        output[name].push(value);
    } else {
	output[name] = [output[name], value];
    }
}

HTTPRequest.prototype._parseMultipart = function(header, data, name) {
    var boundary = header.match(/boundary=(.*)/); /* find boundary */
    boundary = boundary[1];
    var start = "--"+boundary+"\r\n";
    var end = "--"+boundary+"--";
    var parts = data.split(start); /* split by boundary */
    for (var i=0;i<parts.length;i++) { /* all multipart parts */
		var item = parts[i].substring(0, parts[i].length-2);
		if (item == "" || item == "--") { continue; }

		var lines = item.split("\r\n");
		var done = false;
		var obj = {
			headers:{},
			data:""
		};
		for (var j=0;j<lines.length;j++) {
			if (lines[j] == end) { continue; }
			if (done) { /* data */
			obj.data += (obj.data.length ? "\r\n" : "")+lines[j];
			} else { /* headers */
			if (lines[j] == "") { done = true; continue; } /* headers done */
			var r = lines[j].match(/([^:]+): *(.*)/);
			var name = r[1].replace(/-/g,"_").toUpperCase();
			var value = r[2];
			obj.headers[name] = value;
			}
		}
		this._processMultipart(obj, name); /* content parsed, decide how to handle it */
    }
}

HTTPRequest.prototype._processMultipart = function(obj, n) {
    var name = n;
    var cd = obj.headers["CONTENT_DISPOSITION"] || "";
    var ct = obj.headers["CONTENT_TYPE"] || "";
    var r = cd.match(/ name="(.*?)"/i); /* form field name */
    if (r) { name = r[1]; }
    if (ct.match(/multipart\/mixed/i)) { /* recursive processing */
		this._parseMultipart(ct, obj.data, name);
    } else { /* no recursion: either file or form field */
        var r = cd.match(/filename="(.*?)"/i);
		if (r) { /* file */
			obj.originalName = r[1];
			this._addField(this.files, name, obj);
		} else { /* form field */
			var utf = Util.utf8encode(obj.data);
			this._addField(this.post, name, utf);
		}
	}
}

var HTTPSession = function() {
    this._data = {};
    this._id = null;
    this._file = null;

    this._name = Config.sessionCookie || "V8SID";
    this._path = Config.sessionPath || "/tmp";
    this._domain = Config.sessionDomain || "/";
    if (this._path.charAt(this._path.length-1) != "/") { this._path += "/"; }
    this._lifetime = Config.sessionTime || 60*60;
    this._gc();

    var ok = false;
    if (request.cookie[this._name]) { /* cookie here */
	var id = request.cookie[this._name];
	var f = new File(this._fileName(id));
	if (f.exists()) { /* matching file */
	    this._id = id;
	    this._file = f;
	    this._load();
	    ok = true;
	}
    }
    if (!ok) {
	this.setId();
	this.clear();
    }

    var self = this;
    var callback = function() { self.save(); }
    onexit(callback);
}

HTTPSession.prototype.set = function(name, value) {
    this._data[name] = value;
}

HTTPSession.prototype.get = function(name) {
    return this._data[name] || null;
}

HTTPSession.prototype.clear = function() {
    this._data = {};
    if (this._file.exists()) { this._file.remove(); }
}

HTTPSession.prototype.save = function() {
    var propcnt = 0;
    for (var p in this._data) { propcnt++; }
    if (propcnt == 0) {
	if (this._file.exists()) { this._file.remove(); }
	return;
    }
    var str = Util.serialize(this._data);
    this._file.open("w").write(str).close();
}

HTTPSession.prototype.getId = function() {
    return this._id;
}

HTTPSession.prototype.setId = function(id) {
    this._id = id || this._newId();
    this._cookie();
    this._file = new File(this._fileName(this._id));
}

HTTPSession.prototype._newId = function() {
    var str = "";
    for (var i=0;i<3;i++) {
	str += Math.random().toString();
    }
    return Util.sha1(str);
}

HTTPSession.prototype._fileName = function(id) {
    return this._path + Util.sha1(id);
}

HTTPSession.prototype._gc = function() {
    var d = new Directory(this._path);
    var files = d.listFiles();
    var now = Math.round(new Date().getTime()/1000);
    for (var i=0;i<files.length;i++) {
	var file = new File(this._path + files[i]);
	var data = file.stat();
	if (now - data.atime > this._lifetime && now - data.mtime > this._lifetime) {
	    try { file.remove(); } catch(e) { }
	}
    }
}

HTTPSession.prototype._cookie = function() {
    var d = new Date();
    d.setFullYear(100+d.getFullYear());
    response.cookie(this._name, this._id, d, this._domain);
}

HTTPSession.prototype._load = function() {
    var str = this._file.open("r").read();
    this._file.close();
    this._data = Util.unserialize(str);
}

this.response = new HTTPResponse();
this.request = new HTTPRequest();
this.session = new HTTPSession();

})();
<|endoftext|>


<commit_before>var mathf = require("mathf"),
    vec3 = require("vec3"),
    Contact3 = require("contact3");

module.exports = function sphereToSphere(x1, y1, z1, r1, x2, y2, z2, r2) {
    var dx = x2 - x1,
        dy = y2 - y1,
        dz = z2 - z1,
        r = r1 + r2,
        rsq = r * r,
        dsq = dx * dx + dy * dy + dz * dz,
        contact, d, invD, invR, nx, ny, nz, depth;

    if (dsq < rsq) {
        contact = Contact3.create();

        if (dsq !== 0) {
            d = mathf.sqrt(dsq);
            invD = 1 / d;

            nx = dx * invD;
            ny = dy * invD;
            nz = dz * invD;
        } else {
            nx = 0;
            ny = 0;
            nz = 1;
        }

        depth = (r - d) * 0.5;
        invR = r !== 0 ? 1 / r : 0;

        vec3.set(contact.point, (x1 * r2 + x2 * r1) * invR, (y1 * r2 + y2 * r1) * invR, (z1 * r2 + z2 * r1) * invR);
        vec3.set(contact.normal, nx, ny, nz);
        contact.depth = depth;

        return contact;
    } else {
        return false;
    }
};
<commit_msg>updates<commit_after>var mathf = require("mathf"),
    vec3 = require("vec3"),
    Contact3 = require("contact3");

module.exports = function sphereToSphere(x1, y1, z1, r1, x2, y2, z2, r2) {
    var dx = x2 - x1,
        dy = y2 - y1,
        dz = z2 - z1,
        r = r1 + r2,
        rsq = r * r,
        dsq = dx * dx + dy * dy + dz * dz,
        contact, d, invD, invR, nx, ny, nz;

    if (dsq < rsq) {
        contact = Contact3.create();

        if (dsq !== 0) {
            d = mathf.sqrt(dsq);
            invD = 1 / d;

            nx = dx * invD;
            ny = dy * invD;
            nz = dz * invD;
        } else {
            nx = 0;
            ny = 0;
            nz = 1;
        }

        invR = r !== 0 ? 1 / r : 0;

        vec3.set(contact.point, (x1 * r2 + x2 * r1) * invR, (y1 * r2 + y2 * r1) * invR, (z1 * r2 + z2 * r1) * invR);
        vec3.set(contact.normal, nx, ny, nz);
        contact.depth = (r - d) * 0.5;

        return contact;
    } else {
        return false;
    }
};
<|endoftext|>


<commit_before>/*
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 *
*/

var utils = require('cordova/utils');

function each(objects, func, context) {
    for (var prop in objects) {
        if (objects.hasOwnProperty(prop)) {
            func.apply(context, [objects[prop], prop]);
        }
    }
}

function clobber(obj, key, value) {
    exports.replaceHookForTesting(obj, key);
    obj[key] = value;
    // Getters can only be overridden by getters.
    if (obj[key] !== value) {
        utils.defineGetter(obj, key, function() {
            return value;
        });
    }
}

function assignOrWrapInDeprecateGetter(obj, key, value, message) {
    if (message) {
        utils.defineGetter(obj, key, function() {
            console.log(message);
            delete obj[key];
            clobber(obj, key, value);
            return value;
        });
    } else {
        clobber(obj, key, value);
    }
}

function include(parent, objects, clobber, merge) {
    each(objects, function (obj, key) {
        try {
            var result = obj.path ? require(obj.path) : {};

            if (clobber) {
                // Clobber if it doesn't exist.
                if (typeof parent[key] === 'undefined') {
                    assignOrWrapInDeprecateGetter(parent, key, result, obj.deprecated);
                } else if (typeof obj.path !== 'undefined') {
                    // If merging, merge properties onto parent, otherwise, clobber.
                    if (merge) {
                        recursiveMerge(parent[key], result);
                    } else {
                        assignOrWrapInDeprecateGetter(parent, key, result, obj.deprecated);
                    }
                }
                result = parent[key];
            } else {
                // Overwrite if not currently defined.
                if (typeof parent[key] == 'undefined') {
                    assignOrWrapInDeprecateGetter(parent, key, result, obj.deprecated);
                } else {
                    // Set result to what already exists, so we can build children into it if they exist.
                    result = parent[key];
                }
            }

            if (obj.children) {
                include(result, obj.children, clobber, merge);
            }
        } catch(e) {
            utils.alert('Exception building Cordova JS globals: ' + e + ' for key "' + key + '"');
        }
    });
}

/**
 * Merge properties from one object onto another recursively.  Properties from
 * the src object will overwrite existing target property.
 *
 * @param target Object to merge properties into.
 * @param src Object to merge properties from.
 */
function recursiveMerge(target, src) {
    for (var prop in src) {
        if (src.hasOwnProperty(prop)) {
            if (target.prototype && target.prototype.constructor === target) {
                // If the target object is a constructor override off prototype.
                clobber(target.prototype, prop, src[prop]);
            } else {
                if (typeof src[prop] === 'object' && typeof target[prop] === 'object') {
                    recursiveMerge(target[prop], src[prop]);
                } else {
                    clobber(target, prop, src[prop]);
                }
            }
        }
    }
}

exports.buildIntoButDoNotClobber = function(objects, target) {
    include(target, objects, false, false);
};
exports.buildIntoAndClobber = function(objects, target) {
    include(target, objects, true, false);
};
exports.buildIntoAndMerge = function(objects, target) {
    include(target, objects, true, true);
};
exports.recursiveMerge = recursiveMerge;
exports.assignOrWrapInDeprecateGetter = assignOrWrapInDeprecateGetter;
exports.replaceHookForTesting = function() {};
<commit_msg>CB-7868 Make <clobbers> on navigator not break on some versions of Android<commit_after>/*
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 *
*/

var utils = require('cordova/utils');

function each(objects, func, context) {
    for (var prop in objects) {
        if (objects.hasOwnProperty(prop)) {
            func.apply(context, [objects[prop], prop]);
        }
    }
}

function clobber(obj, key, value) {
    exports.replaceHookForTesting(obj, key);
    var needsProperty = false;
    try {
        obj[key] = value;
    } catch (e) {
        needsProperty = true;
    }
    // Getters can only be overridden by getters.
    if (needsProperty || obj[key] !== value) {
        utils.defineGetter(obj, key, function() {
            return value;
        });
    }
}

function assignOrWrapInDeprecateGetter(obj, key, value, message) {
    if (message) {
        utils.defineGetter(obj, key, function() {
            console.log(message);
            delete obj[key];
            clobber(obj, key, value);
            return value;
        });
    } else {
        clobber(obj, key, value);
    }
}

function include(parent, objects, clobber, merge) {
    each(objects, function (obj, key) {
        try {
            var result = obj.path ? require(obj.path) : {};

            if (clobber) {
                // Clobber if it doesn't exist.
                if (typeof parent[key] === 'undefined') {
                    assignOrWrapInDeprecateGetter(parent, key, result, obj.deprecated);
                } else if (typeof obj.path !== 'undefined') {
                    // If merging, merge properties onto parent, otherwise, clobber.
                    if (merge) {
                        recursiveMerge(parent[key], result);
                    } else {
                        assignOrWrapInDeprecateGetter(parent, key, result, obj.deprecated);
                    }
                }
                result = parent[key];
            } else {
                // Overwrite if not currently defined.
                if (typeof parent[key] == 'undefined') {
                    assignOrWrapInDeprecateGetter(parent, key, result, obj.deprecated);
                } else {
                    // Set result to what already exists, so we can build children into it if they exist.
                    result = parent[key];
                }
            }

            if (obj.children) {
                include(result, obj.children, clobber, merge);
            }
        } catch(e) {
            utils.alert('Exception building Cordova JS globals: ' + e + ' for key "' + key + '"');
        }
    });
}

/**
 * Merge properties from one object onto another recursively.  Properties from
 * the src object will overwrite existing target property.
 *
 * @param target Object to merge properties into.
 * @param src Object to merge properties from.
 */
function recursiveMerge(target, src) {
    for (var prop in src) {
        if (src.hasOwnProperty(prop)) {
            if (target.prototype && target.prototype.constructor === target) {
                // If the target object is a constructor override off prototype.
                clobber(target.prototype, prop, src[prop]);
            } else {
                if (typeof src[prop] === 'object' && typeof target[prop] === 'object') {
                    recursiveMerge(target[prop], src[prop]);
                } else {
                    clobber(target, prop, src[prop]);
                }
            }
        }
    }
}

exports.buildIntoButDoNotClobber = function(objects, target) {
    include(target, objects, false, false);
};
exports.buildIntoAndClobber = function(objects, target) {
    include(target, objects, true, false);
};
exports.buildIntoAndMerge = function(objects, target) {
    include(target, objects, true, true);
};
exports.recursiveMerge = recursiveMerge;
exports.assignOrWrapInDeprecateGetter = assignOrWrapInDeprecateGetter;
exports.replaceHookForTesting = function() {};
<|endoftext|>