<commit_before>var frequencies, pivots;

/**
 * for each node, calculate the derivative of the frequency tranjectory. if none exists, copy parent
**/
function calcDfreq(node, freq_ii){
	if (typeof node.children != "undefined") {
		for (var i1=0; i1<node.children.length; i1++) {
			if (typeof node.children[i1].freq != "undefined") {
				if (node.children[i1].freq["global"] != "undefined"){
					var tmp_freq = node.children[i1].freq["global"]
					node.children[i1].dfreq = 0.5*(tmp_freq[freq_ii] - tmp_freq[freq_ii-dfreq_dn])/(tmp_freq[freq_ii] + tmp_freq[freq_ii-dfreq_dn] + 0.1);
				} else {
					node.children[i1].dfreq = node.dfreq;
				}
			}
			calcDfreq(node.children[i1], freq_ii);
		}
	}
};
function parse_gt_string(gt){
	separate_plots = gt.split(',');
	mutations = separate_plots.map(
		function (d) {	var tmp = d.split(/[\s//]/); //FIXME: make more inclusive
						var region;
						var positions = [];
						for (var i=0; i<tmp.length; i++){
							if (contains(["EU","NA","AS","OC"], tmp[i])){
								region = tmp[i];
							}else{
								if (tmp[i].length>0) positions.push(tmp[i]);
							}
						}
						if (typeof region == "undefined") region="global";
						// sort of this is a multi mutation genotype
						if (positions.length>1){
							positions.sort(function (a,b){
								return parseInt(a.substring(0,a.length-1)) - parseInt(b.substring(0,b.length-1));
							});
						}
						return [region, positions.join('/')];});
	return mutations;
};

/**
loops over all genotypes from a certain region and sums the frequency contributions
of the genotype matches at the specified positions
**/
function get_frequencies(region, gt){
	var freq = [];
	for (var pi=0; pi<pivots.length; pi++){freq[freq.length]=0;}
	if (frequencies["clades"][region][gt.toLowerCase()]!=undefined) {
		console.log(gt+" found as clade");
		for (var pi=0; pi<freq.length; pi++){
			freq[pi]+=frequencies["clades"][region][gt.toLowerCase()][pi];
		}
	}
	else if ((typeof frequencies["genotypes"] !="undefined") && (frequencies["genotypes"][region][gt]!=undefined)) {
		console.log(gt+" found as genotype");
		for (var pi=0; pi<freq.length; pi++){
			freq[pi]+=frequencies["genotypes"][region][gt][pi];
		}
	}else if (frequencies["mutations"][region][gt]!=undefined) {
		console.log(gt+" found as mutation");
		for (var pi=0; pi<freq.length; pi++){
			freq[pi]+=frequencies["mutations"][region][gt][pi];
		}
	}
	return freq.map(function (d) {return Math.round(d*100)/100;});
};

function make_gt_chart(gt){
	var tmp_data = [];
	var tmp_trace = ['x'];
	var tmp_colors = {};
	tmp_data.push(tmp_trace.concat(pivots));
	gt.forEach(function (d, i) {
		var region = d[0];
		var genotype = d[1];
		var freq = get_frequencies(region, genotype);
		var tmp_trace = genotype.toString().replace(/,/g, ', ');
		if (region != "global") {
			tmp_trace = region + ':\t' + tmp_trace;
		}
		tmp_data.push([tmp_trace].concat(freq));
		tmp_colors[tmp_trace] = genotypeColors[i];
	});
	console.log(tmp_colors);
	gt_chart.load({
       	columns: tmp_data,
       	unload: true
	});
	gt_chart.data.colors(tmp_colors);
}

function addClade(d) {
	if (typeof gt_chart != "undefined"){
		var plot_data = [['x'].concat(rootNode["pivots"])];
		var reg = "global";
		if ((typeof d.target.freq !="undefined" )&&(d.target.freq[reg] != "undefined")){
			plot_data[plot_data.length] = [reg].concat(d.target.freq[reg]);
		}
		if (plot_data.length > 1) {
			if (plot_data[1][0] == "global") {
				plot_data[1][0] = "clade";
			}
		}
		gt_chart.load({
	       	columns: plot_data
		});
	}
}

function removeClade() {
	if (typeof gt_chart != "undefined"){
		gt_chart.unload({
	       	ids: ["clade"]
		});
	}
}

width = parseInt(d3.select(".freqplot-container").style("width"), 10);
var position = "right";
if (width < 600) {
	position = "bottom";
}

var gt_chart = c3.generate({
	bindto: '#gtchart',
	size: {width: width, height: 350},
	legend: {position: position},
  	color: {
        pattern: genotypeColors
    },
	axis: {
		y: {
			label: {
				text: 'frequency',
				position: 'outer-middle'
			},
			tick: {
				values: [0.0, 0.2, 0.4, 0.6, 0.8, 1.0],
				outer: false
			},
            min: 0,
			max: 1
		},
		x: {
			label: {
				text: 'time',
				position: 'outer-center'
			},
			tick: {
				values: time_ticks,
				outer: false
			}
		}
	},
	data: {
		x: 'x',
		columns: [],
	}
});

function contains(arr, obj) {
    for(var i=0; i<arr.length; i++) {
        if (arr[i] == obj) return true;
    }
}

d3.json(path + file_prefix + "frequencies.json", function(error, json){
	console.log(error);
	frequencies = json;
	pivots= frequencies["mutations"]["global"]["pivots"].map(function (d) {return Math.round(parseFloat(d)*100)/100;});
	var ticks = [Math.round(pivots[0])];
	var tick_step = Math.round((pivots[pivots.length-1]-pivots[0])/6*10)/10;
	while (ticks[ticks.length-1]<pivots[pivots.length-1]){
		ticks.push(Math.round((ticks[ticks.length-1]+tick_step)*10)/10);
	}
	//gt_chart.axis.x.values = ticks;
	/**
		parses a genotype string into region and positions
	**/

	var ent = [['x'],['']];
	for (var ii=0;ii<frequencies["entropy"].length;ii+=1){
		if (Math.round(10000*frequencies["entropy"][ii][1])/10000>0.05){
			ent[1].push(Math.round(10000*frequencies["entropy"][ii][1])/10000);
			ent[0].push(ii+1);
		}
	}

	var entropy_chart = c3.generate({
		bindto: '#entropy',
		size: {width: width, height: 350},
		legend: {show: true},
		color: {pattern: [genotypeColors[8]]},
		axis: {
			y: {
				label: {
					text: 'variability',
					position: 'outer-middle'
				}
			},
			x: {
				label: {
					text: 'position',
					position: 'outer-right'
				},
				tick: {
					outer: false,
					values: [100,200,300,400,500]
				}
			}
		},
		data: {
			x: 'x',
			columns: ent,
			type: "bar",
			onclick: function (d,i) {
						console.log(d);
		            	if (frequencies["entropy"][d.x-1][2].length>1){
		            		var tmp = [];
		            		for (var ii=0;ii<frequencies["entropy"][d.x-1][2].length;ii+=1){
								tmp.push(["global",d.x+frequencies["entropy"][d.x-1][2][ii]]);
		            		}
		            		colorBy = "genotype";
		            		colorByGenotypePosition([d.x-1]);
		            	}
		            }
		},
		bar: {width: 2},
	    tooltip: {
	        format: {
	            title: function (d) {
	            	return 'Position ' + d + frequencies["entropy"][d-1][2].join(","); },
	            value: function (value, ratio, id) {
	                return "Variability: "+value;
	            }
	        }
		},
	});

	d3.select("#plotfreq")
		.on("click", function (){
			gt = parse_gt_string(document.getElementById("gtspec").value);
			make_gt_chart(gt);
		});
	make_gt_chart(parse_gt_string(document.getElementById("gtspec").value));
});
<commit_msg>Update color by text when clicking on entropy plot.<commit_after>var frequencies, pivots;

/**
 * for each node, calculate the derivative of the frequency tranjectory. if none exists, copy parent
**/
function calcDfreq(node, freq_ii){
	if (typeof node.children != "undefined") {
		for (var i1=0; i1<node.children.length; i1++) {
			if (typeof node.children[i1].freq != "undefined") {
				if (node.children[i1].freq["global"] != "undefined"){
					var tmp_freq = node.children[i1].freq["global"]
					node.children[i1].dfreq = 0.5*(tmp_freq[freq_ii] - tmp_freq[freq_ii-dfreq_dn])/(tmp_freq[freq_ii] + tmp_freq[freq_ii-dfreq_dn] + 0.1);
				} else {
					node.children[i1].dfreq = node.dfreq;
				}
			}
			calcDfreq(node.children[i1], freq_ii);
		}
	}
};
function parse_gt_string(gt){
	separate_plots = gt.split(',');
	mutations = separate_plots.map(
		function (d) {	var tmp = d.split(/[\s//]/); //FIXME: make more inclusive
						var region;
						var positions = [];
						for (var i=0; i<tmp.length; i++){
							if (contains(["EU","NA","AS","OC"], tmp[i])){
								region = tmp[i];
							}else{
								if (tmp[i].length>0) positions.push(tmp[i]);
							}
						}
						if (typeof region == "undefined") region="global";
						// sort of this is a multi mutation genotype
						if (positions.length>1){
							positions.sort(function (a,b){
								return parseInt(a.substring(0,a.length-1)) - parseInt(b.substring(0,b.length-1));
							});
						}
						return [region, positions.join('/')];});
	return mutations;
};

/**
loops over all genotypes from a certain region and sums the frequency contributions
of the genotype matches at the specified positions
**/
function get_frequencies(region, gt){
	var freq = [];
	for (var pi=0; pi<pivots.length; pi++){freq[freq.length]=0;}
	if (frequencies["clades"][region][gt.toLowerCase()]!=undefined) {
		console.log(gt+" found as clade");
		for (var pi=0; pi<freq.length; pi++){
			freq[pi]+=frequencies["clades"][region][gt.toLowerCase()][pi];
		}
	}
	else if ((typeof frequencies["genotypes"] !="undefined") && (frequencies["genotypes"][region][gt]!=undefined)) {
		console.log(gt+" found as genotype");
		for (var pi=0; pi<freq.length; pi++){
			freq[pi]+=frequencies["genotypes"][region][gt][pi];
		}
	}else if (frequencies["mutations"][region][gt]!=undefined) {
		console.log(gt+" found as mutation");
		for (var pi=0; pi<freq.length; pi++){
			freq[pi]+=frequencies["mutations"][region][gt][pi];
		}
	}
	return freq.map(function (d) {return Math.round(d*100)/100;});
};

function make_gt_chart(gt){
	var tmp_data = [];
	var tmp_trace = ['x'];
	var tmp_colors = {};
	tmp_data.push(tmp_trace.concat(pivots));
	gt.forEach(function (d, i) {
		var region = d[0];
		var genotype = d[1];
		var freq = get_frequencies(region, genotype);
		var tmp_trace = genotype.toString().replace(/,/g, ', ');
		if (region != "global") {
			tmp_trace = region + ':\t' + tmp_trace;
		}
		tmp_data.push([tmp_trace].concat(freq));
		tmp_colors[tmp_trace] = genotypeColors[i];
	});
	console.log(tmp_colors);
	gt_chart.load({
       	columns: tmp_data,
       	unload: true
	});
	gt_chart.data.colors(tmp_colors);
}

function addClade(d) {
	if (typeof gt_chart != "undefined"){
		var plot_data = [['x'].concat(rootNode["pivots"])];
		var reg = "global";
		if ((typeof d.target.freq !="undefined" )&&(d.target.freq[reg] != "undefined")){
			plot_data[plot_data.length] = [reg].concat(d.target.freq[reg]);
		}
		if (plot_data.length > 1) {
			if (plot_data[1][0] == "global") {
				plot_data[1][0] = "clade";
			}
		}
		gt_chart.load({
	       	columns: plot_data
		});
	}
}

function removeClade() {
	if (typeof gt_chart != "undefined"){
		gt_chart.unload({
	       	ids: ["clade"]
		});
	}
}

width = parseInt(d3.select(".freqplot-container").style("width"), 10);
var position = "right";
if (width < 600) {
	position = "bottom";
}

var gt_chart = c3.generate({
	bindto: '#gtchart',
	size: {width: width, height: 350},
	legend: {position: position},
  	color: {
        pattern: genotypeColors
    },
	axis: {
		y: {
			label: {
				text: 'frequency',
				position: 'outer-middle'
			},
			tick: {
				values: [0.0, 0.2, 0.4, 0.6, 0.8, 1.0],
				outer: false
			},
            min: 0,
			max: 1
		},
		x: {
			label: {
				text: 'time',
				position: 'outer-center'
			},
			tick: {
				values: time_ticks,
				outer: false
			}
		}
	},
	data: {
		x: 'x',
		columns: [],
	}
});

function contains(arr, obj) {
    for(var i=0; i<arr.length; i++) {
        if (arr[i] == obj) return true;
    }
}

d3.json(path + file_prefix + "frequencies.json", function(error, json){
	console.log(error);
	frequencies = json;
	pivots= frequencies["mutations"]["global"]["pivots"].map(function (d) {return Math.round(parseFloat(d)*100)/100;});
	var ticks = [Math.round(pivots[0])];
	var tick_step = Math.round((pivots[pivots.length-1]-pivots[0])/6*10)/10;
	while (ticks[ticks.length-1]<pivots[pivots.length-1]){
		ticks.push(Math.round((ticks[ticks.length-1]+tick_step)*10)/10);
	}
	//gt_chart.axis.x.values = ticks;
	/**
		parses a genotype string into region and positions
	**/

	var ent = [['x'],['']];
	for (var ii=0;ii<frequencies["entropy"].length;ii+=1){
		if (Math.round(10000*frequencies["entropy"][ii][1])/10000>0.05){
			ent[1].push(Math.round(10000*frequencies["entropy"][ii][1])/10000);
			ent[0].push(ii+1);
		}
	}

	var entropy_chart = c3.generate({
		bindto: '#entropy',
		size: {width: width, height: 350},
		legend: {show: true},
		color: {pattern: [genotypeColors[8]]},
		axis: {
			y: {
				label: {
					text: 'variability',
					position: 'outer-middle'
				}
			},
			x: {
				label: {
					text: 'position',
					position: 'outer-right'
				},
				tick: {
					outer: false,
					values: [100,200,300,400,500]
				}
			}
		},
		data: {
			x: 'x',
			columns: ent,
			type: "bar",
			onclick: function (d,i) {
						console.log(d);
		            	if (frequencies["entropy"][d.x-1][2].length>1){
		            		var tmp = [];
		            		for (var ii=0;ii<frequencies["entropy"][d.x-1][2].length;ii+=1){
								tmp.push(["global",d.x+frequencies["entropy"][d.x-1][2][ii]]);
		            		}
		            		colorBy = "genotype";
		            		colorByGenotypePosition([d.x-1]);
		            		d3.select("#gt-color").property("value", d.x);
		            	}
		            }
		},
		bar: {width: 2},
	    tooltip: {
	        format: {
	            title: function (d) {
	            	return 'Position ' + d + frequencies["entropy"][d-1][2].join(","); },
	            value: function (value, ratio, id) {
	                return "Variability: "+value;
	            }
	        }
		},
	});

	d3.select("#plotfreq")
		.on("click", function (){
			gt = parse_gt_string(document.getElementById("gtspec").value);
			make_gt_chart(gt);
		});
	make_gt_chart(parse_gt_string(document.getElementById("gtspec").value));
});
<|endoftext|>


<commit_before>// Denis Molodtsov 2017
// Displays attachments callouts for list items

// Deployment steps:
// 1) reference JSLink ~site/_catalogs/masterpage/attachments/callouts.js
// 2) reference css file /_catalogs/masterpage/attachments/callouts.css

SP.SOD.executeFunc("clienttemplates.js", "SPClientTemplates", function () {

    function getBaseHtml(ctx) {
        return SPClientTemplates["_defaultTemplates"].Fields.default.all.all[ctx.CurrentFieldSchema.FieldType][ctx.BaseViewID](ctx);
    }

    function init() {

        SPClientTemplates.TemplateManager.RegisterTemplateOverrides({

            OnPreRender: function (ctx) {
                if (typeof jQuery == 'function')
                    NotifyScriptLoadedAndExecuteWaitingJobs("jquery.js");
                else if (LoadSodByKey('jquery.js', null) == Sods.missing)
                    RegisterSod('jquery.js', '//code.jquery.com/jquery-1.12.4.js');
                SP.SOD.executeFunc("jquery.js", "jQuery", function () {
                });

            },

            Templates: {
            },

            OnPostRender: function (ctx) {
                var rows = ctx.ListData.Row;
                for (var i = 0; i < rows.length; i++) {
                    var rowElementId = GenerateIIDForListItem(ctx, rows[i]);
                    var tr = document.getElementById(rowElementId);
                    var listId = _spPageContextInfo.listId.replace('{', '').replace('}', '');
                    $.ajax({
                        url: _spPageContextInfo.webServerRelativeUrl + "/_api/Web/Lists(guid'" + listId + "')/items/getById(" + rows[i].ID + ")/attachmentFiles",
                        method: "GET",
                        tr: tr,
                        headers: {
                            accept: "application/json;odata=verbose"
                        },
                        success: function (result) {
                            $(this.tr).hover(handlerIn, handlerOut);
                            if (result.d.results.length > 0) {
                                var calloutContainer = jQuery("

");
                                calloutContainer.appendTo(this.tr);
                                calloutContainer.append("

  Attachments</h4
");
                                for (var i = 0; i < result.d.results.length; i++) {
                                    var attachment = result.d.results[i];
                                    calloutContainer.append("
" + attachment.FileName + "
");
                                }
                            }

                            function handlerIn(event) {
                                $("[idCallout='" + $(event.currentTarget).attr('id') + "']").show();
                            }
                            function handlerOut(event) {
                                $("[idCallout='" + $(event.currentTarget).attr('id') + "']").hide();
                            }

                        }
                    })
                }

            },

            ListTemplateType: 100

        });
    }

    RegisterModuleInit(SPClientTemplates.Utility.ReplaceUrlTokens("~site/_catalogs/masterpage/attachments/callouts.js"), init);
    init();

});
<commit_msg>changed comments<commit_after>// Denis Molodtsov 2017
// Displays attachments callouts for list items

// Deployment steps:
// 1) reference JSLink ~site/_catalogs/masterpage/attachments/callouts.js
// 2) reference css file /_catalogs/masterpage/attachments/callouts.css

SP.SOD.executeFunc("clienttemplates.js", "SPClientTemplates", function () {

    function getBaseHtml(ctx) {
        return SPClientTemplates["_defaultTemplates"].Fields.default.all.all[ctx.CurrentFieldSchema.FieldType][ctx.BaseViewID](ctx);
    }

    function init() {

        SPClientTemplates.TemplateManager.RegisterTemplateOverrides({

            OnPreRender: function (ctx) {
                if (typeof jQuery == 'function')
                    NotifyScriptLoadedAndExecuteWaitingJobs("jquery.js");
                else if (LoadSodByKey('jquery.js', null) == Sods.missing)
                    RegisterSod('jquery.js', '//code.jquery.com/jquery-1.12.4.js');
                SP.SOD.executeFunc("jquery.js", "jQuery", function () {
                });

            },

            Templates: {
            },

            OnPostRender: function (ctx) {
                var rows = ctx.ListData.Row;
                for (var i = 0; i < rows.length; i++) {
                    var rowElementId = GenerateIIDForListItem(ctx, rows[i]);
                    var tr = document.getElementById(rowElementId);
                    var listId = _spPageContextInfo.listId.replace('{', '').replace('}', '');
                    $.ajax({
                        url: _spPageContextInfo.webServerRelativeUrl + "/_api/Web/Lists(guid'" + listId + "')/items/getById(" + rows[i].ID + ")/attachmentFiles",
                        method: "GET",
                        tr: tr,
                        headers: {
                            accept: "application/json;odata=verbose"
                        },
                        success: function (result) {
                            $(this.tr).hover(handlerIn, handlerOut);
                            if (result.d.results.length > 0) {
                                var calloutContainer = jQuery("

");
                                calloutContainer.appendTo(this.tr);
                                calloutContainer.append("

  Attachments</h4
");
                                for (var i = 0; i < result.d.results.length; i++) {
                                    var attachment = result.d.results[i];
                                    calloutContainer.append("
" + attachment.FileName + "
");
                                }
                            }

                            function handlerIn(event) {
                                $("[idCallout='" + $(event.currentTarget).attr('id') + "']").show();
                            }
                            function handlerOut(event) {
                                $("[idCallout='" + $(event.currentTarget).attr('id') + "']").hide();
                            }

                        }
                    })
                }

            },

            //ListTemplateType: 100

        });
    }

    RegisterModuleInit(SPClientTemplates.Utility.ReplaceUrlTokens("~site/_catalogs/masterpage/attachments/callouts.js"), init);
    init();

});
<|endoftext|>


<commit_before>!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.Clay=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
(function(e){var n,r,t,i,o,u,c,a,s,l,p,w;r=require("promiz"),i=(e.env.TRUSTED_DOMAIN||"clay.io").replace(/\./g,"\\."),n=window.self!==window.top,s={},u=!1,o=null,p=null,l=function(){var e;return e=1,function(n){var t,i;t=new r;try{n.id=e,n.clientId=o,n.accessToken=null!=p?p.accessToken:void 0,s[n.id]=t,e+=1,window.parent.postMessage(JSON.stringify(n),"*")}catch(u){i=u,t.reject(i)}return t}}(),a=function(e){var n;if(!c(e.origin))throw new Error("Invalid origin "+e.origin);return n=JSON.parse(e.data),s[n.id].resolve(n.result)},w=function(){return l({method:"ping"})},c=function(e){var n;return n=new RegExp("^https?://(\\w+\\.)?(\\w+\\.)?"+i+"/?$"),n.test(e)},t=function(){function e(){this.version="v0.0.0",window.addEventListener("message",a)}return e.prototype._setInitialized=function(e){return u=e},e.prototype._setFramed=function(e){return n=e},e.prototype.init=function(e){return o=null!=e?e.clientId:void 0,o?n?w().then(function(){return l({method:"auth.getStatus"})}).then(function(e){return u=!0,p=e}):(new r).reject(new Error("Unframed Not Implemented")):(new r).reject(new Error("Missing clientId"))},e.prototype.login=function(e){var n;return n=e.scope,(new r).reject(new Error("Not Implemented"))},e.prototype.api=function(){return(new r).reject(new Error("Not Implemented"))},e.prototype.client=function(e){return u?n?w().then(function(){return l(e)}):(new r).reject(new Error("Missing parent frame. Make sure you are within a clay game running frame")):(new r).reject(new Error("Must call Clay.init() first"))},e}(),module.exports=new t}).call(this,require("_process"));
},{"_process":3,"promiz":2}],2:[function(require,module,exports){
!function(){function t(n,e){function o(t,n,e,o){if("object"==typeof i&&"function"==typeof t)try{var c=0;t.call(i,function(t){c++||(i=t,n())},function(t){c++||(i=t,e())})}catch(r){i=r,e()}else o()}function c(){var t;try{t=i&&i.then}catch(f){return i=f,u=2,c()}o(t,function(){u=1,c()},function(){u=2,c()},function(){try{1==u&&"function"==typeof n?i=n(i):2==u&&"function"==typeof e&&(i=e(i),u=1)}catch(c){return i=c,s()}i==r?(i=TypeError(),s()):o(t,function(){s(3)},s,function(){s(1==u&&3)})})}var r=this,u=0,i=0,f=[];r.promise=r,r.resolve=function(t){return u||(i=t,u=1,setTimeout(c)),this},r.reject=function(t){return u||(i=t,u=2,setTimeout(c)),this},r.then=function(n,e){var o=new t(n,e);return 3==u?o.resolve(i):4==u?o.reject(i):f.push(o),o};var s=function(t){u=t||4,f.map(function(t){3==u&&t.resolve(i)||t.reject(i)})}}"undefined"!=typeof module?module.exports=t:this.Promiz=t}();
},{}],3:[function(require,module,exports){
function noop(){}var process=module.exports={};process.nextTick=function(){var o="undefined"!=typeof window&&window.setImmediate,e="undefined"!=typeof window&&window.postMessage&&window.addEventListener;if(o)return function(o){return window.setImmediate(o)};if(e){var s=[];return window.addEventListener("message",function(o){var e=o.source;if((e===window||null===e)&&"process-tick"===o.data&&(o.stopPropagation(),s.length>0)){var n=s.shift();n()}},!0),function(o){s.push(o),window.postMessage("process-tick","*")}}return function(o){setTimeout(o,0)}}(),process.title="browser",process.browser=!0,process.env={},process.argv=[],process.on=noop,process.addListener=noop,process.once=noop,process.off=noop,process.removeListener=noop,process.removeAllListeners=noop,process.emit=noop,process.binding=function(){throw new Error("process.binding is not supported")},process.cwd=function(){return"/"},process.chdir=function(){throw new Error("process.chdir is not supported")};
},{}]},{},[1])(1)
});<commit_msg>built<commit_after>!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.Clay=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
var IS_FRAMED,Promiz,SDK,TRUSTED_DOMAIN,clientId,isInitialized,isValidOrigin,onMessage,pendingMessages,postMessage,status,validateParent;Promiz=require("promiz"),TRUSTED_DOMAIN="192.168.2.98.xip.io:3000".replace(/\./g,"\\."),IS_FRAMED=window.self!==window.top,pendingMessages={},isInitialized=!1,clientId=null,status=null,postMessage=function(){var e;return e=1,function(n){var t,i;t=new Promiz;try{n.id=e,n.clientId=clientId,n.accessToken=null!=status?status.accessToken:void 0,pendingMessages[n.id]=t,e+=1,window.parent.postMessage(JSON.stringify(n),"*")}catch(r){i=r,t.reject(i)}return t}}(),onMessage=function(e){var n;if(!isValidOrigin(e.origin))throw new Error("Invalid origin "+e.origin);return n=JSON.parse(e.data),pendingMessages[n.id].resolve(n.result)},validateParent=function(){return postMessage({method:"ping"})},isValidOrigin=function(e){var n;return n=new RegExp("^https?://(\\w+\\.)?(\\w+\\.)?"+TRUSTED_DOMAIN+"/?$"),n.test(e)},SDK=function(){function e(){this.version="v0.0.0",window.addEventListener("message",onMessage)}return e.prototype._setInitialized=function(e){return isInitialized=e},e.prototype._setFramed=function(e){return IS_FRAMED=e},e.prototype.init=function(e){return clientId=null!=e?e.clientId:void 0,clientId?IS_FRAMED?validateParent().then(function(){return postMessage({method:"auth.getStatus"})}).then(function(e){return isInitialized=!0,status=e}):(new Promiz).reject(new Error("Unframed Not Implemented")):(new Promiz).reject(new Error("Missing clientId"))},e.prototype.login=function(e){var n;return n=e.scope,(new Promiz).reject(new Error("Not Implemented"))},e.prototype.api=function(){return(new Promiz).reject(new Error("Not Implemented"))},e.prototype.client=function(e){return isInitialized?IS_FRAMED?validateParent().then(function(){return postMessage(e)}):(new Promiz).reject(new Error("Missing parent frame. Make sure you are within a clay game running frame")):(new Promiz).reject(new Error("Must call Clay.init() first"))},e}(),module.exports=new SDK;
},{"promiz":2}],2:[function(require,module,exports){
!function(){function t(n,e){function o(t,n,e,o){if("object"==typeof i&&"function"==typeof t)try{var c=0;t.call(i,function(t){c++||(i=t,n())},function(t){c++||(i=t,e())})}catch(r){i=r,e()}else o()}function c(){var t;try{t=i&&i.then}catch(f){return i=f,u=2,c()}o(t,function(){u=1,c()},function(){u=2,c()},function(){try{1==u&&"function"==typeof n?i=n(i):2==u&&"function"==typeof e&&(i=e(i),u=1)}catch(c){return i=c,s()}i==r?(i=TypeError(),s()):o(t,function(){s(3)},s,function(){s(1==u&&3)})})}var r=this,u=0,i=0,f=[];r.promise=r,r.resolve=function(t){return u||(i=t,u=1,setTimeout(c)),this},r.reject=function(t){return u||(i=t,u=2,setTimeout(c)),this},r.then=function(n,e){var o=new t(n,e);return 3==u?o.resolve(i):4==u?o.reject(i):f.push(o),o};var s=function(t){u=t||4,f.map(function(t){3==u&&t.resolve(i)||t.reject(i)})}}"undefined"!=typeof module?module.exports=t:this.Promiz=t}();
},{}]},{},[1])(1)
});<|endoftext|>


<commit_before>!function(e, t) {
    "object" == typeof exports && "object" == typeof module ? module.exports = t() : "function" == typeof define && define.amd ? define([], t) : "object" == typeof exports ? exports.tvsFlow = t() : e.tvsFlow = t();
}(this, function() {
    return function(e) {
        function t(n) {
            if (r[n]) return r[n].exports;
            var o = r[n] = {
                exports: {},
                id: n,
                loaded: !1
            };
            return e[n].call(o.exports, o, o.exports, t), o.loaded = !0, o.exports;
        }
        var r = {};
        return t.m = e, t.c = r, t.p = "", t(0);
    }([ function(e, t, r) {
        "use strict";
        function n(e) {
            return e && e.__esModule ? e : {
                "default": e
            };
        }
        Object.defineProperty(t, "__esModule", {
            value: !0
        });
        var o = r(1), a = n(o);
        t["default"] = a["default"], e.exports = t["default"];
    }, function(e, t, r) {
        "use strict";
        function n(e) {
            return e && e.__esModule ? e : {
                "default": e
            };
        }
        function o(e) {
            return e && "undefined" != typeof Symbol && e.constructor === Symbol ? "symbol" : typeof e;
        }
        function a() {
            function e() {
                return {
                    entities: R,
                    processes: w,
                    arcs: L,
                    meta: U
                };
            }
            function t() {
                var e = {};
                for (var t in D.es) e[t] = D.es[t].val;
                return e;
            }
            function r() {
                return Y;
            }
            function n(e) {
                Y = e;
            }
            function a() {
                return U;
            }
            function c(e) {
                null == e || "object" !== ("undefined" == typeof e ? "undefined" : o(e)) || e instanceof Array || (U = s({}, U, e));
            }
            function i(e) {
                F = e;
            }
            function l(e) {
                return D.es[e] && D.es[e].val;
            }
            function f(e, t) {
                var r = k(e);
                r.val = t, E(r), T();
            }
            function v(e, t) {
                f(e, t(l(e)));
            }
            function d(e, t) {
                var r = k(e);
                r.cb = t;
            }
            function p(e) {
                var t = k(e);
                delete t.cb;
            }
            function y(e) {
                var t = u["default"].createEntity(e);
                R[t.id] = t;
                var r = k(t.id);
                return r.event = t.isEvent, null != t.value && null == r.val && (r.val = t.value,
                E(r)), null != t.json && null == r.val && (r.val = JSON.parse(t.json), E(r)), t;
            }
            function b(e) {
                var t = k(e);
                for (var r in t.arcs) g(r);
                delete D.es[e], delete R[e];
            }
            function O(e) {
                var t = u["default"].createProcess(e, Y);
                w[t.id] = t;
                var r = C(t.id);
                r.acc = null, r.async = t.async;
                var n = Object.keys(t.ports);
                for (var o in r.arcs) {
                    var a = L[o].port;
                    a && (n.indexOf(a) < 0 || t.ports[a] === u["default"].PORT_TYPES.ACCUMULATOR) && g(o);
                }
                for (var s in t.ports) t.ports[s] === u["default"].PORT_TYPES.ACCUMULATOR && (r.acc = s);
                for (var c in r.arcs) h(L[c]);
                return t;
            }
            function m(e) {
                var t = C(e);
                t.stop && t.stop();
                for (var r in t.arcs) g(r);
                delete D.ps[e], delete w[e];
            }
            function P(e) {
                var t = u["default"].createArc(e);
                L[t.id] = t, h(t);
                var r = C(t.process), n = w[t.process];
                return n && n.autostart === !0 && Object.keys(r.arcs).length === Object.keys(n.ports).length + 1 && S(r),
                t;
            }
            function g(e) {
                var t = L[e];
                if (t) {
                    var r = C(t.process), n = k(t.entity);
                    delete r.arcs[e], delete n.arcs[e], t.port ? (delete n.effects[t.process], delete r.sources[t.port],
                    delete r.values[t.port]) : (r.sink = function() {}, delete r.out, delete n.reactions[t.process]);
                }
                delete L[e];
            }
            function h(e) {
                var t = e.process, r = e.entity, n = C(t), o = k(r), a = w[t];
                o.arcs[e.id] = !0, a && (n.arcs[e.id] = !0, e.port ? (n.sources[e.port] = o, a.ports[e.port] == u["default"].PORT_TYPES.HOT ? o.effects[t] = n : delete o.effects[t]) : (n.sink = function(e) {
                    o.val = e, E(o), T();
                }, n.out = o, n.acc ? (n.sources[n.acc] = o, o.reactions[t] = n) : delete o.reactions[t]));
            }
            function x(e) {
                if (e.entities) for (var t in e.entities) y(e.entities[t]);
                if (e.processes) for (var r in e.processes) O(e.processes[r]);
                if (e.arcs) for (var n in e.arcs) P(e.arcs[n]);
                e.meta && c(e.meta), T();
            }
            function E(e, t) {
                G[e.id] = t || !0;
            }
            function j(e) {
                var t = e.syncSchedule, r = e.asyncSchedule, n = e.callbacks, o = e.activeEntities, a = e.eE, s = e.level, c = void 0 === s ? 0 : s, u = e.pLast;
                if (o[a.id] = !0, a.cb && (n[a.id] = a), !u || !u.acc) {
                    var i = !1;
                    for (var l in a.reactions) i = !0, t[l] ? t[l].level < c && (t[l].level = c) : t[l] = {
                        level: c,
                        eP: a.reactions[l]
                    };
                    i && c++;
                }
                for (var f in a.effects) {
                    var v = a.effects[f];
                    v.async ? r[f] = v : (t[f] ? t[f].level < c && (t[f].level = c) : t[f] = {
                        level: c,
                        eP: v
                    }, v.out && j({
                        syncSchedule: t,
                        asyncSchedule: r,
                        callbacks: n,
                        activeEntities: o,
                        eE: v.out,
                        level: c + 1,
                        pLast: v
                    }));
                }
            }
            function T() {
                F && console.log("flushing graph with", G);
                var e = [], t = {}, r = {}, n = {}, o = {};
                for (var a in G) j({
                    syncSchedule: r,
                    asyncSchedule: n,
                    callbacks: t,
                    activeEntities: o,
                    eE: D.es[a],
                    level: 0,
                    pLast: G[a]
                });
                G = {};
                for (var s in r) {
                    var c = r[s];
                    e[c.level] ? e[c.level].push(c.eP) : e[c.level] = [ c.eP ];
                }
                for (var u = 0; u < e.length; u++) for (var i = 0; i < e[u].length; i++) _(e[u][i], o);
                for (var l in t) t[l].cb(t[l].val);
                for (var f in n) _(n[f], o);
            }
            function _(e, t) {
                F && console.log("executing process", e.id);
                for (var r in e.sources) {
                    var n = e.sources[r];
                    !n.event || t && t[n.id] ? e.values[r] = n.val : e.values[r] = void 0;
                }
                if (e.async) e.stop && e.stop(), e.stop = w[e.id].procedure.call(Y, e.values, e.sink); else {
                    var o = w[e.id].procedure.call(Y, e.values);
                    e.out && (e.out.val = o);
                }
            }
            function S(e) {
                e.async ? setTimeout(function() {
                    _(e);
                }, 10) : (_(e), E(e.out));
            }
            function M(e) {
                var t = C(e);
                _(t), t.out && !t.async && (E(t.out, t), T());
            }
            function A(e) {
                var t = C(e);
                t.stop && t.stop(), delete t.stop;
            }
            function k(e) {
                return R[e] || y({
                    id: e
                }), D.es[e] || (D.es[e] = {
                    id: e,
                    reactions: {},
                    effects: {},
                    arcs: {}
                });
            }
            function C(e) {
                return D.ps[e] || (D.ps[e] = {
                    id: e,
                    acc: null,
                    sources: {},
                    arcs: {},
                    values: {},
                    sink: function() {}
                });
            }
            var R = {}, w = {}, L = {}, U = {}, Y = null, D = {
                es: {},
                ps: {}
            }, F = !1, G = {};
            return {
                addEntity: y,
                removeEntity: b,
                addProcess: O,
                removeProcess: m,
                addArc: P,
                removeArc: g,
                addGraph: x,
                getGraph: e,
                getState: t,
                setMeta: c,
                getMeta: a,
                getContext: r,
                setContext: n,
                setDebug: i,
                get: l,
                set: f,
                update: v,
                on: d,
                off: p,
                start: M,
                stop: A,
                PORT_TYPES: s({}, u["default"].PORT_TYPES)
            };
        }
        Object.defineProperty(t, "__esModule", {
            value: !0
        });
        var s = Object.assign || function(e) {
            for (var t = 1; t < arguments.length; t++) {
                var r = arguments[t];
                for (var n in r) Object.prototype.hasOwnProperty.call(r, n) && (e[n] = r[n]);
            }
            return e;
        }, c = r(2), u = n(c);
        t["default"] = {
            create: a
        }, e.exports = t["default"];
    }, function(e, t, r) {
        "use strict";
        function n(e) {
            var t = e.id, r = void 0 === t ? (0, c.v4)() : t, n = e.value, o = e.json, a = e.isEvent, u = e.meta;
            return {
                id: r,
                value: n,
                json: o,
                isEvent: a,
                meta: s({}, u)
            };
        }
        function o(e, t) {
            var r = e.id, n = void 0 === r ? (0, c.v4)() : r, o = e.ports, a = void 0 === o ? {} : o, i = e.procedure, l = e.code, f = e.autostart, v = e.async, d = e.meta;
            return null == l && (l = i.toString()), null == i && (i = (0, u.evaluate)(l, t)),
            {
                id: n,
                ports: a,
                procedure: i,
                code: l,
                autostart: f,
                async: v,
                meta: s({}, d)
            };
        }
        function a(e) {
            var t = e.id, r = e.entity, n = e.process, o = e.port, a = e.meta;
            if (null == r) throw TypeError("no entity specified in arc " + t);
            if (null == n) throw TypeError("no process specified in arc " + t);
            return null == t && (t = null == o ? n + "->" + r : r + "->" + n + "::" + o), {
                id: t,
                entity: r,
                process: n,
                port: o,
                meta: s({}, a)
            };
        }
        Object.defineProperty(t, "__esModule", {
            value: !0
        });
        var s = Object.assign || function(e) {
            for (var t = 1; t < arguments.length; t++) {
                var r = arguments[t];
                for (var n in r) Object.prototype.hasOwnProperty.call(r, n) && (e[n] = r[n]);
            }
            return e;
        }, c = r(3), u = r(4), i = {
            COLD: "cold",
            HOT: "hot",
            ACCUMULATOR: "accumulator"
        };
        t["default"] = {
            createEntity: n,
            createProcess: o,
            createArc: a,
            PORT_TYPES: i
        }, e.exports = t["default"];
    }, function(e, t) {
        "use strict";
        function r(e) {
            var t = 0, r = s;
            return r[e[t++]] + r[e[t++]] + r[e[t++]] + r[e[t++]] + "-" + r[e[t++]] + r[e[t++]] + "-" + r[e[t++]] + r[e[t++]] + "-" + r[e[t++]] + r[e[t++]] + "-" + r[e[t++]] + r[e[t++]] + r[e[t++]] + r[e[t++]] + r[e[t++]] + r[e[t++]];
        }
        function n() {
            var e = a();
            return e[6] = 15 & e[6] | 64, e[8] = 63 & e[8] | 128, r(e);
        }
        Object.defineProperty(t, "__esModule", {
            value: !0
        }), t.v4 = n;
        for (var o = new Array(16), a = function() {
            for (var e, t = 0; 16 > t; t++) 0 === (3 & t) && (e = 4294967296 * Math.random()),
            o[t] = e >>> ((3 & t) << 3) & 255;
            return o;
        }, s = [], c = {}, u = 0; 256 > u; u++) s[u] = (u + 256).toString(16).substr(1),
        c[s[u]] = u;
    }, function(module, exports) {
        "use strict";
        function evaluate(code, context) {
            var prefix = "(function(){ return ", postfix = "})", factory = eval(prefix + code + postfix);
            return factory.call(context);
        }
        Object.defineProperty(exports, "__esModule", {
            value: !0
        }), exports.evaluate = evaluate;
    } ]);
});<commit_msg>update build<commit_after>!function(e, t) {
    "object" == typeof exports && "object" == typeof module ? module.exports = t() : "function" == typeof define && define.amd ? define([], t) : "object" == typeof exports ? exports.tvsFlow = t() : e.tvsFlow = t();
}(this, function() {
    return function(e) {
        function t(n) {
            if (r[n]) return r[n].exports;
            var o = r[n] = {
                exports: {},
                id: n,
                loaded: !1
            };
            return e[n].call(o.exports, o, o.exports, t), o.loaded = !0, o.exports;
        }
        var r = {};
        return t.m = e, t.c = r, t.p = "", t(0);
    }([ function(e, t, r) {
        "use strict";
        function n(e) {
            if (e && e.__esModule) return e;
            var t = {};
            if (null != e) for (var r in e) Object.prototype.hasOwnProperty.call(e, r) && (t[r] = e[r]);
            return t["default"] = e, t;
        }
        Object.defineProperty(t, "__esModule", {
            value: !0
        });
        var o = r(1), a = n(o);
        t["default"] = a, e.exports = t["default"];
    }, function(e, t, r) {
        "use strict";
        function n(e) {
            if (e && e.__esModule) return e;
            var t = {};
            if (null != e) for (var r in e) Object.prototype.hasOwnProperty.call(e, r) && (t[r] = e[r]);
            return t["default"] = e, t;
        }
        function o(e) {
            return e && "undefined" != typeof Symbol && e.constructor === Symbol ? "symbol" : typeof e;
        }
        function a() {
            function e() {
                return {
                    entities: R,
                    processes: C,
                    arcs: L,
                    meta: Y
                };
            }
            function t() {
                var e = {};
                for (var t in D.es) e[t] = D.es[t].val;
                return e;
            }
            function r() {
                return U;
            }
            function n(e) {
                U = e;
            }
            function a() {
                return Y;
            }
            function c(e) {
                null == e || "object" !== ("undefined" == typeof e ? "undefined" : o(e)) || e instanceof Array || (Y = s({}, Y, e));
            }
            function u(e) {
                F = e;
            }
            function l(e) {
                return D.es[e] && D.es[e].val;
            }
            function f(e, t) {
                var r = k(e);
                r.val = t, j(r), T();
            }
            function v(e, t) {
                f(e, t(l(e)));
            }
            function d(e, t) {
                var r = k(e);
                r.cb = t;
            }
            function p(e) {
                var t = k(e);
                delete t.cb;
            }
            function y(e) {
                var t = i.createEntity(e);
                R[t.id] = t;
                var r = k(t.id);
                return r.event = t.isEvent, null != t.value && null == r.val && (r.val = t.value,
                j(r)), null != t.json && null == r.val && (r.val = JSON.parse(t.json), j(r)), t;
            }
            function O(e) {
                var t = k(e);
                for (var r in t.arcs) m(r);
                delete D.es[e], delete R[e];
            }
            function P(e) {
                var t = i.createProcess(e, U);
                C[t.id] = t;
                var r = w(t.id);
                r.acc = null, r.async = t.async;
                var n = Object.keys(t.ports);
                for (var o in r.arcs) {
                    var a = L[o].port;
                    a && (n.indexOf(a) < 0 || t.ports[a] === i.PORT_TYPES.ACCUMULATOR) && m(o);
                }
                for (var s in t.ports) t.ports[s] === i.PORT_TYPES.ACCUMULATOR && (r.acc = s);
                for (var c in r.arcs) g(L[c]);
                return t;
            }
            function b(e) {
                var t = w(e);
                t.stop && t.stop();
                for (var r in t.arcs) m(r);
                delete D.ps[e], delete C[e];
            }
            function h(e) {
                var t = i.createArc(e);
                L[t.id] = t, g(t);
                var r = w(t.process), n = C[t.process];
                return n && n.autostart === !0 && Object.keys(r.arcs).length === Object.keys(n.ports).length + 1 && S(r),
                t;
            }
            function m(e) {
                var t = L[e];
                if (t) {
                    var r = w(t.process), n = k(t.entity);
                    delete r.arcs[e], delete n.arcs[e], t.port ? (delete n.effects[t.process], delete r.sources[t.port],
                    delete r.values[t.port]) : (r.sink = function() {}, delete r.out, delete n.reactions[t.process]);
                }
                delete L[e];
            }
            function g(e) {
                var t = e.process, r = e.entity, n = w(t), o = k(r), a = C[t];
                o.arcs[e.id] = !0, a && (n.arcs[e.id] = !0, e.port ? (n.sources[e.port] = o, a.ports[e.port] == i.PORT_TYPES.HOT ? o.effects[t] = n : delete o.effects[t]) : (n.sink = function(e) {
                    o.val = e, j(o), T();
                }, n.out = o, n.acc ? (n.sources[n.acc] = o, o.reactions[t] = n) : delete o.reactions[t]));
            }
            function x(e) {
                if (e.entities) for (var t in e.entities) y(e.entities[t]);
                if (e.processes) for (var r in e.processes) P(e.processes[r]);
                if (e.arcs) for (var n in e.arcs) h(e.arcs[n]);
                e.meta && c(e.meta), T();
            }
            function j(e, t) {
                G[e.id] = t || !0;
            }
            function E(e) {
                var t = e.syncSchedule, r = e.asyncSchedule, n = e.callbacks, o = e.activeEntities, a = e.eE, s = e.level, c = void 0 === s ? 0 : s, i = e.pLast;
                if (o[a.id] = !0, a.cb && (n[a.id] = a), !i || !i.acc) {
                    var u = !1;
                    for (var l in a.reactions) u = !0, t[l] ? t[l].level < c && (t[l].level = c) : t[l] = {
                        level: c,
                        eP: a.reactions[l]
                    };
                    u && c++;
                }
                for (var f in a.effects) {
                    var v = a.effects[f];
                    v.async ? r[f] = v : (t[f] ? t[f].level < c && (t[f].level = c) : t[f] = {
                        level: c,
                        eP: v
                    }, v.out && E({
                        syncSchedule: t,
                        asyncSchedule: r,
                        callbacks: n,
                        activeEntities: o,
                        eE: v.out,
                        level: c + 1,
                        pLast: v
                    }));
                }
            }
            function T() {
                F && console.log("flushing graph with", G);
                var e = [], t = {}, r = {}, n = {}, o = {};
                for (var a in G) E({
                    syncSchedule: r,
                    asyncSchedule: n,
                    callbacks: t,
                    activeEntities: o,
                    eE: D.es[a],
                    level: 0,
                    pLast: G[a]
                });
                G = {};
                for (var s in r) {
                    var c = r[s];
                    e[c.level] ? e[c.level].push(c.eP) : e[c.level] = [ c.eP ];
                }
                for (var i = 0; i < e.length; i++) for (var u = 0; u < e[i].length; u++) _(e[i][u], o);
                for (var l in t) t[l].cb(t[l].val);
                for (var f in n) _(n[f], o);
            }
            function _(e, t) {
                F && console.log("executing process", e.id);
                for (var r in e.sources) {
                    var n = e.sources[r];
                    !n.event || t && t[n.id] ? e.values[r] = n.val : e.values[r] = void 0;
                }
                if (e.async) e.stop && e.stop(), e.stop = C[e.id].procedure.call(U, e.values, e.sink); else {
                    var o = C[e.id].procedure.call(U, e.values);
                    e.out && (e.out.val = o);
                }
            }
            function S(e) {
                e.async ? setTimeout(function() {
                    _(e);
                }, 10) : (_(e), j(e.out));
            }
            function M(e) {
                var t = w(e);
                _(t), t.out && !t.async && (j(t.out, t), T());
            }
            function A(e) {
                var t = w(e);
                t.stop && t.stop(), delete t.stop;
            }
            function k(e) {
                return R[e] || y({
                    id: e
                }), D.es[e] || (D.es[e] = {
                    id: e,
                    reactions: {},
                    effects: {},
                    arcs: {}
                });
            }
            function w(e) {
                return D.ps[e] || (D.ps[e] = {
                    id: e,
                    acc: null,
                    sources: {},
                    arcs: {},
                    values: {},
                    sink: function() {}
                });
            }
            var R = {}, C = {}, L = {}, Y = {}, U = null, D = {
                es: {},
                ps: {}
            }, F = !1, G = {};
            return {
                addEntity: y,
                removeEntity: O,
                addProcess: P,
                removeProcess: b,
                addArc: h,
                removeArc: m,
                addGraph: x,
                getGraph: e,
                getState: t,
                setMeta: c,
                getMeta: a,
                getContext: r,
                setContext: n,
                setDebug: u,
                get: l,
                set: f,
                update: v,
                on: d,
                off: p,
                start: M,
                stop: A,
                PORT_TYPES: s({}, i.PORT_TYPES)
            };
        }
        Object.defineProperty(t, "__esModule", {
            value: !0
        });
        var s = Object.assign || function(e) {
            for (var t = 1; t < arguments.length; t++) {
                var r = arguments[t];
                for (var n in r) Object.prototype.hasOwnProperty.call(r, n) && (e[n] = r[n]);
            }
            return e;
        };
        t.create = a;
        var c = r(2), i = n(c);
    }, function(e, t, r) {
        "use strict";
        function n(e) {
            var t = e.id, r = void 0 === t ? (0, c.v4)() : t, n = e.value, o = e.json, a = e.isEvent, i = e.meta;
            return {
                id: r,
                value: n,
                json: o,
                isEvent: a,
                meta: s({}, i)
            };
        }
        function o(e, t) {
            var r = e.id, n = void 0 === r ? (0, c.v4)() : r, o = e.ports, a = void 0 === o ? {} : o, u = e.procedure, l = e.code, f = e.autostart, v = e.async, d = e.meta;
            return null == l && (l = u.toString()), null == u && (u = (0, i.evaluate)(l, t)),
            {
                id: n,
                ports: a,
                procedure: u,
                code: l,
                autostart: f,
                async: v,
                meta: s({}, d)
            };
        }
        function a(e) {
            var t = e.id, r = e.entity, n = e.process, o = e.port, a = e.meta;
            if (null == r) throw TypeError("no entity specified in arc " + t);
            if (null == n) throw TypeError("no process specified in arc " + t);
            return null == t && (t = null == o ? n + "->" + r : r + "->" + n + "::" + o), {
                id: t,
                entity: r,
                process: n,
                port: o,
                meta: s({}, a)
            };
        }
        Object.defineProperty(t, "__esModule", {
            value: !0
        }), t.PORT_TYPES = void 0;
        var s = Object.assign || function(e) {
            for (var t = 1; t < arguments.length; t++) {
                var r = arguments[t];
                for (var n in r) Object.prototype.hasOwnProperty.call(r, n) && (e[n] = r[n]);
            }
            return e;
        };
        t.createEntity = n, t.createProcess = o, t.createArc = a;
        var c = r(3), i = r(4);
        t.PORT_TYPES = {
            COLD: "cold",
            HOT: "hot",
            ACCUMULATOR: "accumulator"
        };
    }, function(e, t) {
        "use strict";
        function r(e) {
            var t = 0, r = s;
            return r[e[t++]] + r[e[t++]] + r[e[t++]] + r[e[t++]] + "-" + r[e[t++]] + r[e[t++]] + "-" + r[e[t++]] + r[e[t++]] + "-" + r[e[t++]] + r[e[t++]] + "-" + r[e[t++]] + r[e[t++]] + r[e[t++]] + r[e[t++]] + r[e[t++]] + r[e[t++]];
        }
        function n() {
            var e = a();
            return e[6] = 15 & e[6] | 64, e[8] = 63 & e[8] | 128, r(e);
        }
        Object.defineProperty(t, "__esModule", {
            value: !0
        }), t.v4 = n;
        for (var o = new Array(16), a = function() {
            for (var e, t = 0; 16 > t; t++) 0 === (3 & t) && (e = 4294967296 * Math.random()),
            o[t] = e >>> ((3 & t) << 3) & 255;
            return o;
        }, s = [], c = {}, i = 0; 256 > i; i++) s[i] = (i + 256).toString(16).substr(1),
        c[s[i]] = i;
    }, function(module, exports) {
        "use strict";
        function evaluate(code, context) {
            var prefix = "(function(){ return ", postfix = "})", factory = eval(prefix + code + postfix);
            return factory.call(context);
        }
        Object.defineProperty(exports, "__esModule", {
            value: !0
        }), exports.evaluate = evaluate;
    } ]);
});<|endoftext|>


<commit_before>/*
    Cornerstone Framework v0.9.1

    COPYRIGHT(C) 2012 BY SKTELECOM CO., LTD. ALL RIGHTS RESERVED.
    Released under the Apache License, Version 2.0
*/
(function(e,t){function f(e,t){t?t(e):console.log("handler is not define")}function l(e,t){var n=!1;for(var r in t)e[t[r]]||(f({result:"fail",resultCode:"1",message:t[r]+" is require."},e.error),n=!0);return n}typeof exports!="undefined"?Backbone=exports:Backbone=t.Backbone={};var n=t.SKT={authFrame:undefined},r,i="http://61.250.22.139:80",s=i+"/oauth/authorize",o=i+"/sms",u=i+"/payment",a=function(e){this.options=e};n.authorize=function(e){return r=new a(e),r.init(),r},n.authSuccess=function(i){var s=i.hash.substr(1).split("&"),o={};for(var u=0;u<s.length;u++){var a=s[u].split("=");o[a[0]]=a[1]}e("#"+n.authFrame)&&(e("#"+n.authFrame).remove(),n.authFrame=undefined,e(t).off("resize"));if(!o.access_token)return r.options.error({result:"fail",resultCode:"1",message:"access_token is not valid."}),!1;r.success(decodeURIComponent(o.access_token))},a.prototype={defaults:{client_id:undefined,redirect_uri:undefined,response_type:"token"},init:function(){var r=["clientId","redirectUri"];if(l(this.options,r))return!1;var i={client_id:this.options.clientId,redirect_uri:encodeURI(this.options.redirectUri)};this.success=this.options.success,e.extend(this.defaults,i);if(!n.authFrame){n.authFrame="skt_auth_iframe_"+Math.floor(Math.random()*1e3)+1;var o=e("<button>close</button>",{type:"button"}).css({left:"10px",top:"10px",position:"absolute","font-size":"15px"});o.on("click",function(r){e("#"+n.authFrame).remove(),n.authFrame=undefined,e(t).off("resize")});var u=e("

",{id:n.authFrame}).css({"z-index":"10000",left:"0px",top:"0px",width:t.innerWidth+"px",height:t.innerHeight+"px",position:"absolute","background-color":"gray"});e(t).on("resize",function(e){u.css({width:e.currentTarget.innerWidth+"px",height:e.currentTarget.innerHeight+"px"}),a.css({width:e.currentTarget.innerWidth+"px",height:e.currentTarget.innerHeight+"px"})});var a=e("",{src:s+"?"+e.param(this.defaults)}).css({width:t.innerWidth+"px",height:t.innerHeight+"px","background-color":"gray"});a.appendTo(u),o.appendTo(u),u.appendTo("body")}else e("#"+n.authFrame).attr("src",s+"?"+e.param(this.defaults))},success:function(){}},n.sendSms=function(t){var n=["accessToken","from","to","message"];if(l(t,n))return!1;var r={access_token:t.accessToken,from:t.from,to:t.to,message:encodeURIComponent(t.message)};e.ajax({url:o,data:r,dataType:"jsonp",jsonp:"callback",jsonpCallback:"success",timeout:t.timeout||5e3,success:function(e){e.resultCode==1?f(e,t.error):f(e,t.success)},error:function(e,n,r){f({result:"fail",resultCode:"1",message:"time out."},t.error)}})},n.pay=function(t){var n=["accessToken","type","amount","to"];t.type!=="one-time"&&t.type!=="recurring"&&n.push("paymentDate");if(l(t,n))return!1;var r={access_token:t.accessToken,type:t.type,amount:t.amount,payment_date:t.paymentDate,to:t.to};e.ajax({url:u,data:r,dataType:"jsonp",jsonp:"callback",jsonpCallback:"success",timeout:t.timeout||5e3,success:function(e){e.resultCode==1?f(e,t.error):f(e,t.success)},error:function(e,n,r){f({result:"fail",resultCode:"1",message:"time out."},t.error)}})}})(jQuery,window)<commit_msg>운영서비 기준으로 빌드<commit_after>/*
    Cornerstone Framework v0.9.1

    COPYRIGHT(C) 2012 BY SKTELECOM CO., LTD. ALL RIGHTS RESERVED.
    Released under the Apache License, Version 2.0
*/
(function(e,t){function f(e,t){t?t(e):console.log("handler is not define")}function l(e,t){var n=!1;for(var r in t)e[t[r]]||(f({result:"fail",resultCode:"1",message:t[r]+" is require."},e.error),n=!0);return n}typeof exports!="undefined"?Backbone=exports:Backbone=t.Backbone={};var n=t.SKT={authFrame:undefined},r,i="http://cornerstone.sktelecom.com/",s=i+"/oauth/authorize",o=i+"/sms",u=i+"/payment",a=function(e){this.options=e};n.authorize=function(e){return r=new a(e),r.init(),r},n.authSuccess=function(i){var s=i.hash.substr(1).split("&"),o={};for(var u=0;u<s.length;u++){var a=s[u].split("=");o[a[0]]=a[1]}e("#"+n.authFrame)&&(e("#"+n.authFrame).remove(),n.authFrame=undefined,e(t).off("resize"));if(!o.access_token)return r.options.error({result:"fail",resultCode:"1",message:"access_token is not valid."}),!1;r.success(decodeURIComponent(o.access_token))},a.prototype={defaults:{client_id:undefined,redirect_uri:undefined,response_type:"token"},init:function(){var r=["clientId","redirectUri"];if(l(this.options,r))return!1;var i={client_id:this.options.clientId,redirect_uri:encodeURI(this.options.redirectUri)};this.success=this.options.success,e.extend(this.defaults,i);if(!n.authFrame){n.authFrame="skt_auth_iframe_"+Math.floor(Math.random()*1e3)+1;var o=e("<button>close</button>",{type:"button"}).css({left:"10px",top:"10px",position:"absolute","font-size":"15px"});o.on("click",function(r){e("#"+n.authFrame).remove(),n.authFrame=undefined,e(t).off("resize")});var u=e("

",{id:n.authFrame}).css({"z-index":"10000",left:"0px",top:"0px",width:t.innerWidth+"px",height:t.innerHeight+"px",position:"absolute","background-color":"gray"});e(t).on("resize",function(e){u.css({width:e.currentTarget.innerWidth+"px",height:e.currentTarget.innerHeight+"px"}),a.css({width:e.currentTarget.innerWidth+"px",height:e.currentTarget.innerHeight+"px"})});var a=e("",{src:s+"?"+e.param(this.defaults)}).css({width:t.innerWidth+"px",height:t.innerHeight+"px","background-color":"gray"});a.appendTo(u),o.appendTo(u),u.appendTo("body")}else e("#"+n.authFrame).attr("src",s+"?"+e.param(this.defaults))},success:function(){}},n.sendSms=function(t){var n=["accessToken","from","to","message"];if(l(t,n))return!1;var r={access_token:t.accessToken,from:t.from,to:t.to,message:encodeURIComponent(t.message)};e.ajax({url:o,data:r,dataType:"jsonp",jsonp:"callback",jsonpCallback:"success",timeout:t.timeout||5e3,success:function(e){e.resultCode==1?f(e,t.error):f(e,t.success)},error:function(e,n,r){f({result:"fail",resultCode:"1",message:"time out."},t.error)}})},n.pay=function(t){var n=["accessToken","type","amount","to"];t.type!=="one-time"&&t.type!=="recurring"&&n.push("paymentDate");if(l(t,n))return!1;var r={access_token:t.accessToken,type:t.type,amount:t.amount,payment_date:t.paymentDate,to:t.to};e.ajax({url:u,data:r,dataType:"jsonp",jsonp:"callback",jsonpCallback:"success",timeout:t.timeout||5e3,success:function(e){e.resultCode==1?f(e,t.error):f(e,t.success)},error:function(e,n,r){f({result:"fail",resultCode:"1",message:"time out."},t.error)}})}})(jQuery,window)<|endoftext|>


<commit_before>define([
    '/customize/messages.js',
    '/customize/application_config.js',
    '/common/cryptpad-common.js',
    '/bower_components/lil-uri/uri.min.js',
    '/customize/languageSelector.js',
    '/bower_components/jquery/dist/jquery.min.js',
], function (Messages, Config, Cryptpad, LilUri, LS) {
    var $ = window.$;

    var USE_TABLE = Config.USE_HOMEPAGE_TABLE;
    var USE_FS_STORE = Config.USE_FS_STORE;

    var APP = window.APP = {
        Cryptpad: Cryptpad,
    };

    // main block is hidden in case javascript is disabled
    $('#mainBlock').removeClass('hidden');

    var padTypes = {
        '/pad/': Messages.type.pad,
        '/code/': Messages.type.code,
        '/poll/': Messages.type.poll,
        '/slide/': Messages.type.slide,
    };

    var $table;
    var $tbody;
    var $tryit;
    var now = new Date();
    var hasRecent = false;

    var forgetPad = Cryptpad.forgetPad;

    var displayCreateButtons = function () {
        var $parent = $('#buttons');
        Config.availablePadTypes.forEach(function (el) {
            $('#create-' + el)//.detach().appendTo($parent)
                .attr('target', '_blank').show();
        });
    };

    // Language selector
    var $sel = $('#language-selector');
    Cryptpad.createLanguageSelector(undefined, $sel);
    $sel.find('button').addClass('btn').addClass('btn-secondary');
    $sel.show();

    $(window).click(function () {
        $sel.find('.cryptpad-dropdown').hide();
    });

    var makeRecentPadsTable = function (recentPads) {
        if (!recentPads.length) { return; }

        $('tbody tr').each(function (i, e) {
            if (!i) { return; }
            $(this).remove();
        });

        recentPads.some(function (pad, index) {
            if (!pad) { return; }

            hasRecent = true;

            // split up the uri
            var uri = LilUri(pad.href);

            // derive the name
            var name = padTypes[uri.path()];

            var title = pad.title || uri.parts.hash.slice(0,8);
            var shortTitle = Cryptpad.truncate(pad.title, 48);

            var date = new Date(pad.atime).toLocaleDateString();
            var created = new Date(pad.ctime).toLocaleDateString();

            if (date === now.toLocaleDateString()) {
                date = new Date(pad.atime).toLocaleTimeString().replace(/ /g, '');
            }

            var id = 'pad-'+index;

            var $row = $('<tr>', {
                id: id
            });

            var $remove = $('<td>', {
                'class': 'remove',
                title: Messages.forget + " '"+shortTitle + "'"
            }).text('✖').click(function () {
                Cryptpad.confirm(Messages.forgetPrompt + ' (' + Cryptpad.fixHTML(shortTitle) + ')', function (yes) {
                    if (!yes) { return; }
                    forgetPad(pad.href, function (err, data) {
                        if (err) {
                            console.log("Unable to forget pad");
                            console.log(err);
                            return;
                        }
                        $row.fadeOut(750, function () {
                            $row.remove();
                            if (!$table.find('tr').find('td').length) {
                                $table.remove();
                                $tryit.text(Messages.tryIt);
                            }
                        });
                    });
                });
            });

            var readOnly = false;
            if (pad.href.indexOf('#') !== -1) {
                var modeArray = pad.href.split('#')[1].split('/');
                if (modeArray.length >= 3 && modeArray[2] === 'view') {
                    readOnly =  true;
                }
            }
            var readOnlyText = readOnly ? '(' + Messages.readonly + ') ' : '';
            $row
                .append($('<td>').text(name))
                .append($('<td>').append(readOnlyText).append($('<a>', {
                    href: pad.href,
                    title: pad.title,
                    target: '_blank',
                }).text(shortTitle)))
                .append($('<td>').text(created))
                .append($('<td>').text(date))
                .append($remove);
            $tbody.append($row);
        });
    };

    var refreshTable = function () {
        Cryptpad.getRecentPads(function (err, recentPads) {
            if (err) {
                console.log("unable to get recent pads");
                console.error(err);
                return;
            }

            if (recentPads.length) {
                recentPads.sort(Cryptpad.mostRecent);
                $('iframe').attr('style', '');
                $tryit.removeAttr('data-localization');
                $tryit.text(Messages.recentPadsIframe);

                if (USE_TABLE) {
                    makeRecentPadsTable(recentPads);
                }
            }

            if (USE_TABLE && hasRecent) {
                $('table').attr('style', '');
                // Race condition here, this is triggered before the localization in HTML
                // so we have to remove the data-localization attr
                $tryit.removeAttr('data-localization');
                $tryit.text(Messages.recentPads);
            }
        });
    };

    var addButtonHandlers = function () {
        $('button.login').click(function (e) {
            var username = $('#name').val();
            var passwd = $('#password').val();
            var remember = $('#rememberme').is(':checked');
            sessionStorage.login_user = username;
            sessionStorage.login_pass = passwd;
            sessionStorage.login_rmb = remember;
            sessionStorage.login = 1;
            document.location.href = '/user';
        });
        $('button.register').click(function (e) {
            var username = $('#name').val();
            var passwd = $('#password').val();
            var remember = $('#rememberme').is(':checked');
            sessionStorage.login_user = username;
            sessionStorage.login_pass = passwd;
            sessionStorage.login_rmb = remember;
            sessionStorage.register = 1;
            document.location.href = '/user';
        });
        $('button.nologin').click(function (e) {
            document.location.href = '/drive';
        });
        $('button.knowmore').click(function (e) {
            e.preventDefault();

            $('html, body').animate({
                scrollTop: $('#knowmore').offset().top
            }, 500);
        });
        $('button.tryit').click(function (e) {
            e.preventDefault();

            $('html, body').animate({
                scrollTop: $('#tryit').offset().top
            }, 500);
        });
    };

    displayCreateButtons();
    //Cryptpad.ready(function () {
        console.log("ready");

        if (Cryptpad.isLoggedIn()) {
            document.location.href = '/drive';
        }

        addButtonHandlers();

        $table = $('table.scroll');
        $tbody = $table.find('tbody');
        $tryit = $('#tryit');

        Cryptpad.styleAlerts();

        //refreshTable();
        /*
        if (Cryptpad.store && Cryptpad.store.change) {
            Cryptpad.store.change(function (data) {
                if (data.key === 'CryptPad_RECENTPADS') {
                    refreshTable();
                }
            });
        }
        */
    //});
});

<commit_msg>hitting enter in the password field should log you in<commit_after>define([
    '/customize/messages.js',
    '/customize/application_config.js',
    '/common/cryptpad-common.js',
    '/bower_components/lil-uri/uri.min.js',
    '/customize/languageSelector.js',
    '/bower_components/jquery/dist/jquery.min.js',
], function (Messages, Config, Cryptpad, LilUri, LS) {
    if (Cryptpad.isLoggedIn()) {
        document.location.href = '/drive';
        return;
    }

    var $ = window.$;

    var USE_TABLE = Config.USE_HOMEPAGE_TABLE;
    var USE_FS_STORE = Config.USE_FS_STORE;

    var APP = window.APP = {
        Cryptpad: Cryptpad,
    };

    // main block is hidden in case javascript is disabled
    $('#mainBlock').removeClass('hidden');

    var padTypes = {
        '/pad/': Messages.type.pad,
        '/code/': Messages.type.code,
        '/poll/': Messages.type.poll,
        '/slide/': Messages.type.slide,
    };

    var now = new Date();
    var hasRecent = false;

    var displayCreateButtons = function () {
        var $parent = $('#buttons');
        Config.availablePadTypes.forEach(function (el) {
            $('#create-' + el).attr('target', '_blank').show();
        });
    };

    // Language selector
    var $sel = $('#language-selector');
    Cryptpad.createLanguageSelector(undefined, $sel);
    $sel.find('button').addClass('btn').addClass('btn-secondary');
    $sel.show();

    $(window).click(function () {
        $sel.find('.cryptpad-dropdown').hide();
    });

    var addButtonHandlers = function () {
        $('button.login').click(function (e) {
            var username = $('#name').val();
            var passwd = $('#password').val();
            var remember = $('#rememberme').is(':checked');
            sessionStorage.login_user = username;
            sessionStorage.login_pass = passwd;
            sessionStorage.login_rmb = remember;
            sessionStorage.login = 1;
            document.location.href = '/user';
        });
        $('button.register').click(function (e) {
            var username = $('#name').val();
            var passwd = $('#password').val();
            var remember = $('#rememberme').is(':checked');
            sessionStorage.login_user = username;
            sessionStorage.login_pass = passwd;
            sessionStorage.login_rmb = remember;
            sessionStorage.register = 1;
            document.location.href = '/user';
        });
        $('button.nologin').click(function (e) {
            document.location.href = '/drive';
        });
        $('button.knowmore').click(function (e) {
            e.preventDefault();

            $('html, body').animate({
                scrollTop: $('#knowmore').offset().top
            }, 500);
        });
        $('button.tryit').click(function (e) {
            e.preventDefault();

            $('html, body').animate({
                scrollTop: $('#tryit').offset().top
            }, 500);
        });

        var $passwd = $('#password');
        $passwd.on('keyup', function (e) {
            if (e.which !== 13) { return; } // enter
            $('button.login').click();
        });
    };

    displayCreateButtons();

    addButtonHandlers();
    console.log("ready");
});

<|endoftext|>


<commit_before>var fs = require('fs')
  , http = require('http')

  http.get({ host: 'shapeshed.com' }, function(res) {
      console.log("Got a response from shapeshed.com");
  }).on('error', function(e) {
      console.log("There was an error from shapeshed.com");
  });

  fs.readFile('file1.txt', 'utf-8', function (err, data) {
      if (err) throw err;
        console.log('File 1 read!');
  });

  http.get({ host: 'www.bbc.co.uk' }, function(res) {
      console.log("Got a response from bbc.co.uk");
  }).on('error', function(e) {
      console.log("There was an error from bbc.co.uk");
  });

  fs.readFile('file2.txt', 'utf-8', function (err, data) {
      if (err) throw err;
        console.log('File 2 read!');
  });
<commit_msg>updating js style<commit_after>var fs = require('fs'),
    http = require('http')

  http.get({ host: 'shapeshed.com' }, function(res) {
      console.log("Got a response from shapeshed.com");
  }).on('error', function(e) {
      console.log("There was an error from shapeshed.com");
  });

  fs.readFile('file1.txt', 'utf8', function (err, data) {
      if (err) throw err;
      console.log('File 1 read!');
  });

  http.get({ host: 'www.bbc.co.uk' }, function(res) {
      console.log("Got a response from bbc.co.uk");
  }).on('error', function(e) {
      console.log("There was an error from bbc.co.uk");
  });

  fs.readFile('file2.txt', 'utf8', function (err, data) {
      if (err) throw err;
      console.log('File 2 read!');
  });
<|endoftext|>


<commit_before>var roleHarvester = {

	/** @param {Creep} creep **/
	run: function(creep) {

		if (creep.memory.harvesting) {
			var sources = creep.room.find(FIND_SOURCES);

			if (!creep.memory.source) {
				for (source in sources) {
					if (_.filter(Game.creeps, (creep) =>
							(creep.memory.role == 'harvester') &&
							(creep.memory.source == source)
					).length != 1) {
						creep.memory.source = source;
					}
				}
			}
			if (creep.harvest(sources[creep.memory.source]) == ERR_NOT_IN_RANGE) {
				creep.moveTo(sources[creep.memory.source]);
			}
			else if (creep.carry.energy == creep.carryCapacity) {
				creep.say('Depositing');
			  creep.memory.harvesting = false;
			}
		}
		else {
			var targets = creep.pos.findClosestByRange(FIND_STRUCTURES, {
				filter: (structure) => {
					return ((structure.structureType == STRUCTURE_CONTAINER) ||
									(structure.structureType == STRUCTURE_SPAWN);
				}
			});

			if (targets.length > 0) {
				if (creep.transfer(targets[0], RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
					creep.moveTo(targets[0]);
				}
			}
			if (creep.carry.energy == 0) {
				creep.say('Harvesting');
			  creep.memory.harvesting = true;
			}
		}

	} // function

}; // roleHarvester

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

	/** @param {Creep} creep **/
	run: function(creep) {

		if (creep.memory.harvesting) {
			var sources = creep.room.find(FIND_SOURCES);

			if (!creep.memory.source) {
				for (source in sources) {
					if (_.filter(Game.creeps, (creep) =>
							(creep.memory.role == 'harvester') &&
							(creep.memory.source == source)
					).length != 1) {
						creep.memory.source = source;
					}
				}
			}
			if (creep.harvest(sources[creep.memory.source]) == ERR_NOT_IN_RANGE) {
				creep.moveTo(sources[creep.memory.source]);
			}
			else if (creep.carry.energy == creep.carryCapacity) {
				creep.say('Depositing');
			  creep.memory.harvesting = false;
			}
		}
		else {
			var targets = creep.pos.findClosestByRange(FIND_STRUCTURES, {
				filter: (structure) => {
					return ((structure.structureType == STRUCTURE_CONTAINER) ||
									(structure.structureType == STRUCTURE_SPAWN));
				}
			});

			if (targets.length > 0) {
				if (creep.transfer(targets[0], RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
					creep.moveTo(targets[0]);
				}
			}
			if (creep.carry.energy == 0) {
				creep.say('Harvesting');
			  creep.memory.harvesting = true;
			}
		}

	} // function

}; // roleHarvester

module.exports = roleHarvester;<|endoftext|>


<commit_before>var Database = require('./db');
var db = new Database();

module.exports = function (req, res) {
    var errorHandle = function () {
        res.code = '4.00';
        res.end(JSON.stringify({method: 'not support'}));
    };

    var uriQuery = [];
    var existBlock = false;
    for (var i = 1; i < req.options.length; i++) {
        if (req.options[i].name === 'Uri-Query') {
            uriQuery.push(req.options[i].value.toString());
            existBlock = true;
        }
    }
    if (!existBlock) {
        return errorHandle();
    }

    var handlerGet = function () {
        var payload = {user: 1, device: 1};
        db.findOrder(payload, 1, function (dbResult) {
            console.log(dbResult);
            res.code = '2.05';
            res.end(JSON.stringify({result: dbResult}));
        });
    };

    var handPut = function () {
        res.code = '2.05';
        res.end(JSON.stringify({method: 'put'}));
    };

    var handPost = function () {
        res.code = '2.05';
        res.end(JSON.stringify({method: 'post'}));
    };

    switch (req.method) {
        case 'GET':
            handlerGet();
            break;
        case 'PUT':
            handPut();
            break;
        case 'POST':
            handPost();
            break;
        default:
            return errorHandle();
    }
};
<commit_msg>add result handle<commit_after>var Database = require('./db');
var db = new Database();

module.exports = function (req, res) {
    var errorHandle = function () {
        res.code = '4.00';
        res.end(JSON.stringify({method: 'not support'}));
    };

    var uriQuery = {};
    var existBlock = false;
    for (var i = 0; i < req.options.length; i++) {
        if (req.options[i].name === 'Uri-Query') {
            var query = req.options[i].value.toString().split(':');
            uriQuery[query[0]] = parseInt(query[1]);
            existBlock = true;
        }
    }
    if (!existBlock) {
        return errorHandle();
    }

    var handlerGet = function () {
        var payload = {user: uriQuery.user, device: uriQuery.device};
        db.find(payload, function (dbResult) {
            res.code = '2.05';
            res.end(JSON.stringify({result: dbResult}));
        });
    };

    var handPut = function () {
        res.code = '2.05';
        res.end(JSON.stringify({method: 'put'}));
    };

    var handPost = function () {
        res.code = '2.05';
        res.end(JSON.stringify({method: 'post'}));
    };

    switch (req.method) {
        case 'GET':
            handlerGet();
            break;
        case 'PUT':
            handPut();
            break;
        case 'POST':
            handPost();
            break;
        default:
            return errorHandle();
    }
};
<|endoftext|>


<commit_before>// Source: http://stackoverflow.com/a/1830844
function isNumber(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

function statBonus(statValue) {
    if(!isNumber(statValue)) {
        return false;
    }
    switch(+statValue) { // cast to number
        case 0:
            return "–";
            break;
        case 1:
            return -5;
            break;
        case 2:
            return -3;
            break;
        case 3:
            return 0;
            break;
        case 4:
            return 1;
            break;
        case 5:
            return 3;
            break;
        case 6:
            return 5;
            break;
        case 7:
            return 9;
            break;
        case 8:
            return 15;
            break;
        case 9:
            return 21;
            break;
        default:
            return false;
    }
}

var AppViewModel = {
    characterAttributes: [
        {
            name: "Physical",
            attributes: [
                {
                    name: "Strength"
                },
                {
                    name: "Endurance"
                },
                {
                    name: "Agility"
                },
                {
                    name: "Speed"
                }
            ]
        },
        {
            name: "Mental",
            attributes: [
                {
                    name: "Willpower"
                },
                {
                    name: "Insight"
                },
                {
                    name: "Reasoning"
                },
                {
                    name: "Perception"
                }
            ]
        },
        {
            name: "Social",
            attributes: [
                {
                    name: "Presence"
                },
                {
                    name: "Composure"
                },
                {
                    name: "Manipulation"
                },
                {
                    name: "Beauty"
                }
            ]
        }
    ]
};

// Activate knockout.js
var viewModel = ko.mapping.fromJS(AppViewModel);
ko.applyBindings(viewModel);

<commit_msg>Use custom create for mapping attributes.<commit_after>// Source: http://stackoverflow.com/a/1830844
function isNumber(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

function statBonus(statValue) {
    if(!isNumber(statValue)) {
        return false;
    }
    switch(+statValue) { // cast to number
        case 0:
            return "–";
            break;
        case 1:
            return -5;
            break;
        case 2:
            return -3;
            break;
        case 3:
            return 0;
            break;
        case 4:
            return 1;
            break;
        case 5:
            return 3;
            break;
        case 6:
            return 5;
            break;
        case 7:
            return 9;
            break;
        case 8:
            return 15;
            break;
        case 9:
            return 21;
            break;
        default:
            return false;
    }
}

var AppViewModel = {
    characterAttributes: [
        {
            name: "Physical",
            attributes: [
                {
                    name: "Strength"
                },
                {
                    name: "Endurance"
                },
                {
                    name: "Agility"
                },
                {
                    name: "Speed"
                }
            ]
        },
        {
            name: "Mental",
            attributes: [
                {
                    name: "Willpower"
                },
                {
                    name: "Insight"
                },
                {
                    name: "Reasoning"
                },
                {
                    name: "Perception"
                }
            ]
        },
        {
            name: "Social",
            attributes: [
                {
                    name: "Presence"
                },
                {
                    name: "Composure"
                },
                {
                    name: "Manipulation"
                },
                {
                    name: "Beauty"
                }
            ]
        }
    ]
};

var attributesMapping = {
    "attributes": {
        "create": function(options) {
            return new AttributesModel(options.data);
        }
    }
};

function AttributesModel(data) {
    ko.mapping.fromJS(data, {}, this);
    this.score = ko.observable();
    this.bonus = ko.computed(function() {
        return statBonus(this.score());
    }, this);
}

// Activate knockout.js
var viewModel = ko.mapping.fromJS(AppViewModel, attributesMapping);
ko.applyBindings(viewModel);

<|endoftext|>


<commit_before>/*'use strict';
let color = require('../config/color');

function display(user, bet) {
	return '';
}

function isMoney(money) {
	let numMoney = Number(money);
	if (isNaN(money)) return "Must be a number.";
	if (String(money).includes('.')) return "Cannot contain a decimal.";
	if (numMoney < 1) return "Cannot be less than one buck.";
	return numMoney;
}

exports.commands = {
	shell: {
		hide: function (target, room, user) {
			if (room.id !== 'casino') return this.errorReply('Shell Game can only be played in the Casino.');
			if (!this.canTalk()) return this.errorReply("You can not start Shell Games while unable to speak.");
			if (!target || target.indexOf(',') < 0) return this.parse('/help shells');

			let parts = target.split(',');
			let shell = toId(parts[0]);
			let bet = isMoney(parts[1]);
			let output = display(user, bet);
			switch (shell) {
			case 'red':
			case 'blue':
				if (Db('money').get(user.userid, 0) < bet) return this.errorReply("You do not have enough bucks to place this bet.");
				if (bet > 100) return this.errorReply("The betting limit is 100.");
				if (typeof bet === 'string') return this.errorReply('Bet was a string, report this to an admin');

				if (!room.shellgame) room.shellgame = {};
				if (room.shellgame.active) return this.errorReply('There is already a Shell Game active.');

				room.shellgame.host = user.userid;
				room.shellgame.active = true;
				room.shellgame.bet = bet;
				room.shellgame.shell = shell;
				room.shellgame.startTime = Date.now();
				Db('money').set(user.userid, Db('money').get(user.userid) - room.shellgame.bet);
				room.addRaw(output);
				this.sendReply('The ball is hidden under the ' + shell + ' shell.');
				break;
			default:
				return this.errorReply(shell + ' is not a shell. Options are red and blue.');
			}
		},
		guess: function (target, room, user) {
			if (room.id !== 'casino') return this.errorReply('Shell Game can only be played in the Casino.');
			if (!this.canTalk()) return this.errorReply('You can not play Shell Games while unable to speak.');
			if (!room.shellgame.active) return this.errorReply('There is no Shell Game currently active.');
			if (room.shellgame.host === user.userid) return this.errorReply("You hid the ball.");
			if (Db('money').get(user.userid, 0) < room.shellgame.bet) return this.errorReply("You do not have enough bucks to guess.");
			let guess = target.toLowerCase();
			let shell = room.shellgame.shell;
			switch (guess) {
			case 'red':
			case 'blue':
				if (guess === shell) {
					Db('money').set(user.userid, Db('money').get(user.userid) + room.shellgame.bet);
					room.addRaw(user + ' has correctly chosen the ' + shell + ' Shell and has won the game!');
				} else {
					Db('money').set(user.userid, Db('money').get(user.userid) - room.shellgame.bet);
					Db('money').set(room.shellgame.host, Db('money').get(room.shellgame.host) + (room.shellgame.bet * 2));
					room.addRaw(user + ' chose the ' + guess + ' shell incorrectly and lost their money!');
				}
				delete room.shellgame;
				break;
			default:
				return this.errorReply(shell + ' is not a shell. Options are red and blue.');
			}
		},
		end: function (target, room, user) {
			if (room.id !== 'casino') return this.errorReply('shell Game can only be played in the Casino.');
			if (room.shellgame.host !== user.userid && !this.can('ban', null, room)) return this.errorReply('You cannot end this shell Game.');
			if ((Date.now() - room.shellgame.startTime) < 15000 && !user.can('broadcast', null, room)) return this.errorReply("Regular users may not end a Shell game within the first minute of it starting.");
			delete room.shellgame;
			room.addRaw('
The Shell Game was ended early by ' + user + '.');
		},
	},
};   */<commit_msg>Update shell-game.js<commit_after>'use strict';
let color = require('../config/color');

function display(user, bet) {
	return '';
}

function isMoney(money) {
	let numMoney = Number(money);
	if (isNaN(money)) return "Must be a number.";
	if (String(money).includes('.')) return "Cannot contain a decimal.";
	if (numMoney < 1) return "Cannot be less than one buck.";
	return numMoney;
}

exports.commands = {
	shell: {
		hide: function (target, room, user) {
			if (room.id !== 'casino') return this.errorReply('Shell Game can only be played in the Casino.');
			if (!this.canTalk()) return this.errorReply("You can not start Shell Games while unable to speak.");
			if (!target || target.indexOf(',') < 0) return this.parse('/help shells');

			let parts = target.split(',');
			let shell = toId(parts[0]);
			let bet = isMoney(parts[1]);
			let output = display(user, bet);
			switch (shell) {
			case 'red':
			case 'blue':
				if (Db('money').get(user.userid, 0) < bet) return this.errorReply("You do not have enough bucks to place this bet.");
				if (bet > 100) return this.errorReply("The betting limit is 100.");
				if (typeof bet === 'string') return this.errorReply('Bet was a string, report this to an admin');

				if (!room.shellgame) room.shellgame = {};
				if (room.shellgame.active) return this.errorReply('There is already a Shell Game active.');

				room.shellgame.host = user.userid;
				room.shellgame.active = true;
				room.shellgame.bet = bet;
				room.shellgame.shell = shell;
				room.shellgame.startTime = Date.now();
				Db('money').set(user.userid, Db('money').get(user.userid) - room.shellgame.bet);
				room.addRaw(output);
				this.sendReply('The ball is hidden under the ' + shell + ' shell.');
				break;
			default:
				return this.errorReply(shell + ' is not a shell. Options are red and blue.');
			}
		},
		guess: function (target, room, user) {
			if (room.id !== 'casino') return this.errorReply('Shell Game can only be played in the Casino.');
			if (!this.canTalk()) return this.errorReply('You can not play Shell Games while unable to speak.');
			if (!room.shellgame.active) return this.errorReply('There is no Shell Game currently active.');
			if (room.shellgame.host === user.userid) return this.errorReply("You hid the ball.");
			if (Db('money').get(user.userid, 0) < room.shellgame.bet) return this.errorReply("You do not have enough bucks to guess.");
			let guess = target.toLowerCase();
			let shell = room.shellgame.shell;
			switch (guess) {
			case 'red':
			case 'blue':
				if (guess === shell) {
					Db('money').set(user.userid, Db('money').get(user.userid) + room.shellgame.bet);
					room.addRaw(user + ' has correctly chosen the ' + shell + ' Shell and has won the game!');
				} else {
					Db('money').set(user.userid, Db('money').get(user.userid) - room.shellgame.bet);
					Db('money').set(room.shellgame.host, Db('money').get(room.shellgame.host) + (room.shellgame.bet * 2));
					room.addRaw(user + ' chose the ' + guess + ' shell incorrectly and lost their money!');
				}
				delete room.shellgame;
				break;
			default:
				return this.errorReply(shell + ' is not a shell. Options are red and blue.');
			}
		},
		end: function (target, room, user) {
			if (room.id !== 'casino') return this.errorReply('shell Game can only be played in the Casino.');
			if (room.shellgame.host !== user.userid && !this.can('ban', null, room)) return this.errorReply('You cannot end this shell Game.');
			if ((Date.now() - room.shellgame.startTime) < 15000 && !user.can('broadcast', null, room)) return this.errorReply("Regular users may not end a Shell game within the first minute of it starting.");
			delete room.shellgame;
			room.addRaw('
The Shell Game was ended early by ' + user + '.');
		},
	},
};
<|endoftext|>


<commit_before>const ranksDataFile = DATA_DIR + 'superranks.json';

var fs = require('fs');

global.SuperRanks = {
	ranks: {},
	isHoster: function (userid) {
		if (userid === 'presidentaaether') return true;
		if (this.ranks[userid] && this.ranks[userid] === "h") return true;
		return false;
	},
	isOwner: function (userid) {
		if (this.ranks[userid] && this.ranks[userid] === "o") return true;
		return false;
	},
	isAdmin: function (userid) {
		if (userid === 'fairyclaw') return true;
		if (this.ranks[userid] && this.ranks[userid] === "a") return true;
		return false;
	}
};

if (!fs.existsSync(ranksDataFile))
	fs.writeFileSync(ranksDataFile, JSON.stringify(SuperRanks.ranks));

SuperRanks.ranks = JSON.parse(fs.readFileSync(ranksDataFile).toString());

function writeRankData() {
	try {
		fs.writeFileSync(ranksDataFile, JSON.stringify(SuperRanks.ranks));
	} catch (e) {}
}

exports.commands = {
	ga: 'giveaccess',
	giveaccess: function (target, room, user) {
		if (!SuperRanks.isHoster(user.userid) && !SuperRanks.isOwner(user.userid)) return this.sendReply('/giveaccess - access denied');
		if (!target) return this.sendReply('Usage: /giveaccess user, [hoster/owner/admin]');
		target = this.splitTarget(target, true);
		var targetUser = this.targetUser;
		var userid = toId(this.targetUsername);
		var name = targetUser ? targetUser.name : this.targetUsername;
		if (!userid) return this.sendReply('Usage: /giveaccess user, [hoster/owner/admin]');
		if (!SuperRanks.ranks[userid]) {
			if (!targetUser) {
				return this.sendReply("User '" + name + "' is offline and unauthed, and so can't be promoted.");
			}
			if (!targetUser.registered) {
				return this.sendReply("User '" + name + "' is unregistered, and so can't be promoted.");
			}
		}
		var currentRank = SuperRanks.ranks[userid] || ' ';
		var toRank = target.trim() ? target.trim().charAt(0) : 'none';
		if (!(toRank in {h: 1, o: 1, a: 1})) return this.sendReply('Usage: /giveaccess user, [hoster/owner/admin]');
		if ((toRank === 'h' || toRank === 'o' || currentRank === 'h' || currentRank === 'o') && !SuperRanks.isHoster(user.userid)) return this.sendReply('/giveaccess - access denied');
		SuperRanks.ranks[userid] = toRank;
		writeRankData();
		var nameTable = {
			h: "Hoster",
			o: "Owner",
			a: "Admin Director"
		};
		this.sendReply("User " + name + " is now " + nameTable[toRank]);
	},
	ra: 'removeaccess',
	removeaccess: function (target, room, user) {
		if (!SuperRanks.isHoster(user.userid) && !SuperRanks.isOwner(user.userid)) return this.sendReply('/removeaccess - access denied');
		if (!target) return this.sendReply('Usage: /removeaccess user');
		var userid = toId(target);
		if (!SuperRanks.ranks[userid]) return this.sendReply("User " + userid + " does not have access");
		var currentRank = SuperRanks.ranks[userid];
		if ((currentRank === 'h' || currentRank === 'o') && !SuperRanks.isHoster(user.userid)) return this.sendReply('/removeaccess - access denied');
		delete SuperRanks.ranks[userid];
		writeRankData();
		this.sendReply("User " + userid + " removed from excepted users");
	},
	hosters: function (target, room, user, connection) {
		var ranks = SuperRanks.ranks;
		var hosters = [], owners = [], admins = [];
		for (var i in ranks) {
			switch (ranks[i]) {
				case 'h':
					hosters.push(i);
					break;
				case 'o':
					owners.push(i);
					break;
				case 'a':
					admins.push(i);
					break;
			}
		}
		connection.popup("**Hosters:** " + (hosters.length ? hosters.join(", ") : "__(ninguno)__") + "\n\n" + "**Owners:** " + (owners.length ? owners.join(", ") : "__(ninguno)__") + "\n\n" + "**Admin Directors:** " + (admins.length ? admins.join(", ") : "__(ninguno)__"));
	}
};
<commit_msg>Update superranks.js<commit_after>const ranksDataFile = DATA_DIR + 'superranks.json';

var fs = require('fs');

global.SuperRanks = {
	ranks: {},
	isHoster: function (userid) {
		if (userid === 'presidentaaether') return true;
		if (this.ranks[userid] && this.ranks[userid] === "h") return true;
		return false;
	},
	isOwner: function (userid) {
		if (this.ranks[userid] && this.ranks[userid] === "o") return true;
		return false;
	},
	isAdmin: function (userid) {
		if (userid === '') return true;
		if (this.ranks[userid] && this.ranks[userid] === "a") return true;
		return false;
	}
};

if (!fs.existsSync(ranksDataFile))
	fs.writeFileSync(ranksDataFile, JSON.stringify(SuperRanks.ranks));

SuperRanks.ranks = JSON.parse(fs.readFileSync(ranksDataFile).toString());

function writeRankData() {
	try {
		fs.writeFileSync(ranksDataFile, JSON.stringify(SuperRanks.ranks));
	} catch (e) {}
}

exports.commands = {
	ga: 'giveaccess',
	giveaccess: function (target, room, user) {
		if (!SuperRanks.isHoster(user.userid) && !SuperRanks.isOwner(user.userid)) return this.sendReply('/giveaccess - access denied');
		if (!target) return this.sendReply('Usage: /giveaccess user, [hoster/owner/admin]');
		target = this.splitTarget(target, true);
		var targetUser = this.targetUser;
		var userid = toId(this.targetUsername);
		var name = targetUser ? targetUser.name : this.targetUsername;
		if (!userid) return this.sendReply('Usage: /giveaccess user, [hoster/owner/admin]');
		if (!SuperRanks.ranks[userid]) {
			if (!targetUser) {
				return this.sendReply("User '" + name + "' is offline and unauthed, and so can't be promoted.");
			}
			if (!targetUser.registered) {
				return this.sendReply("User '" + name + "' is unregistered, and so can't be promoted.");
			}
		}
		var currentRank = SuperRanks.ranks[userid] || ' ';
		var toRank = target.trim() ? target.trim().charAt(0) : 'none';
		if (!(toRank in {h: 1, o: 1, a: 1})) return this.sendReply('Usage: /giveaccess user, [hoster/owner/admin]');
		if ((toRank === 'h' || toRank === 'o' || currentRank === 'h' || currentRank === 'o') && !SuperRanks.isHoster(user.userid)) return this.sendReply('/giveaccess - access denied');
		SuperRanks.ranks[userid] = toRank;
		writeRankData();
		var nameTable = {
			h: "Hoster",
			o: "Owner",
			a: "Admin Director"
		};
		this.sendReply("User " + name + " is now " + nameTable[toRank]);
	},
	ra: 'removeaccess',
	removeaccess: function (target, room, user) {
		if (!SuperRanks.isHoster(user.userid) && !SuperRanks.isOwner(user.userid)) return this.sendReply('/removeaccess - access denied');
		if (!target) return this.sendReply('Usage: /removeaccess user');
		var userid = toId(target);
		if (!SuperRanks.ranks[userid]) return this.sendReply("User " + userid + " does not have access");
		var currentRank = SuperRanks.ranks[userid];
		if ((currentRank === 'h' || currentRank === 'o') && !SuperRanks.isHoster(user.userid)) return this.sendReply('/removeaccess - access denied');
		delete SuperRanks.ranks[userid];
		writeRankData();
		this.sendReply("User " + userid + " removed from excepted users");
	},
	hosters: function (target, room, user, connection) {
		var ranks = SuperRanks.ranks;
		var hosters = [], owners = [], admins = [];
		for (var i in ranks) {
			switch (ranks[i]) {
				case 'h':
					hosters.push(i);
					break;
				case 'o':
					owners.push(i);
					break;
				case 'a':
					admins.push(i);
					break;
			}
		}
		connection.popup("**Hosters:** " + (hosters.length ? hosters.join(", ") : "__(ninguno)__") + "\n\n" + "**Owners:** " + (owners.length ? owners.join(", ") : "__(ninguno)__") + "\n\n" + "**Admin Directors:** " + (admins.length ? admins.join(", ") : "__(ninguno)__"));
	}
};
<|endoftext|>