<commit_before>var path="http://www.ssy.me/TNJ/js/map_sea.js";
var Data = {
	tooltip: {
		html: "

\n",
		css: "",
		js: 'seajs.use("lib/util/tooltip/tip",function($){\n  $(".tip").tooltip({"title":"ssss"}).tooltip("show");\n})'
	},
	pager: {
		html: "

\n",
		css: "",
		js: '/**\n* @parent 放置插件的容器\n* @current 当前页\n* @item  每页显示数量\n* @total  数据总数\n* @display_num 按钮最多显示数量\n* @selectChange 选项更改时触发的事件\n**/\nseajs.use("lib/util/pager/page",function(pager){\n  pager.init({\n		parent: ".pager",\n		current: 1,\n		item: 10,\n		total: 270,\n		display_num:5,\n		selectChange: function() {\n			console.log(this.current);\n		}\n	});\n})'
	},
	dialog: {
		html: "
\n    这是一个测试，这是抓取过来的隐藏DOM\n
\n",
		css: "",
		js: '/*!Extend jquery.js*/\n/**\n* @title 标题内容\n* @content 如果传入的是HTMLElement类型，\n		   如果是隐藏元素会给其设置display:block以显示该元素，\n		   其他属性与绑定的事件都会完整保留\n* @ok 	 确定按钮回调函数。\n		 函数如果返回false将阻止对话框关闭；函数this指针指向内部api；\n		 如果传入true表示只显示有关闭功能的按钮\n* @okVal  "确定按钮"文字\n* @cancel 取消按钮回调函数。\n		  函数如果返回false将阻止对话框关闭；函数this指针指向内部api；如果传入true表示只显示有关闭功能的按钮\n	      对话框标题栏的关闭按钮其实就是取消按钮，只不过视觉不同罢了，点击同样触发cancel事件\n* @cancelVal "取消按钮"文字\n* @copy   复制按钮，复制文字\n* @copy_target 复制目标默认.textarea\n* @width   设置消息内容宽度，可以带单位。一般不需要设置此，对话框框架会自己适应内容。\n		   如果设置为百分值单位，将会以根据浏览器可视范围作为基准，此时如果浏览器窗口大小被改变其也会进行相应的调整\n* @height  设置消息内容高度，可以带单位。不建议设置此，而应该让内容自己撑开高度。\n		   如果设置为百分值单位，将会以根据浏览器可视范围作为基准，此时如果浏览器窗口大小被改变其也会进行相应的调整\n* @drag   是否允许用户拖动位置\n* @time   设置对话框显示时间。以毫秒为单位\n*/\nseajs.use("lib/util/dialog/dialog",function(pop){\n  pop.dialog({\n    title:"这是一个测试",\n    content:$(".con"),\n    ok:function(){\n  		alert();\n  	},\n    drag:true,\n    copy:function(){\n    	this.tip();\n    },\n    copy_target:".con",\n  })	\n})'
	},
	item:{
		html:"
\n

\n
\n",
		css:".content{\n	width:900px;\n  	margin:0 auto;\n  	text-align: center;\n}",
		js:'/**\n* @parent 放置插件的容器\n* @item  表头数据 “键” 表示绑定域的ID，对应的之值表示表头名称\n* @data  数据对象数组\n* @display_num 按钮最多显示数量\n* @pager true:时启用分页插件,默认为:false\n* @per_item 每页显示数量\n**/\nseajs.use("lib/util/item/item",function(item){\n  item.init({\n	parent:".table",\n	item:{"ider":"ddd","ddd":"weqwe"},\n	data:[{"ider":"12","ddd":"dasd"},{"ider":"1222","ddd":"da3sd"},{"ider":"1tt2","ddd":"dasd"},{"ider":"1tt2","ddd":"dasd"},{"ider":"122t2","ddd":"da3sd"},{"ider":"12","ddd":"dasd"},{"ider":"12","ddd":"dasd"},{"ider":"1222","ddd":"da3sd"},{"ider":"12","ddd":"dasd"},{"ider":"12","ddd":"dasd"},{"ider":"1222","ddd":"da3sd"},{"ider":"12","ddd":"dasd"},{"ider":"1222","ddd":"da3sd"},{"ider":"12","ddd":"dasd"},{"ider":"1222","ddd":"da3sd"}],\n	pager:true,\n	per_item:3,\n	display_num:5\n  })\n})'
	},
	copy:{
		html:"
这是要被复制的内容
\n	复制\n",
		css:"",
		js:'/**\n* @arg1 复制按钮\n* @arg2 复制对象\n* @arg3 成功复制的回调函数\n**/\nseajs.use("lib/base/util",function(util){\n	util.copy(".copy", ".word", function() {\n		alert("复制成功！");\n	});\n})'
	},
	datepick:{
		html:"<input class='inputDate' value='2014-11-21'/>\n",
		css:".datepickerMonths{\n	font-size:14px;\n}",
		js:"/**\n* eventName	String 所需的事件来触发日期选择器。默认：click\n* date	String, Date, array	 选定的日期（S）为字符串和Date对象的单一选择，字符串或日期对象数组\n* flat 日期选取器被附加到元素或由事件触发,默认false\n* start 一天一周开始。默认:1（星期一）\n* mode single|multiple|range 模式\n* format  格式 默认YMD\n* position  位置top|left|right|bottom 默认bottom\n* onChange 回调函数触发时，日期将被改变\n* onRender 回调函数触发时，日期的日历被渲染\n* onHide 回调函数时触发，日期选择器被隐藏\n* onShow 回调函数触发,日期选择器显示\n* onBeforeShow 日期选择器之前,触发回调函数\n**/\nseajs.use('lib/util/calendar/datepicker',function(){\n	$('.inputDate').DatePicker({\n		format: 'Y-m-d',\n		date: $('.inputDate').val(),\n		current: $('.inputDate').val(),\n		starts: 1,\n		position: 'bottom',\n		onBeforeShow: function() {\n			$('.inputDate').DatePickerSetDate($('.inputDate').val(), true);\n		},\n		onChange: function(formated, dates) {\n			$('.inputDate').val(formated);\n		}\n	});\n})"
	},
	suggest:{
		html:"<input class='sug'/>\n",
		css:"",
		js:'/**\n* @target 目标输入框\n* @suggest 建议数组\n**/\nseajs.use("lib/util/suggest/suggester",function(suggest){\n	suggest.init({\n		target: ".sug",\n		suggest: ["", "@163.com", "@gmail.com", "@qq.com", "@111.com", "@tetequ.com"]\n	});\n})'
	},
	pieChart:{
		html:"
\n	\n	%\n
\n",
		css:".chart {\n  position: relative;\n  text-align: center;\n  height:150px;\n  width: 150px;\n  text-align :center;\n}\n.chart span {\n  display: inline-block;\n  line-height: 150px;\n  font-size: 1.3em;\n  z-index: 2;\n}\n.chart canvas {\n  position: absolute;\n  top: 0;\n  left: 0;\n}",
		js:'/**\n* @barColor 默认:＃ef1e25 该curcular栏的颜色。您可以通过有效的CSS颜色字符串，或一个函数，\n			它目前的百分比值，并返回一个有效的CSS颜色字符串。\n* @trackColor 默认:#f2f2f2  轨道的颜色，或false来禁用渲染\n* @scaleColor 默认:＃dfe0e0 刻度线的颜色，false来禁用渲染。\n* @scaleLength 默认:5 刻度线的长度（降低了图表的半径）\n* @lineCap 默认:round 定义其样式 参数为: butt , round and square\n* @lineWidth  圆的宽度 默认:3\n* @size    大小\n* @rotate  旋转图标的角度 默认:0\n* @animate   动画\n* @onStep(from, to, currentValue) 在动画提供的当前值\n*/\n\nseajs.use("lib/util/pieChart/chart",function(pager){\n  $(".chart").easyPieChart({\n		easing: "easeOutBounce",\n		onStep: function(from, to, percent) {\n			$(this.el).find(".percent").text(Math.round(percent));\n		},\n		lineCap: "butt",\n		size: 150,\n		lineWidth: 20,\n		barColor: "#e66e1e",\n		scaleColor: false\n	});\n})'
	},
	slider:{
		html:"

\n",
		css:".slider{\n	margin:100px;\n}",
		js:'/**\n* @parent 插件容器\n* @min 最小刻度值 默认0\n* @max 最大刻度值 默认100\n* @onChange 滑块value改变时触发\n\n* setValue 重设滑块值的函数\n**/\n\nseajs.use("lib/util/slider/slider",function(slider){\n  slider.init({\n	parent: ".slider",\n	min: 20,\n	max: 200,\n	onChange: function() {\n		console.log(this.value);\n	}\n  });\n  //slider.setValue(75);\n})'
	},
	validate:{
		html:"<form action=''>\n  邮箱验证:\n
\n    <input />\n
\n
\n    <input type='submit'  value='确定'/>\n
\n</form>\n",
		css:"body{\n	width:980px;\n  	margin: 50px auto;\n}\nform{\n	width:200px;\n}\ninput{\n	width:100%;\n}",
		js:'/**\n* 在HTML中的属性\n	@max 字符最大长度 默认：9999\n    @min 字符自小长度 默认：0\n    @reg 过滤用的正则表达式 \n    @data-trigger 触发条件 默认hover\n    @data-placement 显示位置 默认top\n**/\n\nseajs.use("lib/base/util",function(util){\n  util.validate();\n})'
	},
	parseTpl:{
		html:"

\n

\n",
		css:"",
		js:'/**\n* str 模板\n* data 数据\n* 解析模版tpl。当data未传入时返回编译结果函数；\n* 当某个template需要多次解析时，建议保存编译结果函数，\n* 然后调用此函数来得到结果\n**/\nseajs.use("lib/base/util",function(util){\n  var str = "
房间名称：<%=name%>
房间人数：<%=num%>
";\n  var obj = {num:"234",name: "hello"};\n  var value=util.parseTpl(str,obj);\n  $(".temp").append(value).next().text(value);\n})'
	},
	stringCat:{
		html:"

\n

\n",
		css:"",
		js:'/**\n* str 模板\n* data 数据\n**/\nseajs.use("lib/base/util",function(util){\n  var str = "
房间名称：%%
房间人数：%%
";\n  var value = util.stringCat(str,3,4);\n  $(".temp").append(value).next().text(value);\n});'
	},
	cookie:{
		html:"

\n",
		css:"",
		js:'/**\n* cookie创建，获取\n**/\nseajs.use("lib/util/cache/cookie",function(pager){\n  $.cookie("TEJ","easy");\n  $.cookie("TEJ","better",{"expires":1,"path":"/","domain":""});\n  $(".cookie").text($.cookie("TEJ"));\n  /**\n  * cookie删除\n  **/\n  //$.removeCookie("TEJ");\n})\n'
	},
	unslider:{
		html:'
\n
\n

\n\n

\n\n

\n\n

\n
\n
\n'+'',
		css:"body{\n  margin:0;\n  padding:0;\n}",
		js:'seajs.use("lib/util/unslider/unslider",function(){\n   $(".banner").unslider({\n      speed: 500,               //  The speed to animate each slide (in milliseconds)\n      delay: 3000,              //  The delay between slide animations (in milliseconds)\n      complete: function() {},  //  A function that gets called after every slide animation\n      keys: true,               //  Enable keyboard (left, right) arrow shortcuts\n      dots: true,               //  Display dot navigation\n      fluid: false              //  Support responsive design. May break non-responsive designs\n  });\n})'
	}
}
<commit_msg>change 注释<commit_after>var path="http://www.ssy.me/TNJ/js/map_sea.js";
var Data = {
	tooltip: {
		html: "

\n",
		css: "",
		js: 'seajs.use("lib/util/tooltip/tip",function($){\n  $(".tip").tooltip({"title":"ssss"}).tooltip("show");\n})'
	},
	pager: {
		html: "

\n",
		css: "",
		js: '/**\n* @parent 放置插件的容器\n* @current 当前页\n* @item  每页显示数量\n* @total  数据总数\n* @display_num 按钮最多显示数量\n* @selectChange 选项更改时触发的事件\n**/\nseajs.use("lib/util/pager/page",function(pager){\n  pager.init({\n		parent: ".pager",\n		current: 1,\n		item: 10,\n		total: 270,\n		display_num:5,\n		selectChange: function() {\n			console.log(this.current);\n		}\n	});\n})'
	},
	dialog: {
		html: "
\n    这是一个测试，这是抓取过来的隐藏DOM\n
\n",
		css: "",
		js: '/*!Extend jquery.js*/\n/**\n* @title 标题内容\n* @content 如果传入的是HTMLElement类型，\n		   如果是隐藏元素会给其设置display:block以显示该元素，\n		   其他属性与绑定的事件都会完整保留\n* @ok 	 确定按钮回调函数。\n		 函数如果返回false将阻止对话框关闭；函数this指针指向内部api；\n		 如果传入true表示只显示有关闭功能的按钮\n* @okVal  "确定按钮"文字\n* @cancel 取消按钮回调函数。\n		  函数如果返回false将阻止对话框关闭；函数this指针指向内部api；如果传入true表示只显示有关闭功能的按钮\n	      对话框标题栏的关闭按钮其实就是取消按钮，只不过视觉不同罢了，点击同样触发cancel事件\n* @cancelVal "取消按钮"文字\n* @copy   复制按钮，复制文字\n* @copy_target 复制目标默认.textarea\n* @width   设置消息内容宽度，可以带单位。一般不需要设置此，对话框框架会自己适应内容。\n		   如果设置为百分值单位，将会以根据浏览器可视范围作为基准，此时如果浏览器窗口大小被改变其也会进行相应的调整\n* @height  设置消息内容高度，可以带单位。不建议设置此，而应该让内容自己撑开高度。\n		   如果设置为百分值单位，将会以根据浏览器可视范围作为基准，此时如果浏览器窗口大小被改变其也会进行相应的调整\n* @drag   是否允许用户拖动位置\n* @time   设置对话框显示时间。以毫秒为单位\n*/\nseajs.use("lib/util/dialog/dialog",function(pop){\n  pop.dialog({\n    title:"这是一个测试",\n    content:$(".con"),\n    ok:function(){\n  		alert();\n  	},\n    drag:true,\n    copy:function(){\n    	this.tip();\n    },\n    copy_target:".con",\n  })	\n})'
	},
	item:{
		html:"
\n

\n
\n",
		css:".content{\n	width:900px;\n  	margin:0 auto;\n  	text-align: center;\n}",
		js:'/**\n* @parent 放置插件的容器\n* @item  表头数据 “键” 表示绑定域的ID，对应的之值表示表头名称\n* @data  数据对象数组\n* @display_num 按钮最多显示数量\n* @pager true:时启用分页插件,默认为:false\n* @per_item 每页显示数量\n**/\nseajs.use("lib/util/item/item",function(item){\n  item.init({\n	parent:".table",\n	item:{"ider":"ddd","ddd":"weqwe"},\n	data:[{"ider":"12","ddd":"dasd"},{"ider":"1222","ddd":"da3sd"},{"ider":"1tt2","ddd":"dasd"},{"ider":"1tt2","ddd":"dasd"},{"ider":"122t2","ddd":"da3sd"},{"ider":"12","ddd":"dasd"},{"ider":"12","ddd":"dasd"},{"ider":"1222","ddd":"da3sd"},{"ider":"12","ddd":"dasd"},{"ider":"12","ddd":"dasd"},{"ider":"1222","ddd":"da3sd"},{"ider":"12","ddd":"dasd"},{"ider":"1222","ddd":"da3sd"},{"ider":"12","ddd":"dasd"},{"ider":"1222","ddd":"da3sd"}],\n	pager:true,\n	per_item:3,\n	display_num:5\n  })\n})'
	},
	copy:{
		html:"
这是要被复制的内容
\n	复制\n",
		css:"",
		js:'/**\n* @arg1 复制按钮\n* @arg2 复制对象\n* @arg3 成功复制的回调函数\n**/\nseajs.use("lib/base/util",function(util){\n	util.copy(".copy", ".word", function() {\n		alert("复制成功！");\n	});\n})'
	},
	datepick:{
		html:"<input class='inputDate' value='2014-11-21'/>\n",
		css:".datepickerMonths{\n	font-size:14px;\n}",
		js:"/**\n* eventName	String 所需的事件来触发日期选择器。默认：click\n* date	String, Date, array	 选定的日期（S）为字符串和Date对象的单一选择，字符串或日期对象数组\n* flat 日期选取器被附加到元素或由事件触发,默认false\n* start 一天一周开始。默认:1（星期一）\n* mode single|multiple|range 模式\n* format  格式 默认YMD\n* position  位置top|left|right|bottom 默认bottom\n* onChange 回调函数触发时，日期将被改变\n* onRender 回调函数触发时，日期的日历被渲染\n* onHide 回调函数时触发，日期选择器被隐藏\n* onShow 回调函数触发,日期选择器显示\n* onBeforeShow 日期选择器之前,触发回调函数\n**/\nseajs.use('lib/util/calendar/datepicker',function(){\n	$('.inputDate').DatePicker({\n		format: 'Y-m-d',\n		date: $('.inputDate').val(),\n		current: $('.inputDate').val(),\n		starts: 1,\n		position: 'bottom',\n		onBeforeShow: function() {\n			$('.inputDate').DatePickerSetDate($('.inputDate').val(), true);\n		},\n		onChange: function(formated, dates) {\n			$('.inputDate').val(formated);\n		}\n	});\n})"
	},
	suggest:{
		html:"<input class='sug'/>\n",
		css:"",
		js:'/**\n* @target 目标输入框\n* @suggest 建议数组\n**/\nseajs.use("lib/util/suggest/suggester",function(suggest){\n	suggest.init({\n		target: ".sug",\n		suggest: ["", "@163.com", "@gmail.com", "@qq.com", "@111.com", "@tetequ.com"]\n	});\n})'
	},
	pieChart:{
		html:"
\n	\n	%\n
\n",
		css:".chart {\n  position: relative;\n  text-align: center;\n  height:150px;\n  width: 150px;\n  text-align :center;\n}\n.chart span {\n  display: inline-block;\n  line-height: 150px;\n  font-size: 1.3em;\n  z-index: 2;\n}\n.chart canvas {\n  position: absolute;\n  top: 0;\n  left: 0;\n}",
		js:'/**\n* @barColor 默认:＃ef1e25 该curcular栏的颜色。您可以通过有效的CSS颜色字符串，或一个函数，\n			它目前的百分比值，并返回一个有效的CSS颜色字符串。\n* @trackColor 默认:#f2f2f2  轨道的颜色，或false来禁用渲染\n* @scaleColor 默认:＃dfe0e0 刻度线的颜色，false来禁用渲染。\n* @scaleLength 默认:5 刻度线的长度（降低了图表的半径）\n* @lineCap 默认:round 定义其样式 参数为: butt , round and square\n* @lineWidth  圆的宽度 默认:3\n* @size    大小\n* @rotate  旋转图标的角度 默认:0\n* @animate   动画\n* @onStep(from, to, currentValue) 在动画提供的当前值\n*/\n\nseajs.use("lib/util/pieChart/chart",function(pager){\n  $(".chart").easyPieChart({\n		easing: "easeOutBounce",\n		onStep: function(from, to, percent) {\n			$(this.el).find(".percent").text(Math.round(percent));\n		},\n		lineCap: "butt",\n		size: 150,\n		lineWidth: 20,\n		barColor: "#e66e1e",\n		scaleColor: false\n	});\n})'
	},
	slider:{
		html:"

\n",
		css:".slider{\n	margin:100px;\n}",
		js:'/**\n* @parent 插件容器\n* @min 最小刻度值 默认0\n* @max 最大刻度值 默认100\n* @onChange 滑块value改变时触发\n\n* setValue 重设滑块值的函数\n**/\n\nseajs.use("lib/util/slider/slider",function(slider){\n  slider.init({\n	parent: ".slider",\n	min: 20,\n	max: 200,\n	onChange: function() {\n		console.log(this.value);\n	}\n  });\n  //slider.setValue(75);\n})'
	},
	validate:{
		html:"<form action=''>\n  邮箱验证:\n
\n    <input />\n
\n
\n    <input type='submit'  value='确定'/>\n
\n</form>\n",
		css:"body{\n	width:980px;\n  	margin: 50px auto;\n}\nform{\n	width:200px;\n}\ninput{\n	width:100%;\n}",
		js:'/**\n* 在HTML中的属性\n	@max 字符最大长度 默认：9999\n    @min 字符自小长度 默认：0\n    @reg 过滤用的正则表达式 \n    @data-trigger 触发条件 默认hover\n    @data-placement 显示位置 默认top\n**/\n\nseajs.use("lib/base/util",function(util){\n  util.validate();\n})'
	},
	parseTpl:{
		html:"

\n

\n",
		css:"",
		js:'/**\n* str 模板\n* data 数据\n* 解析模版tpl。当data未传入时返回编译结果函数；\n* 当某个template需要多次解析时，建议保存编译结果函数，\n* 然后调用此函数来得到结果\n**/\nseajs.use("lib/base/util",function(util){\n  var str = "
房间名称：<%=name%>
房间人数：<%=num%>
";\n  var obj = {num:"234",name: "hello"};\n  var value=util.parseTpl(str,obj);\n  $(".temp").append(value).next().text(value);\n})'
	},
	stringCat:{
		html:"

\n

\n",
		css:"",
		js:'/**\n* str 模板\n* data 数据\n**/\nseajs.use("lib/base/util",function(util){\n  var str = "
房间名称：%%
房间人数：%%
";\n  var value = util.stringCat(str,3,4);\n  $(".temp").append(value).next().text(value);\n});'
	},
	cookie:{
		html:"

\n",
		css:"",
		js:'/**\n* cookie创建，获取\n**/\nseajs.use("lib/util/cache/cookie",function(pager){\n  $.cookie("TEJ","easy");\n  $.cookie("TEJ","better",{"expires":1,"path":"/","domain":""});\n  $(".cookie").text($.cookie("TEJ"));\n  /**\n  * cookie删除\n  **/\n  //$.removeCookie("TEJ");\n})\n'
	},
	unslider:{
		html:'
\n
\n

\n\n

\n\n

\n\n

\n
\n
\n'+'',
		css:"body{\n  margin:0;\n  padding:0;\n}",
		js:'seajs.use("lib/util/unslider/unslider",function(){\n   $(".banner").unslider({\n      speed: 500,               //  动效执行时间\n      delay: 3000,              // 轮询时间 \n      complete: function() {},  //  每次滑动特效后执行函数\n      keys: true,               //  支持左右按键\n      dots: true,               //  点导航\n      fluid: true              //  是否支持响应式网页\n  });\n})'
	}
}
<|endoftext|>


<commit_before>var http = require('http');
var root = require('root');
var flat = require('flat-file-db');
var fs = require('fs');
var rimraf = require('rimraf');
var path = require('path');
var tar = require('tar-fs');
var select = require('select-keys');
var xtend = require('xtend');
var zlib = require('zlib');
var url = require('url');
var pump = require('pump');
var os = require('os');
var thunky = require('thunky');
var once = require('once');
var proc = require('child_process');
var protocol = require('../lib/protocol');
var subscriptions = require('../lib/subscriptions');
var pkg = require('../package.json');

var noop = function() {};

var HANDSHAKE =
	'HTTP/1.1 101 Swiching Protocols\r\n'+
	'Upgrade: hms-protocol\r\n'+
	'Connection: Upgrade\r\n\r\n';

var log = function(tag) {
	tag = tag ? '[term] ['+tag+']' : '[term]';
	console.log.apply(null, arguments);
};

module.exports = function(opts) {
	var server = root();
	var db = flat.sync('db');
	var subs = subscriptions();
	var docks = [];

	var ondock = function(protocol, host) {
		protocol.on('close', function() {
			docks.splice(docks.indexOf(protocol), 1);
			log(null, 'connection to dock ('+host+') dropped');
		});

		protocol.on('stdout', function(id, origin, data) {
			subs.publish('stdout', id, origin, data);
		});

		protocol.on('stderr', function(id, origin, data) {
			subs.publish('stderr', id, origin, data);
		});

		protocol.on('spawn', function(id, origin, pid) {
			subs.publish('spawn', id, origin, pid);
		});

		protocol.on('exit', function(id, origin, code) {
			subs.publish('exit', id, origin, code);
		});

		docks.push(protocol);
		log(null, 'connection to dock ('+host+') established');

		subs.subscriptions().forEach(function(key) {
			protocol.subscribe(key);
		});
	};

	var forEach = function(fn, cb) {
		cb = once(cb || noop);

		var result = [];
		var missing = docks.length;
		var onresponse = function(err, val) {
			if (err) return cb(err);

			if (val && !Buffer.isBuffer(val)) {
				if (Array.isArray(val)) result.push.apply(result, val);
				else result.push(val);
			}

			if (--missing) return;
			cb(null, result);
		};

		if (!missing) return cb(null, result);
		docks.forEach(function(dock) {
			fn(dock, onresponse);
		});
	};

	subs.on('subscribe', function(id, protocol, count) {
		if (count > 1) return;
		log(id, 'subscribing to service events and logs');
		forEach(function(dock, next) {
			dock.subscribe(id, next);
		});
	});

	subs.on('unsubscribe', function(id, protocol, count) {
		if (count) return;
		log(id, 'unsubscribing to service events and logs');
		forEach(function(dock, next) {
			dock.unsubscribe(id, next);
		});
	});

	var save = function(id, opts, cb) {
		db.put(id, xtend(db.get(id) || {id:id}, select(opts, ['start', 'build', 'docks', 'revision', 'env'])), cb);
	};

	var onstatuschange = function(id, status, cb) {
		if (!db.has(id)) return cb(new Error('Service not found'));

		var service = db.get(id);
		var upd = {start:service.start, build:service.build, env:service.env, docks:service.docks};

		service.stopped = status === 'stop';
		db.put(id, service, function(err) {
			if (err) return cb(err);

			log(id, 'sending', status, 'to docks');
			forEach(function(dock, next) {
				dock.update(id, upd, function(err) {
					if (err) return next(err);
					dock[status](id, next);
				});
			}, cb);
		});
	};

	var onclient = function(protocol) {
		protocol.on('add', function(id, opts, cb) {
			if (db.has(id)) return cb(new Error('Service already exist'));
			if (!/^[a-zA-Z0-9\-\.]+$/.test(id)) return cb(new Error('Service name should be alphanumericish'));
			log(id, 'adding new service');
			save(id, opts, cb);
		});

		protocol.on('update', function(id, opts, cb) {
			if (!db.has(id)) return cb(new Error('Service not found'));
			log(id, 'updating service');
			save(id, opts, cb);
		});

		protocol.on('remove', function(id, cb) {
			log(id, 'removing service');
			db.del(id, cb);
		});

		protocol.on('get', function(id, cb) {
			if (!db.has(id)) return cb(new Error('Service not found'));
			cb(null, db.get(id));
		});

		protocol.on('list', function(cb) {
			var list = db.keys().map(function(key) {
				return db.get(key);
			});

			cb(null, list);
		});

		protocol.on('distribute', function(id, service, cb) {
			if (!service) service = db.get(id);
			if (!service) return cb(new Error('Service not found'));
			log(id, 'distributing build to docks');
			save(id, service, function(err) {
				if (err) return cb(err);
				forEach(function(dock, next) {
					dock.distribute(id, service, next);
				}, cb);
			});
		});

		protocol.on('restart', function(id, cb) {
			onstatuschange(id, 'restart', cb);
		});

		protocol.on('start', function(id, cb) {
			onstatuschange(id, 'start', cb);
		});

		protocol.on('stop', function(id, cb) {
			onstatuschange(id, 'stop', cb);
		});

		protocol.on('ps', function(cb) {
			forEach(function(dock, next) {
				dock.ps(next);
			}, cb);
		});

		var unsubscribe = function(id, cb) {
			if (typeof cb !== 'function') cb = noop;
			var subs = subscriptions[id] = subscriptions[id] || [];
			var i = subs.indexOf(protocol);
			if (i === -1) return cb();

			log(id, 'client unsubscribing');
			if (subs.length === 1) delete subscriptions[id];
			else subs.splice(i, 1);
			cb();
		};

		protocol.on('subscribe', function(id, cb) {
			if (!db.has(id) && id !== '*') return cb(new Error('Service not found'));
			subs.subscribe(id, protocol);
			cb();
		});

		protocol.once('subscribe', function() {
			protocol.on('close', function() {
				subs.clear(protocol);
			});
		});

		protocol.on('unsubscribe', function(id, cb) {
			subs.unsubscribe(id, protocol);
			cb();
		});
	};

	var cache = {};

	server.put('/{id}', function(req, res) {
		var id = req.params.id;
		var deployed = new Date().toISOString();
		var cwd = path.join('builds', id+'@'+deployed);

		var onerror = function(status, message) {
			log(id, 'build failed');
			rimraf(cwd, function() {
				res.statusCode = status;
				res.addTrailers({'X-Status': status});
				res.end(message);
			});
		};

		var ondone = function(status) {
			var service = db.get(id);

			service.cwd = cwd;
			service.deployed = deployed;
			service.revision = req.query.revision;

			db.put(id, service, function(err) {
				if (err) return onerror(500);
				log(id, 'build succeded');
				delete cache[id];
				res.statusCode = status;
				res.addTrailers({'X-Status': 200});
				res.end();
			});
		};

		log(id, 'receiving tarball');
		res.setHeader('Trailer', 'X-Status');
		pump(req, zlib.createGunzip(), tar.extract(cwd), function(err) {
			if (err) return onerror(500, err.message);

			var service = db.get(id);

			if (!service) return onerror(404, 'Service not found');
			if (!service.build) return ondone(204);

			var build = proc.spawn('/bin/sh', ['-c', service.build, id], {cwd:cwd, env:service.env});

			build.stdout.pipe(res, {end:false});
			build.stderr.pipe(res, {end:false});

			build.on('error', function(err) {
				onerror(500);
			});

			build.on('close', function(code) {
				if (code) return onerror(500);
				if (!db.has(id)) return onerror(404);
				ondone(200);
			});
		});
	});

	server.get('/{id}', function(req, res) {
		var id = req.params.id;
		var service = db.get(id);

		if (!service) return res.error(404, 'Service not found');
		if (!service.cwd) return res.error(404, 'No builds found');

		if (!cache[id]) {
			log(id, 'writing tarball to cache');
			cache[id] = thunky(function(cb) {
				var tmp = path.join(os.tmpDir(), 'hms-'+id+'.tgz');
				pump(tar.pack(service.cwd), zlib.createGzip(), fs.createWriteStream(tmp), function(err) {
					if (err) return cb(err);
					cb(null, tmp);
				});
			});
		}

		log(id, 'sending tarball');
		cache[id](function(err, tmp) {
			if (err) return res.error(err);
			pump(fs.createReadStream(tmp), res);
		});
	});

	server.get('/', function(req, res) {
		res.end('hms-terminal '+pkg.version+'\n');
	});

	server.on('connect', function(req, socket, data) {
		var p = protocol(socket, data);
		socket.write(HANDSHAKE);
		if (req.url === '/dock') ondock(p, req.headers.origin || 'unknown');
		else onclient(p);
	});

	var port = opts.port || 10002;
	server.listen(port, function() {
		log(null, 'listening on', port);
		if (opts.dock) require('./dock')({port:port+1, remote:'127.0.0.1:'+port, id:opts.id, db:db});
	});
};<commit_msg>forwarding old env on build<commit_after>var http = require('http');
var root = require('root');
var flat = require('flat-file-db');
var fs = require('fs');
var rimraf = require('rimraf');
var path = require('path');
var tar = require('tar-fs');
var select = require('select-keys');
var xtend = require('xtend');
var zlib = require('zlib');
var url = require('url');
var pump = require('pump');
var os = require('os');
var thunky = require('thunky');
var once = require('once');
var proc = require('child_process');
var protocol = require('../lib/protocol');
var subscriptions = require('../lib/subscriptions');
var pkg = require('../package.json');

var noop = function() {};

var HANDSHAKE =
	'HTTP/1.1 101 Swiching Protocols\r\n'+
	'Upgrade: hms-protocol\r\n'+
	'Connection: Upgrade\r\n\r\n';

var log = function(tag) {
	tag = tag ? '[term] ['+tag+']' : '[term]';
	console.log.apply(null, arguments);
};

module.exports = function(opts) {
	var server = root();
	var db = flat.sync('db');
	var subs = subscriptions();
	var docks = [];

	var ondock = function(protocol, host) {
		protocol.on('close', function() {
			docks.splice(docks.indexOf(protocol), 1);
			log(null, 'connection to dock ('+host+') dropped');
		});

		protocol.on('stdout', function(id, origin, data) {
			subs.publish('stdout', id, origin, data);
		});

		protocol.on('stderr', function(id, origin, data) {
			subs.publish('stderr', id, origin, data);
		});

		protocol.on('spawn', function(id, origin, pid) {
			subs.publish('spawn', id, origin, pid);
		});

		protocol.on('exit', function(id, origin, code) {
			subs.publish('exit', id, origin, code);
		});

		docks.push(protocol);
		log(null, 'connection to dock ('+host+') established');

		subs.subscriptions().forEach(function(key) {
			protocol.subscribe(key);
		});
	};

	var forEach = function(fn, cb) {
		cb = once(cb || noop);

		var result = [];
		var missing = docks.length;
		var onresponse = function(err, val) {
			if (err) return cb(err);

			if (val && !Buffer.isBuffer(val)) {
				if (Array.isArray(val)) result.push.apply(result, val);
				else result.push(val);
			}

			if (--missing) return;
			cb(null, result);
		};

		if (!missing) return cb(null, result);
		docks.forEach(function(dock) {
			fn(dock, onresponse);
		});
	};

	subs.on('subscribe', function(id, protocol, count) {
		if (count > 1) return;
		log(id, 'subscribing to service events and logs');
		forEach(function(dock, next) {
			dock.subscribe(id, next);
		});
	});

	subs.on('unsubscribe', function(id, protocol, count) {
		if (count) return;
		log(id, 'unsubscribing to service events and logs');
		forEach(function(dock, next) {
			dock.unsubscribe(id, next);
		});
	});

	var save = function(id, opts, cb) {
		db.put(id, xtend(db.get(id) || {id:id}, select(opts, ['start', 'build', 'docks', 'revision', 'env'])), cb);
	};

	var onstatuschange = function(id, status, cb) {
		if (!db.has(id)) return cb(new Error('Service not found'));

		var service = db.get(id);
		var upd = {start:service.start, build:service.build, env:service.env, docks:service.docks};

		service.stopped = status === 'stop';
		db.put(id, service, function(err) {
			if (err) return cb(err);

			log(id, 'sending', status, 'to docks');
			forEach(function(dock, next) {
				dock.update(id, upd, function(err) {
					if (err) return next(err);
					dock[status](id, next);
				});
			}, cb);
		});
	};

	var onclient = function(protocol) {
		protocol.on('add', function(id, opts, cb) {
			if (db.has(id)) return cb(new Error('Service already exist'));
			if (!/^[a-zA-Z0-9\-\.]+$/.test(id)) return cb(new Error('Service name should be alphanumericish'));
			log(id, 'adding new service');
			save(id, opts, cb);
		});

		protocol.on('update', function(id, opts, cb) {
			if (!db.has(id)) return cb(new Error('Service not found'));
			log(id, 'updating service');
			save(id, opts, cb);
		});

		protocol.on('remove', function(id, cb) {
			log(id, 'removing service');
			db.del(id, cb);
		});

		protocol.on('get', function(id, cb) {
			if (!db.has(id)) return cb(new Error('Service not found'));
			cb(null, db.get(id));
		});

		protocol.on('list', function(cb) {
			var list = db.keys().map(function(key) {
				return db.get(key);
			});

			cb(null, list);
		});

		protocol.on('distribute', function(id, service, cb) {
			if (!service) service = db.get(id);
			if (!service) return cb(new Error('Service not found'));
			log(id, 'distributing build to docks');
			save(id, service, function(err) {
				if (err) return cb(err);
				forEach(function(dock, next) {
					dock.distribute(id, service, next);
				}, cb);
			});
		});

		protocol.on('restart', function(id, cb) {
			onstatuschange(id, 'restart', cb);
		});

		protocol.on('start', function(id, cb) {
			onstatuschange(id, 'start', cb);
		});

		protocol.on('stop', function(id, cb) {
			onstatuschange(id, 'stop', cb);
		});

		protocol.on('ps', function(cb) {
			forEach(function(dock, next) {
				dock.ps(next);
			}, cb);
		});

		var unsubscribe = function(id, cb) {
			if (typeof cb !== 'function') cb = noop;
			var subs = subscriptions[id] = subscriptions[id] || [];
			var i = subs.indexOf(protocol);
			if (i === -1) return cb();

			log(id, 'client unsubscribing');
			if (subs.length === 1) delete subscriptions[id];
			else subs.splice(i, 1);
			cb();
		};

		protocol.on('subscribe', function(id, cb) {
			if (!db.has(id) && id !== '*') return cb(new Error('Service not found'));
			subs.subscribe(id, protocol);
			cb();
		});

		protocol.once('subscribe', function() {
			protocol.on('close', function() {
				subs.clear(protocol);
			});
		});

		protocol.on('unsubscribe', function(id, cb) {
			subs.unsubscribe(id, protocol);
			cb();
		});
	};

	var cache = {};

	server.put('/{id}', function(req, res) {
		var id = req.params.id;
		var deployed = new Date().toISOString();
		var cwd = path.join('builds', id+'@'+deployed);

		var onerror = function(status, message) {
			log(id, 'build failed');
			rimraf(cwd, function() {
				res.statusCode = status;
				res.addTrailers({'X-Status': status});
				res.end(message);
			});
		};

		var ondone = function(status) {
			var service = db.get(id);

			service.cwd = cwd;
			service.deployed = deployed;
			service.revision = req.query.revision;

			db.put(id, service, function(err) {
				if (err) return onerror(500);
				log(id, 'build succeded');
				delete cache[id];
				res.statusCode = status;
				res.addTrailers({'X-Status': 200});
				res.end();
			});
		};

		log(id, 'receiving tarball');
		res.setHeader('Trailer', 'X-Status');
		pump(req, zlib.createGunzip(), tar.extract(cwd), function(err) {
			if (err) return onerror(500, err.message);

			var service = db.get(id);

			if (!service) return onerror(404, 'Service not found');
			if (!service.build) return ondone(204);

			var build = proc.spawn('/bin/sh', ['-c', service.build, id], {
				cwd:cwd,
				env:xtend(process.env, service.env)
			});

			build.stdout.pipe(res, {end:false});
			build.stderr.pipe(res, {end:false});

			build.on('error', function(err) {
				onerror(500);
			});

			build.on('close', function(code) {
				if (code) return onerror(500);
				if (!db.has(id)) return onerror(404);
				ondone(200);
			});
		});
	});

	server.get('/{id}', function(req, res) {
		var id = req.params.id;
		var service = db.get(id);

		if (!service) return res.error(404, 'Service not found');
		if (!service.cwd) return res.error(404, 'No builds found');

		if (!cache[id]) {
			log(id, 'writing tarball to cache');
			cache[id] = thunky(function(cb) {
				var tmp = path.join(os.tmpDir(), 'hms-'+id+'.tgz');
				pump(tar.pack(service.cwd), zlib.createGzip(), fs.createWriteStream(tmp), function(err) {
					if (err) return cb(err);
					cb(null, tmp);
				});
			});
		}

		log(id, 'sending tarball');
		cache[id](function(err, tmp) {
			if (err) return res.error(err);
			pump(fs.createReadStream(tmp), res);
		});
	});

	server.get('/', function(req, res) {
		res.end('hms-terminal '+pkg.version+'\n');
	});

	server.on('connect', function(req, socket, data) {
		var p = protocol(socket, data);
		socket.write(HANDSHAKE);
		if (req.url === '/dock') ondock(p, req.headers.origin || 'unknown');
		else onclient(p);
	});

	var port = opts.port || 10002;
	server.listen(port, function() {
		log(null, 'listening on', port);
		if (opts.dock) require('./dock')({port:port+1, remote:'127.0.0.1:'+port, id:opts.id, db:db});
	});
};<|endoftext|>


<commit_before>/*global describe, it, chai, expect */

"use strict";

var assert = require("assert"),
    chai = require("chai"),
    expect = chai.expect,
    chaiHttp = require('chai-http'),
    http = require('http'),
    cheerio = require('cheerio'),
    servicesStub = require("./services-stub");

chai.use(chaiHttp);

servicesStub.start(8080);

var parameters = {hostname: '192.168.50.50', port: '7000', path: '/work/work_00001'};

describe('PatronClient', function () {
    describe('/', function () {
        // FIXME tests should not use same data, and shouldn't get more data than they require
        servicesStub.getJson('/work/work_00001',
            {"id": "work_00001", "title": "Sult", "creator": "Knut Hamsun", "date": "1890",
                "editions": [
                    {"id": "edition_00001", "isbn": "82-05-27748-6", "placement": "Voksenavdelingen, Hovedbiblioteket", "shelf": "magasinet", "status": "På hylla"},
                    {"id": "edition_00001", "isbn": "82-05-27748-6", "placement": "Voksenavdelingen, Hovedbiblioteket", "status": "På hylla"}
                ]
                }
            );

        it('should return status OK', function (done) {
            chai.request('http://' + parameters.hostname + ':' + parameters.port).
                get(parameters.path).
                end(function (err, res) {
                    expect(err).to.equal(null);
                    expect(res).to.have.status(200);
                    done();
                });
        });

        it('should find text "Sult av Knut Hamsun (1890)"', function (done) {
            http.get(parameters, function (res) {
                var body = '',
                    $ = '';
                res.on('data', function (chunk) {
                    body += chunk;
                });
                res.on('end', function () {
                    $ = cheerio.load(body);
                    expect($('h1').text()).to.equal("Sult av Knut Hamsun (1890)");
                    done();
                });
            }).on('error', function (e) {
                console.log("Got error: ", e);
            });
        });
    });
});<commit_msg>Remove unused require.<commit_after>/*jslint node: true */
/*global describe, it */

"use strict";

var chai = require("chai"),
    expect = chai.expect,
    chaiHttp = require('chai-http'),
    http = require('http'),
    cheerio = require('cheerio'),
    servicesStub = require("./services-stub");

chai.use(chaiHttp);

servicesStub.start(8080);

var parameters = {hostname: '192.168.50.50', port: '7000', path: '/work/work_00001'};

describe('PatronClient', function () {
    describe('/', function () {
        // FIXME tests should not use same data, and shouldn't get more data than they require
        servicesStub.getJson('/work/work_00001',
            {"id": "work_00001", "title": "Sult", "creator": "Knut Hamsun", "date": "1890",
                "editions": [
                    {"id": "edition_00001", "isbn": "82-05-27748-6", "placement": "Voksenavdelingen, Hovedbiblioteket", "shelf": "magasinet", "status": "På hylla"},
                    {"id": "edition_00001", "isbn": "82-05-27748-6", "placement": "Voksenavdelingen, Hovedbiblioteket", "status": "På hylla"}
                ]
                }
            );

        it('should return status OK', function (done) {
            chai.request('http://' + parameters.hostname + ':' + parameters.port).
                get(parameters.path).
                end(function (err, res) {
                    expect(err).to.equal(null);
                    expect(res).to.have.status(200);
                    done();
                });
        });

        it('should find text "Sult av Knut Hamsun (1890)"', function (done) {
            http.get(parameters, function (res) {
                var body = '',
                    $ = '';
                res.on('data', function (chunk) {
                    body += chunk;
                });
                res.on('end', function () {
                    $ = cheerio.load(body);
                    expect($('h1').text()).to.equal("Sult av Knut Hamsun (1890)");
                    done();
                });
            }).on('error', function (e) {
                console.log("Got error: ", e);
            });
        });
    });
});<|endoftext|>


<commit_before>// dependencies
var Assert = require('assert')
  , GoogleApis = require('googleapis')
  , authData = require("./authData")
  ;

// output
console.log("Auth data is: ", authData);

// set jwt data
var jwt = new GoogleApis.auth.JWT(
    authData.email
  , authData.keyFile
  , authData.key
  , authData.scopes
  , "admin@example.com"
);

// authorize
jwt.authorize(function (err, data) {

    // output error
    if (err) {
        console.log("Error: ", err);
        return;
    }

    // output
    console.log("You have been successfully authenticated: ", data);

    // get client
    GoogleApis
        .discover('admin', 'directory_v1')
        .withAuthClient(jwt)
        .execute(function (err, client) {

            // handle error
            if (err) {
                return callback(err);
            }

            // create the group insert request
            var request = client.admin.members.delete({
                groupKey: "some_group@example.com"
            }, {
                email: "me@example.com"
            });

            // and execute it
            request.execute(function (err, data) {
                console.log(err, data);
            });
        });
});
<commit_msg>Added instructions<commit_after>/**
 *  # Creating a Service Account using the Google Developers Console
 *
 *  1. From the [Google Developers Console](https://cloud.google.com/console), select your project or create a new one.
 *
 *  2. Under "APIs & auth", click "Credentials".
 *
 *  3. Under "OAuth", click the "Create new client ID" button.
 *
 *  4. Select "Service account" as the application type and click "Create Client ID".
 *
 *  5. The key for your new service account should prompt for download automatically. Note that your key is protected with a password.
 *  IMPORTANT: keep a secure copy of the key, as Google keeps only the public key.
 *
 *  6. Convert the downloaded key to PEM, so we can use it from the Node [crypto](http://nodejs.org/api/crypto.html) module.
 *
 *  To do this, run the following in Terminal:
 *  ```bash
 *  openssl pkcs12 -in downloaded-key-file.p12 -out your-key-file.pem -nodes
 *  ```
 *
 *  You will be asked for the password you received during step 5.
 *
 *  That's it! You now have a service account with an email address and a key that you can use from your Node application.
 *
 *  [Source. Thanks!](https://github.com/extrabacon/google-oauth-jwt)
 *
 *  # Setting authentication data
 *  Create a file named `authData.json` containing:
 *  {
 *      "email":    "215406603088-l......rf19misb7rvrmu@developer.gserviceaccount.com"
 *    , "keyFile":  "./keyFile.pem"
 *    , "key":      "f5938a7....734e68bf1a6d5ad02"
 *    , "scopes":   [
 *          "https://www.googleapis.com/auth/admin.directory.group"
 *        , "https://www.googleapis.com/auth/admin.directory.group.member"
 *      ]
 *  }
 *
 *  Provide credentials of your Google Application in `email` and `key` fields.
 *
 * */

// dependencies
var Assert = require('assert')
  , GoogleApis = require('googleapis')
  , authData = require("./authData")
  ;

// output
console.log("Auth data is: ", authData);

// set jwt data
var jwt = new GoogleApis.auth.JWT(
    authData.email
  , authData.keyFile
  , authData.key
  , authData.scopes
  , "admin@example.com"
);

// authorize
jwt.authorize(function (err, data) {

    // output error
    if (err) {
        console.log("Error: ", err);
        return;
    }

    // output
    console.log("You have been successfully authenticated: ", data);

    // get client
    GoogleApis
        .discover('admin', 'directory_v1')
        .withAuthClient(jwt)
        .execute(function (err, client) {

            // handle error
            if (err) {
                return callback(err);
            }

            // create the group insert request
            var request = client.admin.members.delete({
                groupKey: "some_group@example.com"
            }, {
                email: "me@example.com"
            });

            // and execute it
            request.execute(function (err, data) {
                console.log(err, data);
            });
        });
});
<|endoftext|>


<commit_before>/*@pjs preload="data/images/logo1.png";*/

var sketchProc=function(processingInstance){ with (processingInstance){

//Setup
var wi = window.innerWidth ||
        document.documentElement.clientWidth ||
        document.body.clientWidth;
var he = window.innerHeight ||
         document.documentElement.clientHeight ||
         document.body.clientHeight;
size(wi*0.9,he*0.9);
frameRate(60);

setup = function() {
	mainfont = createFont("Times New Roman");
	logo = loadImage("data/images/logo1.png");
	ismobile = /iPhone|iPad|iPod|Android/i.test(navigator.userAgent);

	keys = [];
	pages = [];
	page = 0;

	chapter1 = [];
	chapter1pages = [];
	chapter1length = 6;

	chapter2 = [];
	chapter2pages = [];

	m = false;
	md = false;
	flevel = 255;
	bw = width/6;
	bh = width/12;
	prim = color(15,15,15);
	sec = color(100,30,30);
	tert = color(150,150,150);
	backg = color(55,55,55);

	// Standard fade in.
	fade = function() {
		flevel -= 10;
		fill(55,55,55,flevel);
		noStroke();
		rectMode(CORNER);
		rect(-1,-1,width+1,height+1);
	};

	// Loads all panels in the named folder into the target array.
	loadpanels = function(name,number,target) {
		for (i = 0; i < number;) {
			target[i] = loadImage("data/images/panels/"+name+i+".png");
			i ++;
		}
	};

	// The array of data for buttons used.
	buttons = {
		start:{x:width*(3/4),y:height/2,w:bw,h:bh,text:"Enter"},
		next:{x:width*(8/9),y:height*(1/2),w:bw,h:bh,text:"Next"},
		prev:{x:width*(1/9),y:height*(1/2),w:bw,h:bh,text:"Previous"},
	};

	// The hefty button function.  Works on all platforms tested.  Needs an exterior click call.
	button = function(con) {
		bux = con.x
		buy = con.y
		buw = con.w
		buh = con.h
		butext = con.text
		con.pressed = false;
		mouseover = false;

		rectMode(CENTER);

		if (mouseX>bux-buw/2&&mouseX<bux+buw/2 && mouseY>buy-buh/2&&mouseY<buy+buh/2) {
			mouseover = true;
		}

		if (mouseover) {
			fill(prim);
		} else {
			fill(sec);
		}
		stroke(prim);
		strokeWeight(buh/10);
		rect(bux,buy,buw,buh,buh/2.5);

		if (mouseover) {
			fill(sec);
		} else {
			fill(prim);
		}
		textFont(mainfont,buh/2);
		if (ismobile) {
			textSize(buh/3);
		}
		textAlign(CENTER,CENTER);
		text(butext,bux,buy);

		if (ismobile && mouseover) {
			con.pressed = true;
			return con.pressed;
		}

		if (mouseover && m) {
			con.pressed = true;
			return con.pressed;
		}
		return con.pressed;
	};

	// Standard button layout
	standardbuttons = function() {
		button(buttons.next);
		if (buttons.next.pressed) {
			if (ismobile) {
				if (flevel < 0) {
					page += 1;
					flevel = 255;
				}
			} else if (flevel < 80) {
				page += 1;
				flevel = 255;
			}
		};

		button(buttons.prev);
		if (buttons.prev.pressed) {
			if (ismobile) {
				if (flevel < 0) {
					page -= 1;
					flevel = 255;
				}
			} else if (flevel < 80) {
				page -= 1;
				flevel = 255;
			}

		};
	};

	// Displays an image properly.
	displaypanel = function(img,x,y) {
		imageMode(CENTER);
		pushMatrix();
		translate(x,y);
		scale(0.001*height,0.001*height);
			image(img,0,0);
		popMatrix();
	};

	// Creates a full page
	displaypage = function(chap,number) {
		background(backg);
		displaypanel(chap[number],width/2,height/2);
		standardbuttons();
		fade();
	};
	// Loads an array with full pages
	loadpages = function(cha,targ) {
		for (i = 0; i < cha.length; i ++) {
			targ.push(function() {fcha= cha; fi= i; displaypage(fcha,fi)});
		};
		targ[cha.length] = function() {
			background(backg);
			textSize(height/5);
			fill(sec);
			text("Under Construction",width/2,height/2);
		};
	};

	loadpanels("chap1/",chapter1length,chapter1);

	pages = [
		function() {
			background(backg)

			displaypanel(logo,width/4,height/2)

			button(buttons.start)
			if (buttons.start.pressed==true) {
				page += 1
			}
		},

	];
	loadpages(chapter1,pages);
};

draw = function() {
	pages[page]();
	textSize(17);
	text(pages,width/2,height/2);
};

keyPressed = function() {
	keys[keyCode] = true;
};
keyReleased = function() {
	keys[keyCode] = false;
};
mousePressed = function() {
	m = true;
};
mouseReleased = function() {
	m = false;
};
}};
<commit_msg>Update main.js<commit_after>/*@pjs preload="data/images/logo1.png";*/

var sketchProc=function(processingInstance){ with (processingInstance){

//Setup
var wi = window.innerWidth ||
        document.documentElement.clientWidth ||
        document.body.clientWidth;
var he = window.innerHeight ||
         document.documentElement.clientHeight ||
         document.body.clientHeight;
size(wi*0.9,he*0.9);
frameRate(60);

setup = function() {
	mainfont = createFont("Times New Roman");
	logo = loadImage("data/images/logo1.png");
	ismobile = /iPhone|iPad|iPod|Android/i.test(navigator.userAgent);

	keys = [];
	pages = [];
	page = 0;

	chapter1 = [];
	chapter1pages = [];
	chapter1length = 6;

	chapter2 = [];
	chapter2pages = [];

	m = false;
	md = false;
	flevel = 255;
	bw = width/6;
	bh = width/12;
	prim = color(15,15,15);
	sec = color(100,30,30);
	tert = color(150,150,150);
	backg = color(55,55,55);

	// Standard fade in.
	fade = function() {
		flevel -= 10;
		fill(55,55,55,flevel);
		noStroke();
		rectMode(CORNER);
		rect(-1,-1,width+1,height+1);
	};

	// Loads all panels in the named folder into the target array.
	loadpanels = function(name,number,target) {
		for (i = 0; i < number;) {
			target[i] = loadImage("data/images/panels/"+name+i+".png");
			i ++;
		}
	};

	// The array of data for buttons used.
	buttons = {
		start:{x:width*(3/4),y:height/2,w:bw,h:bh,text:"Enter"},
		next:{x:width*(8/9),y:height*(1/2),w:bw,h:bh,text:"Next"},
		prev:{x:width*(1/9),y:height*(1/2),w:bw,h:bh,text:"Previous"},
	};

	// The hefty button function.  Works on all platforms tested.  Needs an exterior click call.
	button = function(con) {
		bux = con.x
		buy = con.y
		buw = con.w
		buh = con.h
		butext = con.text
		con.pressed = false;
		mouseover = false;

		rectMode(CENTER);

		if (mouseX>bux-buw/2&&mouseX<bux+buw/2 && mouseY>buy-buh/2&&mouseY<buy+buh/2) {
			mouseover = true;
		}

		if (mouseover) {
			fill(prim);
		} else {
			fill(sec);
		}
		stroke(prim);
		strokeWeight(buh/10);
		rect(bux,buy,buw,buh,buh/2.5);

		if (mouseover) {
			fill(sec);
		} else {
			fill(prim);
		}
		textFont(mainfont,buh/2);
		if (ismobile) {
			textSize(buh/3);
		}
		textAlign(CENTER,CENTER);
		text(butext,bux,buy);

		if (ismobile && mouseover) {
			con.pressed = true;
			return con.pressed;
		}

		if (mouseover && m) {
			con.pressed = true;
			return con.pressed;
		}
		return con.pressed;
	};

	// Standard button layout
	standardbuttons = function() {
		button(buttons.next);
		if (buttons.next.pressed) {
			if (ismobile) {
				if (flevel < 0) {
					page += 1;
					flevel = 255;
				}
			} else if (flevel < 80) {
				page += 1;
				flevel = 255;
			}
		};

		button(buttons.prev);
		if (buttons.prev.pressed) {
			if (ismobile) {
				if (flevel < 0) {
					page -= 1;
					flevel = 255;
				}
			} else if (flevel < 80) {
				page -= 1;
				flevel = 255;
			}

		};
	};

	// Displays an image properly.
	displaypanel = function(img,x,y) {
		imageMode(CENTER);
		pushMatrix();
		translate(x,y);
		scale(0.001*height,0.001*height);
			image(img,0,0);
		popMatrix();
	};

	// Creates a full page
	displaypage = function(chap,number) {
		background(backg);
		displaypanel(chap[number],width/2,height/2);
		standardbuttons();
		fade();
	};
	// Loads an array with full pages
	loadpages = function(cha,targ) {
		for (i = 0; i < cha.length; i ++) {
			targ.push(function() {fcha= cha; fi= i; displaypage(fcha,fi)});
		};
		targ[cha.length] = function() {
			background(backg);
			textSize(height/5);
			fill(sec);
			text("Under Construction",width/2,height/2);
		};
	};

	loadpanels("chap1/",chapter1length,chapter1);

	pages = [
		function() {
			background(backg)

			displaypanel(logo,width/4,height/2)

			button(buttons.start)
			if (buttons.start.pressed==true) {
				page += 1
			}
		},

	];
	loadpages(chapter1,pages);
};

draw = function() {
	pages[page]();
	textSize(17);
	text(pages[2],width/2,height/2);
};

keyPressed = function() {
	keys[keyCode] = true;
};
keyReleased = function() {
	keys[keyCode] = false;
};
mousePressed = function() {
	m = true;
};
mouseReleased = function() {
	m = false;
};
}};
<|endoftext|>


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

traceur.define('codegeneration', function() {
  'use strict';

  var ObjectMap = traceur.util.ObjectMap;

  var ParseTreeValidator = traceur.syntax.ParseTreeValidator;
  var ProgramTree = traceur.syntax.trees.ProgramTree;
  var UniqueIdentifierGenerator = traceur.codegeneration.UniqueIdentifierGenerator;
  var ForEachTransformer = traceur.codegeneration.ForEachTransformer;
  var PropertyMethodAssignmentTransformer = traceur.codegeneration.PropertyMethodAssignmentTransformer;
  var PropertyNameShorthandTransformer = traceur.codegeneration.PropertyNameShorthandTransformer;
  var RestParameterTransformer = traceur.codegeneration.RestParameterTransformer;
  var DefaultParametersTransformer = traceur.codegeneration.DefaultParametersTransformer;
  var GeneratorTransformPass = traceur.codegeneration.GeneratorTransformPass;
  var DestructuringTransformer = traceur.codegeneration.DestructuringTransformer;
  var SpreadTransformer = traceur.codegeneration.SpreadTransformer;
  var BlockBindingTransformer = traceur.codegeneration.BlockBindingTransformer;
  var TraitTransformer = traceur.codegeneration.TraitTransformer;
  var ClassTransformer = traceur.codegeneration.ClassTransformer;
  var ModuleTransformer = traceur.codegeneration.ModuleTransformer;
  var GeneratorTransformPass = traceur.codegeneration.GeneratorTransformPass;
  var FreeVariableChecker = traceur.semantics.FreeVariableChecker;
  var ArrowFunctionTransformer = traceur.codegeneration.ArrowFunctionTransformer;

  var CLASS_DECLARATION = traceur.syntax.trees.ParseTreeType.CLASS_DECLARATION;
  var TRAIT_DECLARATION = traceur.syntax.trees.ParseTreeType.TRAIT_DECLARATION;

  /**
   * Transforms a Traceur file's ParseTree to a JS ParseTree.
   *
   * @param {ErrorReporter} reporter
   * @param {Project} project
   * @constructor
   */
  function ProgramTransformer(reporter, project) {
    this.project_ = project;
    this.reporter_ = reporter;
    this.results_ = new ObjectMap();
    this.identifierGenerator_ = new UniqueIdentifierGenerator();
    Object.freeze(this);
  }

  /**
   * @param {ErrorReporter} reporter
   * @param {Project} project
   * @return {ObjectMap}
   */
  ProgramTransformer.transform = function(reporter, project) {
    var transformer = new ProgramTransformer(reporter, project);
    transformer.transform_();
    return transformer.results_;
  };

  /**
   * @param {ErrorReporter} reporter
   * @param {Project} project
   * @param {SourceFile} sourceFile
   * @return {ObjectMap}
   */
  ProgramTransformer.transformFile = function(reporter, project, sourceFile) {
    var transformer = new ProgramTransformer(reporter, project);
    transformer.transformFile_(sourceFile);
    return transformer.results_;
  };

  /**
   * @param {ErrorReporter} reporter
   * @param {Project} project
   * @param {ModuleSymbol}
   * @param {SourceFile} sourceFile
   * @return {ObjectMap}
   */
  ProgramTransformer.transformFileAsModule = function(reporter, project,
                                                      module, sourceFile) {
    var transformer = new ProgramTransformer(reporter, project);
    transformer.transformFileAsModule_(module, sourceFile);
    return transformer.results_;
  };

  ProgramTransformer.prototype = {
    /**
     * @return {void}
     * @private
     */
    transform_: function() {
      this.project_.getSourceFiles().forEach(function(file) {
        this.transformFile_(file);
      }, this);
    },

    /**
     * @param {SourceFile} file
     * @return {void}
     * @private
     */
    transformFile_: function(file) {
      var result = this.transform(this.project_.getParseTree(file));
      this.results_.put(file, result);
    },

    /**
     * @param {ModuleSymbol} module
     * @param {SourceFile} file
     * @return {void}
     * @private
     */
    transformFileAsModule_: function(module, file) {
      var result = this.transformTree_(this.project_.getParseTree(file),
                                       module);
      this.results_.put(file, result);
    },

    /**
     * This is the root of the code generation pass.
     * Each pass translates one contruct from Traceur to standard JS constructs.
     * The order of the passes matters.
     *
     * @param {Program} tree
     * @return {ParseTree}
     */
    transform: function(tree) {
      return this.transformTree_(tree);
    },

    transformTree_: function(tree, opt_module) {
      if (!this.reporter_.hadError()) {
        ParseTreeValidator.validate(tree);
        tree = this.transformModules_(tree, opt_module);
      }
      // TODO: many of these simple, local transforms could happen in the same
      // tree pass
      if (!this.reporter_.hadError()) {
        ParseTreeValidator.validate(tree);
        tree = ArrowFunctionTransformer.transformTree(this.reporter_, tree);
      }
      if (!this.reporter_.hadError()) {
        ParseTreeValidator.validate(tree);
        tree = PropertyMethodAssignmentTransformer.transformTree(tree);
      }
      if (!this.reporter_.hadError()) {
        ParseTreeValidator.validate(tree);
        tree = PropertyNameShorthandTransformer.transformTree(tree);
      }
      if (!this.reporter_.hadError()) {
        ParseTreeValidator.validate(tree);
        tree = this.transformAggregates_(tree);
      }
      if (!this.reporter_.hadError()) {
        ParseTreeValidator.validate(tree);
        // foreach must come before destructuring and generator, or anything
        // that wants to use VariableBinder
        tree = ForEachTransformer.transformTree(
            this.identifierGenerator_, tree);
      }
      if (!this.reporter_.hadError()) {
        ParseTreeValidator.validate(tree);
        // rest parameters must come before generator
        tree = RestParameterTransformer.transformTree(tree);
      }
      if (!this.reporter_.hadError()) {
        ParseTreeValidator.validate(tree);
        // default parameters should come after rest parameter to get the
        // expected order in the transformed code.
        tree = DefaultParametersTransformer.transformTree(tree);
      }
      if (!this.reporter_.hadError()) {
        ParseTreeValidator.validate(tree);
        // generator must come after foreach and rest parameters
        tree = GeneratorTransformPass.transformTree(
            this.identifierGenerator_, this.reporter_, tree);
      }
      if (!this.reporter_.hadError()) {
        ParseTreeValidator.validate(tree);
        // destructuring must come after foreach and before block binding
        tree = DestructuringTransformer.transformTree(tree);
      }
      if (!this.reporter_.hadError()) {
        ParseTreeValidator.validate(tree);
        tree = SpreadTransformer.transformTree(tree);
      }
      if (!this.reporter_.hadError()) {
        ParseTreeValidator.validate(tree);
        tree = BlockBindingTransformer.transformTree(tree);
      }
      if (!this.reporter_.hadError()) {
        ParseTreeValidator.validate(tree);

        // Issue errors for any unbound variables
        FreeVariableChecker.checkProgram(this.reporter_, tree);
      }
      return tree;
    },

    /**
     * Transforms a program tree. If an optional module is passed in the
     * program is treated as a module body.
     * @param {Program} tree
     * @param {ModuleSymbol} module
     * @return {Program}
     * @private
     */
    transformModules_: function(tree, opt_module) {
      if (opt_module) {
        return ModuleTransformer.transformAsModule(opt_module, tree);
      } else {
        return ModuleTransformer.transform(this.project_, tree);
      }
    },

    /**
     * @param {Program} tree
     * @return {Program}
     * @private
     */
    transformAggregates_: function(tree) {
      return ClassTransformer.transform(this.reporter_, tree);
    }
  };

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

traceur.define('codegeneration', function() {
  'use strict';

  var ObjectMap = traceur.util.ObjectMap;

  var ParseTreeValidator = traceur.syntax.ParseTreeValidator;
  var ProgramTree = traceur.syntax.trees.ProgramTree;
  var UniqueIdentifierGenerator = traceur.codegeneration.UniqueIdentifierGenerator;
  var ForEachTransformer = traceur.codegeneration.ForEachTransformer;
  var PropertyMethodAssignmentTransformer = traceur.codegeneration.PropertyMethodAssignmentTransformer;
  var PropertyNameShorthandTransformer = traceur.codegeneration.PropertyNameShorthandTransformer;
  var RestParameterTransformer = traceur.codegeneration.RestParameterTransformer;
  var DefaultParametersTransformer = traceur.codegeneration.DefaultParametersTransformer;
  var GeneratorTransformPass = traceur.codegeneration.GeneratorTransformPass;
  var DestructuringTransformer = traceur.codegeneration.DestructuringTransformer;
  var SpreadTransformer = traceur.codegeneration.SpreadTransformer;
  var BlockBindingTransformer = traceur.codegeneration.BlockBindingTransformer;
  var TraitTransformer = traceur.codegeneration.TraitTransformer;
  var ClassTransformer = traceur.codegeneration.ClassTransformer;
  var ModuleTransformer = traceur.codegeneration.ModuleTransformer;
  var GeneratorTransformPass = traceur.codegeneration.GeneratorTransformPass;
  var FreeVariableChecker = traceur.semantics.FreeVariableChecker;
  var ArrowFunctionTransformer = traceur.codegeneration.ArrowFunctionTransformer;

  var CLASS_DECLARATION = traceur.syntax.trees.ParseTreeType.CLASS_DECLARATION;
  var TRAIT_DECLARATION = traceur.syntax.trees.ParseTreeType.TRAIT_DECLARATION;

  /**
   * Transforms a Traceur file's ParseTree to a JS ParseTree.
   *
   * @param {ErrorReporter} reporter
   * @param {Project} project
   * @constructor
   */
  function ProgramTransformer(reporter, project) {
    this.project_ = project;
    this.reporter_ = reporter;
    this.results_ = new ObjectMap();
    this.identifierGenerator_ = new UniqueIdentifierGenerator();
    Object.freeze(this);
  }

  /**
   * @param {ErrorReporter} reporter
   * @param {Project} project
   * @return {ObjectMap}
   */
  ProgramTransformer.transform = function(reporter, project) {
    var transformer = new ProgramTransformer(reporter, project);
    transformer.transform_();
    return transformer.results_;
  };

  /**
   * @param {ErrorReporter} reporter
   * @param {Project} project
   * @param {SourceFile} sourceFile
   * @return {ObjectMap}
   */
  ProgramTransformer.transformFile = function(reporter, project, sourceFile) {
    var transformer = new ProgramTransformer(reporter, project);
    transformer.transformFile_(sourceFile);
    return transformer.results_;
  };

  /**
   * @param {ErrorReporter} reporter
   * @param {Project} project
   * @param {ModuleSymbol}
   * @param {SourceFile} sourceFile
   * @return {ObjectMap}
   */
  ProgramTransformer.transformFileAsModule = function(reporter, project,
                                                      module, sourceFile) {
    var transformer = new ProgramTransformer(reporter, project);
    transformer.transformFileAsModule_(module, sourceFile);
    return transformer.results_;
  };

  ProgramTransformer.prototype = {
    /**
     * @return {void}
     * @private
     */
    transform_: function() {
      this.project_.getSourceFiles().forEach(function(file) {
        this.transformFile_(file);
      }, this);
    },

    /**
     * @param {SourceFile} file
     * @return {void}
     * @private
     */
    transformFile_: function(file) {
      var result = this.transform(this.project_.getParseTree(file));
      this.results_.put(file, result);
    },

    /**
     * @param {ModuleSymbol} module
     * @param {SourceFile} file
     * @return {void}
     * @private
     */
    transformFileAsModule_: function(module, file) {
      var result = this.transformTree_(this.project_.getParseTree(file),
                                       module);
      this.results_.put(file, result);
    },

    /**
     * This is the root of the code generation pass.
     * Each pass translates one contruct from Traceur to standard JS constructs.
     * The order of the passes matters.
     *
     * @param {Program} tree
     * @return {ParseTree}
     */
    transform: function(tree) {
      return this.transformTree_(tree);
    },

    transformTree_: function(tree, opt_module) {
      var reporter = this.reporter_;

      function chain(transformer) {
        if (!reporter.hadError()) {
          ParseTreeValidator.validate(tree);
          tree = transformer(tree) || tree;
        }
      }

      if (!this.reporter_.hadError()) {
        ParseTreeValidator.validate(tree);
        tree = this.transformModules_(tree, opt_module);
      }

      // TODO: many of these simple, local transforms could happen in the same
      // tree pass

      chain(ArrowFunctionTransformer.transformTree.bind(null, this.reporter_));
      chain(PropertyMethodAssignmentTransformer.transformTree);
      chain(PropertyNameShorthandTransformer.transformTree);
      chain(ClassTransformer.transform.bind(null, this.reporter_));

      // foreach must come before destructuring and generator, or anything
      // that wants to use VariableBinder
      chain(ForEachTransformer.transformTree.bind(null,
                                                  this.identifierGenerator_));

      // rest parameters must come before generator
      chain(RestParameterTransformer.transformTree);

      // default parameters should come after rest parameter to get the
      // expected order in the transformed code.
      chain(DefaultParametersTransformer.transformTree);

      // generator must come after foreach and rest parameters
      chain(GeneratorTransformPass.transformTree.bind(null,
                                                      this.identifierGenerator_,
                                                      this.reporter_));

      // destructuring must come after foreach and before block binding
      chain(DestructuringTransformer.transformTree);
      chain(SpreadTransformer.transformTree);
      chain(BlockBindingTransformer.transformTree);

      // Issue errors for any unbound variables
      chain(FreeVariableChecker.checkProgram.bind(null, this.reporter_));

      return tree;
    },

    /**
     * Transforms a program tree. If an optional module is passed in the
     * program is treated as a module body.
     * @param {Program} tree
     * @param {ModuleSymbol} module
     * @return {Program}
     * @private
     */
    transformModules_: function(tree, opt_module) {
      if (opt_module) {
        return ModuleTransformer.transformAsModule(opt_module, tree);
      } else {
        return ModuleTransformer.transform(this.project_, tree);
      }
    }
  };

  return {
    ProgramTransformer: ProgramTransformer
  };
});
<|endoftext|>


<commit_before>/**
 * GSS-API wrapper for Kerberos implementation. For now it's very
 * kerberos-specific. We can add machinery to make it generic if the
 * need ever arises.
 */
var gss = (function() {
    "use strict";

    var gss = { };

    /** @const */ gss.KRB5_MECHANISM = "1.2.840.113554.1.2.2";

    /** @const */ gss.NT_EXPORT_NAME = "1.3.6.1.5.6.4";
    /** @const */ gss.NT_HOSTBASED_SERVICE = "1.3.6.1.5.6.2";
    /** @const */ gss.NT_USER_NAME = "1.2.840.113554.1.2.1.1";

    /** @const */ gss.KRB5_NT_PRINCIPAL_NAME = "1.2.840.113554.1.2.2.1";
    /** @const */ gss.KRB5_NT_HOSTBASED_SERVICE_NAME = "1.2.840.113554.1.2.1.4";

    /** @const */ gss.S_BAD_BINDINGS = 1;
    /** @const */ gss.S_BAD_MECH = 2;
    /** @const */ gss.S_BAD_NAME = 3;
    /** @const */ gss.S_BAD_NAMETYPE = 4;
    /** @const */ gss.S_BAD_STATUS = 5;
    /** @const */ gss.S_BAD_SIG = 6;
    /** @const */ gss.S_CONTEXT_EXPIRED = 7;
    /** @const */ gss.S_CREDENTIALS_EXPIRED = 8;
    /** @const */ gss.S_DEFECTIVE_CREDENTIAL = 9;
    /** @const */ gss.S_DEFECTIVE_TOKEN = 10;
    /** @const */ gss.S_FAILURE = 11;
    /** @const */ gss.S_NO_CONTEXT = 12;
    /** @const */ gss.S_NO_CRED = 13;
    /** @const */ gss.S_BAD_QOP = 14;
    /** @const */ gss.S_UNAUTHORIZED = 15;
    /** @const */ gss.S_UNAVAILABLE = 16;
    /** @const */ gss.S_DUPLICATE_ELEMENT = 17;
    /** @const */ gss.S_NAME_NOT_MN = 18;

    /** @const */ gss.S_DUPLICATE_TOKEN = 19;
    /** @const */ gss.S_OLD_TOKEN = 20;
    /** @const */ gss.S_UNSEQ_TOKEN = 21;
    /** @const */ gss.S_GAP_TOKEN = 22;

    /**
     * @constructor
     * @param {number} major
     * @param {number} minor
     * @param {string} message
     */
    gss.Error = function(major, minor, message) {
        this.major = major;
        this.minor = minor;
        this.message = message;
    };
    /** @return {string} */
    gss.Error.prototype.toString = function() {
        return this.message;
    };

    /**
     * Creates a gss.Name that wraps a KDC.Principal.
     * @constructor
     * @param {KDC.Principal} principal
     */
    gss.Name = function(principal) {
        this.principal = principal;
    };
    /**
     * GSS_Import_name. For now just returns a gss.Name. If we want to
     * do some sort of host canonicalization, that may want a promise
     * object from Q.
     *
     * @param {string} data The input bytes.
     * @param {string} nameType An OID for the name type.
     * @return {gss.Name} The resulting name.
     */
    gss.Name.importName = function(data, nameType) {
        if (nameType === gss.NT_EXPORT_NAME) {
            // Strip off the header.
            if (data.length < 4)
                throw new gss.Error(gss.S_BAD_NAME, 0, "Bad format");
            if (data.substring(0, 2) != '\x04\x01')
                throw new gss.Error(gss.S_BAD_NAME, 0, "Bad TOK_ID");
            var mechOidLen = (data.charCodeAt(2) << 8) | data.charCodeAt(3);
            if (data.length < 4 + mechOidLen + 4)
                throw new gss.Error(gss.S_BAD_NAME, 0, "Bad format");
            try {
                var mechOid = asn1.OBJECT_IDENTIFIER.decodeDER(
                    data.substring(4, 4 + mechOidLen));
            } catch (e) {
                if (e instanceof asn1.Error)
                    throw new gss.Error(gss.S_BAD_NAME, 0, e.toString());
                throw e;
            }
            // We only support KRB5.
            if (mechOid !== gss.KRB5_MECHANISM)
                throw new gss.Error(gss.S_BAD_MECH, 0,
                                    "Only krb5 names supported");
            var nameLen =
                (data.charCodeAt(4 + mechOidLen) << 24) |
                (data.charCodeAt(4 + mechOidLen + 1) << 16) |
                (data.charCodeAt(4 + mechOidLen + 2) << 8) |
                data.charCodeAt(4 + mechOidLen + 3);
            if (data.length != (4 + mechOidLen + 4 + nameLen))
                throw new gss.Error(gss.S_BAD_NAME, 0, "Bad length");
            try {
                return new gss.Name(KDC.Principal.fromString(
                    data.substring(4 + mechOidLen + 4)));
            } catch (e) {
                throw new gss.Error(gss.S_BAD_NAME, 0, e);
            }
        } else if (nameType === gss.NT_HOSTBASED_SERVICE ||
                   nameType === gss.KRB5_NT_HOSTBASED_SERVICE_NAME) {
            // Format is service@hostname. Hostname is optional, but
            // for now require it. Probably the most reasonable
            // interpretation of "the canonicalized name of the local
            // host" is location.host, but meh.
            var at = data.indexOf("@");
            if (at < 0)
                throw new gss.Error(gss.S_BAD_NAME, 0,
                                    "Default host not supported");
            var service = data.substring(0, at);
            var host = data.substring(at + 1);
            // FIXME: Hostname canonicalization??
            return new gss.Name(new KDC.Principal({
                nameType: krb.KRB_NT_SRV_HST,
                nameString: [service, host]
            }, KDC.realm));
        } else if (nameType === gss.KRB5_NT_PRINCIPAL_NAME) {
            try {
                return new gss.Name(KDC.Principal.fromString(data));
            } catch (e) {
                throw new gss.Error(gss.S_BAD_NAME, 0, e);
            }
        } else if (nameType === gss.NT_USER_NAME) {
            return new gss.Name(new KDC.Principal({
                nameType: krb.KRB_NT_PRINCIPAL,
                nameString: [data]
            }, KDC.realm));
        } else {
            throw new gss.Error(gss.S_BAD_NAMETYPE, 0, "Bad nametype");
        }
    };
    gss.Name.prototype.canonicalize = function() {
        // TODO
    };
    /** @return {string} */
    gss.Name.prototype.exportName = function() {
        var tokId = "\x04\x01";
        var mechOid = asn1.OBJECT_IDENTIFIER.encodeDER(gss.KRB5_MECHANISM);
        var mechOidLen = String.fromCharCode(
            mechOid.length >>> 8,
            mechOid.length & 0xff);
        var name = this.principal.toString();
        var nameLen = String.fromCharCode(
            name.length >>> 24,
            (name.length >>> 16) & 0xff,
            (name.length >>> 8) & 0xff,
            name.length & 0xff);
        return tokId + mechOidLen + mechOid + nameLen + name;
    };

    /** @constructor */
    gss.Context = function() {
        // TODO...
    };

    return gss;
}());
<commit_msg>Import some minor status codes from RFC 1964<commit_after>/**
 * GSS-API wrapper for Kerberos implementation. For now it's very
 * kerberos-specific. We can add machinery to make it generic if the
 * need ever arises.
 */
var gss = (function() {
    "use strict";

    var gss = { };

    /** @const */ gss.NT_EXPORT_NAME = "1.3.6.1.5.6.4";
    /** @const */ gss.NT_HOSTBASED_SERVICE = "1.3.6.1.5.6.2";
    /** @const */ gss.NT_USER_NAME = "1.2.840.113554.1.2.1.1";

    /** @const */ gss.S_BAD_BINDINGS = 1;
    /** @const */ gss.S_BAD_MECH = 2;
    /** @const */ gss.S_BAD_NAME = 3;
    /** @const */ gss.S_BAD_NAMETYPE = 4;
    /** @const */ gss.S_BAD_STATUS = 5;
    /** @const */ gss.S_BAD_SIG = 6;
    /** @const */ gss.S_CONTEXT_EXPIRED = 7;
    /** @const */ gss.S_CREDENTIALS_EXPIRED = 8;
    /** @const */ gss.S_DEFECTIVE_CREDENTIAL = 9;
    /** @const */ gss.S_DEFECTIVE_TOKEN = 10;
    /** @const */ gss.S_FAILURE = 11;
    /** @const */ gss.S_NO_CONTEXT = 12;
    /** @const */ gss.S_NO_CRED = 13;
    /** @const */ gss.S_BAD_QOP = 14;
    /** @const */ gss.S_UNAUTHORIZED = 15;
    /** @const */ gss.S_UNAVAILABLE = 16;
    /** @const */ gss.S_DUPLICATE_ELEMENT = 17;
    /** @const */ gss.S_NAME_NOT_MN = 18;

    /** @const */ gss.S_DUPLICATE_TOKEN = 19;
    /** @const */ gss.S_OLD_TOKEN = 20;
    /** @const */ gss.S_UNSEQ_TOKEN = 21;
    /** @const */ gss.S_GAP_TOKEN = 22;

    /** @const */ gss.KRB5_MECHANISM = "1.2.840.113554.1.2.2";

    /** @const */ gss.KRB5_NT_PRINCIPAL_NAME = "1.2.840.113554.1.2.2.1";
    /** @const */ gss.KRB5_NT_HOSTBASED_SERVICE_NAME = "1.2.840.113554.1.2.1.4";

    /** @const */ gss.KRB5_S_G_BAD_SERVICE_NAME = 1;
    /** @const */ gss.KRB5_S_G_BAD_STRING_UID = 2;
    /** @const */ gss.KRB5_S_G_NOUSER = 3;
    /** @const */ gss.KRB5_S_G_VALIDATE_FAILED = 4;
    /** @const */ gss.KRB5_S_G_BUFFER_ALLOC = 5;
    /** @const */ gss.KRB5_S_G_BAD_MSG_CTX = 6;
    /** @const */ gss.KRB5_S_G_WRONG_SIZE = 7;
    /** @const */ gss.KRB5_S_G_BAD_USAGE = 8;
    /** @const */ gss.KRB5_S_G_UNKNOWN_QOP = 9;

    /** @const */ gss.KRB5_S_KG_CCACHE_NOMATCH = 10;
    /** @const */ gss.KRB5_S_KG_KEYTAB_NOMATCH = 11;
    /** @const */ gss.KRB5_S_KG_TGT_MISSING = 12;
    /** @const */ gss.KRB5_S_KG_NO_SUBKEY = 13;
    /** @const */ gss.KRB5_S_KG_CONTEXT_ESTABLISHED = 14;
    /** @const */ gss.KRB5_S_KG_BAD_SIGN_TYPE = 15;
    /** @const */ gss.KRB5_S_KG_BAD_LENGTH = 16;
    /** @const */ gss.KRB5_S_KG_CTX_INCOMPLETE = 17;

    /**
     * @constructor
     * @param {number} major
     * @param {number} minor
     * @param {string} message
     */
    gss.Error = function(major, minor, message) {
        this.major = major;
        this.minor = minor;
        this.message = message;
    };
    /** @return {string} */
    gss.Error.prototype.toString = function() {
        return this.message;
    };

    /**
     * Creates a gss.Name that wraps a KDC.Principal.
     * @constructor
     * @param {KDC.Principal} principal
     */
    gss.Name = function(principal) {
        this.principal = principal;
    };
    /**
     * GSS_Import_name. For now just returns a gss.Name. If we want to
     * do some sort of host canonicalization, that may want a promise
     * object from Q.
     *
     * @param {string} data The input bytes.
     * @param {string} nameType An OID for the name type.
     * @return {gss.Name} The resulting name.
     */
    gss.Name.importName = function(data, nameType) {
        if (nameType === gss.NT_EXPORT_NAME) {
            // Strip off the header.
            if (data.length < 4)
                throw new gss.Error(gss.S_BAD_NAME, 0, "Bad format");
            if (data.substring(0, 2) != '\x04\x01')
                throw new gss.Error(gss.S_BAD_NAME, 0, "Bad TOK_ID");
            var mechOidLen = (data.charCodeAt(2) << 8) | data.charCodeAt(3);
            if (data.length < 4 + mechOidLen + 4)
                throw new gss.Error(gss.S_BAD_NAME, 0, "Bad format");
            try {
                var mechOid = asn1.OBJECT_IDENTIFIER.decodeDER(
                    data.substring(4, 4 + mechOidLen));
            } catch (e) {
                if (e instanceof asn1.Error)
                    throw new gss.Error(gss.S_BAD_NAME, 0, e.toString());
                throw e;
            }
            // We only support KRB5.
            if (mechOid !== gss.KRB5_MECHANISM)
                throw new gss.Error(gss.S_BAD_MECH, 0,
                                    "Only krb5 names supported");
            var nameLen =
                (data.charCodeAt(4 + mechOidLen) << 24) |
                (data.charCodeAt(4 + mechOidLen + 1) << 16) |
                (data.charCodeAt(4 + mechOidLen + 2) << 8) |
                data.charCodeAt(4 + mechOidLen + 3);
            if (data.length != (4 + mechOidLen + 4 + nameLen))
                throw new gss.Error(gss.S_BAD_NAME, 0, "Bad length");
            try {
                return new gss.Name(KDC.Principal.fromString(
                    data.substring(4 + mechOidLen + 4)));
            } catch (e) {
                throw new gss.Error(gss.S_BAD_NAME, 0, e);
            }
        } else if (nameType === gss.NT_HOSTBASED_SERVICE ||
                   nameType === gss.KRB5_NT_HOSTBASED_SERVICE_NAME) {
            // Format is service@hostname. Hostname is optional, but
            // for now require it. Probably the most reasonable
            // interpretation of "the canonicalized name of the local
            // host" is location.host, but meh.
            var at = data.indexOf("@");
            if (at < 0)
                throw new gss.Error(
                    gss.S_BAD_NAME, gss.KRB5_S_G_BAD_SERVICE_NAME,
                    "Default host not supported");
            var service = data.substring(0, at);
            var host = data.substring(at + 1);
            // FIXME: Hostname canonicalization??
            return new gss.Name(new KDC.Principal({
                nameType: krb.KRB_NT_SRV_HST,
                nameString: [service, host]
            }, KDC.realm));
        } else if (nameType === gss.KRB5_NT_PRINCIPAL_NAME) {
            try {
                return new gss.Name(KDC.Principal.fromString(data));
            } catch (e) {
                throw new gss.Error(gss.S_BAD_NAME, 0, e);
            }
        } else if (nameType === gss.NT_USER_NAME) {
            return new gss.Name(new KDC.Principal({
                nameType: krb.KRB_NT_PRINCIPAL,
                nameString: [data]
            }, KDC.realm));
        } else {
            throw new gss.Error(gss.S_BAD_NAMETYPE, 0, "Bad nametype");
        }
    };
    gss.Name.prototype.canonicalize = function() {
        // TODO
    };
    /** @return {string} */
    gss.Name.prototype.exportName = function() {
        var tokId = "\x04\x01";
        var mechOid = asn1.OBJECT_IDENTIFIER.encodeDER(gss.KRB5_MECHANISM);
        var mechOidLen = String.fromCharCode(
            mechOid.length >>> 8,
            mechOid.length & 0xff);
        var name = this.principal.toString();
        var nameLen = String.fromCharCode(
            name.length >>> 24,
            (name.length >>> 16) & 0xff,
            (name.length >>> 8) & 0xff,
            name.length & 0xff);
        return tokId + mechOidLen + mechOid + nameLen + name;
    };

    /** @constructor */
    gss.Context = function() {
        // TODO...
    };

    return gss;
}());
<|endoftext|>


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

import Loader from './Loader';
import PageRenderer from './PageRenderer';

const docSrc = (src) => '.' + src.replace(/^docs/, '');
const getDocContext = () => require.context('raw!../../../docs', true, /\.md$/);

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

  componentWillMount() {
    if (process.env.NODE_ENV === 'catalog-hot-development') {
      if (module.hot) {
        let ctx = getDocContext();
        this.setState({content: ctx(docSrc(this.context.page.src))});

        module.hot.accept(ctx.id, () => {
          ctx = getDocContext();
          this.setState({content: ctx(docSrc(this.context.page.src))});
        });
        return;
      }
    }

    this.fetchPageData(this.context.page.src);
  }

  componentWillReceiveProps(_, nextContext) {
    if (nextContext.page.src !== this.context.page.src) {
      if (process.env.NODE_ENV === 'catalog-hot-development') {
        if (module.hot) {
          const ctx = getDocContext();
          this.setState({content: ctx(docSrc(nextContext.page.src))});
          return;
        }
      }

      this.setState({content: null});
      this.fetchPageData(nextContext.page.src);
    }
  }

  render() {
    const content = this.state.content || <Loader />;
    return <PageRenderer content={content} />;
  }

  fetchPageData(url) {
    fetch(url)
      .then((response) => response.text())
      .then((text) => this.setState({content: text}))
      .catch((error) => {
        return this.setState({
          content: error
        });
      });
  }
}

PageContentLoader.contextTypes = {
  page: CatalogPropTypes.page.isRequired
};

export default PageContentLoader;
<commit_msg>Same-origin fetch credentials<commit_after>import React, {Component} from 'react';
import CatalogPropTypes from '../../CatalogPropTypes';

import Loader from './Loader';
import PageRenderer from './PageRenderer';

const docSrc = (src) => '.' + src.replace(/^docs/, '');
const getDocContext = () => require.context('raw!../../../docs', true, /\.md$/);

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

  componentWillMount() {
    if (process.env.NODE_ENV === 'catalog-hot-development') {
      if (module.hot) {
        let ctx = getDocContext();
        this.setState({content: ctx(docSrc(this.context.page.src))});

        module.hot.accept(ctx.id, () => {
          ctx = getDocContext();
          this.setState({content: ctx(docSrc(this.context.page.src))});
        });
        return;
      }
    }

    this.fetchPageData(this.context.page.src);
  }

  componentWillReceiveProps(_, nextContext) {
    if (nextContext.page.src !== this.context.page.src) {
      if (process.env.NODE_ENV === 'catalog-hot-development') {
        if (module.hot) {
          const ctx = getDocContext();
          this.setState({content: ctx(docSrc(nextContext.page.src))});
          return;
        }
      }

      this.setState({content: null});
      this.fetchPageData(nextContext.page.src);
    }
  }

  render() {
    const content = this.state.content || <Loader />;
    return <PageRenderer content={content} />;
  }

  fetchPageData(url) {
    fetch(url, {credentials: 'same-origin'})
      .then((response) => response.text())
      .then((text) => this.setState({content: text}))
      .catch((error) => {
        return this.setState({
          content: error
        });
      });
  }
}

PageContentLoader.contextTypes = {
  page: CatalogPropTypes.page.isRequired
};

export default PageContentLoader;
<|endoftext|>


<commit_before>import { ClientUser } from "discord.js";

module.exports = (client, message, args) =>
{
  let member = message.mentions.members.first();
  if(!member)
  {
    return message.reply("Por favor, informe um nome correto!");
  }
  else
  {
    //member.user. (com busca)
    //message.author. (sem busca)
    //client.user. (bot info)
    //member.user.tag
    message.channel.send({embed:{
          color: 3447003,
          author: {  name: member.nickname, icon_url: member.user.avatarURL },
          title: `Informações do usuário.`,  /*url: "http://google.com",*/ description: `${member.user.tag}`,
          fields:
          [
            { name: `Apelido: `, value: `${member.nickname}` /*value: "[link](http://google.com)."*/ },
            { name: `Nome cadastrado: `, value: `${member.user.username}` },
            { name: `Número do ID: `, value: `${member.user.id}` },
            { name: `Conta verificada: `, value: `${ClientUser.verified}` },
            { name: `Usuário premium: `, value: `${ClientUser.premium}` },
            { name: `Celular: `, value: `${ClientUser.mobile}` },
            { name: `BoT: `, value: `${member.user.bot}` },
            { name: `Data de criação: `, value: `${member.user.createdAt}` }
          ],
          timestamp: new Date(), footer: { icon_url: client.user.avatarURL , text: "© Verificado em" }
      }
    }).then(msg => {
      msg.delete(60000)
    });
  }
  message.delete(60000);
};<commit_msg><commit_after>module.exports = (client, message, args) =>
{
  let member = message.mentions.members.first();
  if(!member)
  {
    return message.reply("Por favor, informe um nome correto!");
  }
  else
  {
    //member.user. (com busca)
    //message.author. (sem busca)
    //client.user. (bot info)
    //member.user.tag
    message.channel.send({embed:{
          color: 3447003,
          author: {  name: member.nickname, icon_url: member.user.avatarURL },
          title: `Informações do usuário.`,  /*url: "http://google.com",*/ description: `${member.user.tag}`,
          fields:
          [
            { name: `Apelido: `, value: `${member.nickname}` /*value: "[link](http://google.com)."*/ },
            { name: `Nome cadastrado: `, value: `${member.user.username}` },
            { name: `Número do ID: `, value: `${member.user.id}` },
            { name: `Conta verificada: `, value: `${client.verified}` },
            { name: `Usuário premium: `, value: `${client.premium}` },
            { name: `Celular: `, value: `${client.mobile}` },
            { name: `BoT: `, value: `${member.user.bot}` },
            { name: `Data de criação: `, value: `${member.user.createdAt}` }
          ],
          timestamp: new Date(), footer: { icon_url: client.user.avatarURL , text: "© Verificado em" }
      }
    }).then(msg => {
      msg.delete(60000)
    });
  }
  message.delete(60000);
};<|endoftext|>


<commit_before>export const NO_NAME = 'NULL';
export const NO_ALPHA = Number.POSITIVE_INFINITY;

const MIN_ALPHA = 0;
const MAX_ALPHA = 1;

/**
 * Class representing a Color
 */
export default class Color {
  /**
   * Creates a color
   *
   * @protected
   * @param {string} name - The name of color space
   * @param {Iterable} components - The color components
   */
  constructor(name, components) {
    this.name = name;
    this.components = new Map(components);
  }

  /**
   * Returns a string representing an instance
   *
   * @public
   * @returns {string} Representation of an instance
   */
  toString() {
    const object = Object.create(null);
    object.name = this.name;
    object.components = Array.from(this.components.entries())
      .reduce((previous, entry) => {
        const key = entry[0];
        const value = entry[1];
        previous[Symbol.keyFor(key)] = value;
        return previous;
      }, Object.create(null));
    return JSON.stringify(object);
  }

  /**
   * Checks whether a property exists in the components or not
   *
   * @protected
   * @param {Symbol} property - Key of property
   * @returns {boolean} true if the components has a specified property as a key.
   */
  has(property) {
    return this.components.has(property);
  }

  /**
   * Returns a value which is mapped to a specified property.
   *
   * @protected
   * @param {Symbol} property - Key of property
   * @returns {number} A color value
   * @throws {TypeError} Argument property must exist in the component as a key.
   */
  get(property) {
    if (!this.has(property)) {
      throw new TypeError("Specified property does not exist in a component:" + this.components);
    }
    return this.components.get(property);
  }

  /**
   * Sets a value to a specified property
   *
   * @protected
   * @param {Symbol} property - Key of property
   * @param {number} value - A color value
   * @returns {Color} Instance of self
   * @throws {TypeError} Argument property must exist in the components as a key.
   * @throws {TypeError} Argument value must be a finite number.
   */
  set(property, value) {
    if (!this.has(property)) {
      throw new TypeError("Specified property does not exist in a component:" + this.components);
    }
    if (!Number.isFinite(value)) {
      throw new TypeError("Specified value must be a finite number");
    }
    this.components.set(property, value);
    return this;
  }

  /**
   * Creates an accessor for a specific property
   *
   * @protected
   * @param {Symbol} property - Key of property
   * @returns {function()} An accessor for a specified property
   */
  accessor(property) {
    // The below anonymous function works as a setter and a getter.
    return (value) => {
      if (!Number.isFinite(value)) {
        return this.get(property);
      }
      return this.set(property, value);
    };
  }

  /**
   * Clones an instance
   *
   * @public
   * @returns {Color} A cloned instance
   */
  clone() {
    const cloned = new this.constructor();
    cloned.name = this.name;
    cloned.components = new Map(this.components);
    return cloned;
  }

  /**
   * Compares this instance with a specified value
   *
   * @param {*} value - Any types of value
   * @returns {boolean} true if this instance is same as the value argument.
   */
  equals(value) {
    if (!(value instanceof Color)) {
      return false;
    }

    if (value.name !== this.name) {
      return false;
    }

    if (this.components.size !== value.components.size) {
      return false;
    }

    const entries = Array.from(this.components.entries());
    return entries.every((entry) => {
      const key = entry[0];
      return value.get(key) === entry[1];
    });
  }

  /**
   * Checks whether the instance is valid or invalid.
   *
   * @public
   * @returns {boolean} true if the instance is valid
   */
  isValid() {
    return false;
  }

  /**
   * Creates a new color which is darker than the current color.
   *
   * @public
   * @param {number} factor
   * @throws {TypeError} Argument factor must be within range 0 and 1
   */
  darken(factor) {
    if (!Number.isFinite(factor)) {
      throw new TypeError(`Argument factor(${factor}) must be a finite number`);
    }
  }

  /**
   * Creates a new color which is lighter than the current color.
   *
   * @public
   * @param {number} factor
   * @throws {TypeError} Argument factor must be within range 0 and 1
   */
  lighten(factor) {
    if (!Number.isFinite(factor)) {
      throw new TypeError("Factor(" + factor + ") must be a finite number");
    }
    if (factor === 0) {
      throw new TypeError("Factor(" + factor + ") must not be zero");
    }
  }

  /**
   * Converts color to a hex string
   *
   * @public
   * @returns {string} A hex string
   */
  hex() {
    const rgb = this.rgb();
    const values = [rgb.r(), rgb.g(), rgb.b()].map((value) => {
      const string = value.toString(16);
      if (string.length === 1) {
        return `0${string.toUpperCase()}`;
      }
      return string.toLowerCase();
    });
    return `#${values.join('')}`;
  }

  /**
   * Converts color to a css string
   *
   * @public
   * @returns {string} A css string
   */
  css() {
    return '';
  }

  /**
   * Converts color space to CMY
   *
   * @abstract
   * @public
   * @returns {Cmy} A CMY color
   */
  cmy() {
    throw new Error('This method must be implemented by a child class');
  }

  /**
   * Converts color space to CMYK
   *
   * @abstract
   * @public
   * @returns {Cmyk} A CMYK color
   */
  cmyk() {
    throw new Error('This method must be implemented by a child class');
  }

  /**
   * Converts color space to HSL
   *
   * @abstract
   * @public
   * @returns {Hsl} A HSL color
   */
  hsl() {
    throw new Error('This method must be implemented by a child class');
  }

  /**
   * Converts color space to HSV
   *
   * @abstract
   * @public
   * @returns {Hsl} A HSL color
   */
  hsv() {
    throw new Error('This method must be implemented by a child class');
  }

  /**
   * Converts color space to HWB
   *
   * @abstract
   * @public
   * @returns {Hwb} A HWB color
   */
  hwb() {
    throw new Error('This method must be implemented by a child class');
  }

  /**
   * Converts color space to RGB
   *
   * @abstract
   * @public
   * @returns {Rgb} A converted RGB color
   */
  rgb() {
    throw new Error('This method must be implemented by a child class');
  }

  /**
   * Checks whether the alpha value is set or not
   *
   * @protected
   * @param {Symbol} key - The key of alpha value
   * @returns {boolean} true if the alpha value is set
   * @see isValidAlpha
   */
  hasAlpha(key) {
    const value = this.components.get(key);
    return value !== NO_ALPHA;
  }

  /**
   * Checks whether the alpha value is set or not
   *
   * @protected
   * @param {Symbol} key - The key of alpha value
   * @returns {boolean} true if the alpha value is valid
   * @see hasAlpha
   */
  isValidAlpha(key) {
    const value = this.components.get(key);
    return MIN_ALPHA <= value && value <= MAX_ALPHA;
  }

  /**
   * Creates an invalid instance
   *
   * @public
   * @static
   * @returns {Color} An invalid color
   */
  static invalid() {
    return new Color(NO_NAME, []);
  }
}<commit_msg>Fixed JSDoc<commit_after>export const NO_NAME = 'NULL';
export const NO_ALPHA = Number.POSITIVE_INFINITY;

const MIN_ALPHA = 0;
const MAX_ALPHA = 1;

/**
 * Class representing a Color
 */
export default class Color {
  /**
   * Creates a color
   *
   * @protected
   * @param {string} name - The name of color space
   * @param {Iterable} components - The color components
   */
  constructor(name, components) {
    this.name = name;
    this.components = new Map(components);
  }

  /**
   * Returns a string representing an instance
   *
   * @public
   * @returns {string} Representation of an instance
   */
  toString() {
    const object = Object.create(null);
    object.name = this.name;
    object.components = Array.from(this.components.entries())
      .reduce((previous, entry) => {
        const key = entry[0];
        const value = entry[1];
        previous[Symbol.keyFor(key)] = value;
        return previous;
      }, Object.create(null));
    return JSON.stringify(object);
  }

  /**
   * Checks whether a property exists in the components or not
   *
   * @protected
   * @param {Symbol} property - Key of property
   * @returns {boolean} true if the components has a specified property as a key.
   */
  has(property) {
    return this.components.has(property);
  }

  /**
   * Returns a value which is mapped to a specified property.
   *
   * @protected
   * @param {Symbol} property - Key of property
   * @returns {number} A color value
   * @throws {TypeError} Argument property must exist in the component as a key.
   */
  get(property) {
    if (!this.has(property)) {
      throw new TypeError("Specified property does not exist in a component:" + this.components);
    }
    return this.components.get(property);
  }

  /**
   * Sets a value to a specified property
   *
   * @protected
   * @param {Symbol} property - Key of property
   * @param {number} value - A color value
   * @returns {Color} Instance of self
   * @throws {TypeError} Argument property must exist in the components as a key.
   * @throws {TypeError} Argument value must be a finite number.
   */
  set(property, value) {
    if (!this.has(property)) {
      throw new TypeError("Specified property does not exist in a component:" + this.components);
    }
    if (!Number.isFinite(value)) {
      throw new TypeError("Specified value must be a finite number");
    }
    this.components.set(property, value);
    return this;
  }

  /**
   * Creates an accessor for a specific property
   *
   * @protected
   * @param {Symbol} property - Key of property
   * @returns {function()} An accessor for a specified property
   */
  accessor(property) {
    // The below anonymous function works as a setter and a getter.
    return (value) => {
      if (!Number.isFinite(value)) {
        return this.get(property);
      }
      return this.set(property, value);
    };
  }

  /**
   * Clones an instance
   *
   * @public
   * @returns {Color} A cloned instance
   */
  clone() {
    const cloned = new this.constructor();
    cloned.name = this.name;
    cloned.components = new Map(this.components);
    return cloned;
  }

  /**
   * Compares this instance with a specified value
   *
   * @param {*} value - Any types of value
   * @returns {boolean} true if this instance is same as the value argument.
   */
  equals(value) {
    if (!(value instanceof Color)) {
      return false;
    }

    if (value.name !== this.name) {
      return false;
    }

    if (this.components.size !== value.components.size) {
      return false;
    }

    const entries = Array.from(this.components.entries());
    return entries.every((entry) => {
      const key = entry[0];
      return value.get(key) === entry[1];
    });
  }

  /**
   * Checks whether the instance is valid or invalid.
   *
   * @public
   * @returns {boolean} true if the instance is valid
   */
  isValid() {
    return false;
  }

  /**
   * Creates a new color which is darker than the current color.
   *
   * @public
   * @param {number} factor
   * @throws {TypeError} Argument factor must be within range 0 and 1
   */
  darken(factor) {
    if (!Number.isFinite(factor)) {
      throw new TypeError(`Argument factor(${factor}) must be a finite number`);
    }
  }

  /**
   * Creates a new color which is lighter than the current color.
   *
   * @public
   * @param {number} factor
   * @throws {TypeError} Argument factor must be within range 0 and 1
   */
  lighten(factor) {
    if (!Number.isFinite(factor)) {
      throw new TypeError("Factor(" + factor + ") must be a finite number");
    }
    if (factor === 0) {
      throw new TypeError("Factor(" + factor + ") must not be zero");
    }
  }

  /**
   * Converts color to a hex string
   *
   * @public
   * @returns {string} A hex string
   */
  hex() {
    const rgb = this.rgb();
    const values = [rgb.r(), rgb.g(), rgb.b()].map((value) => {
      const string = value.toString(16);
      if (string.length === 1) {
        return `0${string.toUpperCase()}`;
      }
      return string.toLowerCase();
    });
    return `#${values.join('')}`;
  }

  /**
   * Converts color to a css string
   *
   * @public
   * @returns {string} A css string
   */
  css() {
    return '';
  }

  /**
   * Converts color space to CMY
   *
   * @abstract
   * @public
   * @returns {Cmy} A CMY color
   */
  cmy() {
    throw new Error('This method must be implemented by a child class');
  }

  /**
   * Converts color space to CMYK
   *
   * @abstract
   * @public
   * @returns {Cmyk} A CMYK color
   */
  cmyk() {
    throw new Error('This method must be implemented by a child class');
  }

  /**
   * Converts color space to HSL
   *
   * @abstract
   * @public
   * @returns {Hsl} A HSL color
   */
  hsl() {
    throw new Error('This method must be implemented by a child class');
  }

  /**
   * Converts color space to HSV
   *
   * @abstract
   * @public
   * @returns {Hsv} A HSV color
   */
  hsv() {
    throw new Error('This method must be implemented by a child class');
  }

  /**
   * Converts color space to HWB
   *
   * @abstract
   * @public
   * @returns {Hwb} A HWB color
   */
  hwb() {
    throw new Error('This method must be implemented by a child class');
  }

  /**
   * Converts color space to RGB
   *
   * @abstract
   * @public
   * @returns {Rgb} A converted RGB color
   */
  rgb() {
    throw new Error('This method must be implemented by a child class');
  }

  /**
   * Checks whether the alpha value is set or not
   *
   * @protected
   * @param {Symbol} key - The key of alpha value
   * @returns {boolean} true if the alpha value is set
   * @see isValidAlpha
   */
  hasAlpha(key) {
    const value = this.components.get(key);
    return value !== NO_ALPHA;
  }

  /**
   * Checks whether the alpha value is set or not
   *
   * @protected
   * @param {Symbol} key - The key of alpha value
   * @returns {boolean} true if the alpha value is valid
   * @see hasAlpha
   */
  isValidAlpha(key) {
    const value = this.components.get(key);
    return MIN_ALPHA <= value && value <= MAX_ALPHA;
  }

  /**
   * Creates an invalid instance
   *
   * @public
   * @static
   * @returns {Color} An invalid color
   */
  static invalid() {
    return new Color(NO_NAME, []);
  }
}<|endoftext|>