<commit_before>/** @license MIT License (c) copyright B Cavalier & J Hann */

/**
 * wire/cola plugin
 *
 * wire is part of the cujo.js family of libraries (http://cujojs.com/)
 *
 * Licensed under the MIT License at:
 * http://www.opensource.org/licenses/mit-license.php
 */

(function(define) {
define(['when', 'cola/AdapterResolver',
	'cola/ArrayAdapter', 'cola/dom/NodeListAdapter',
	'cola/ResultSetAdapter', 'cola/QueryAdapter', 'cola/mediator/syncCollections',
	'cola/ObjectAdapter', 'cola/dom/NodeAdapter',
	'cola/ResultAdapter', 'cola/mediator/syncProperties',
	'cola/addPropertyTransforms', 'cola/transformCollection', 'cola/transform/compose'],
function(when, adapterResolver,
	ArrayAdapter, NodeListAdapter, ResultSetAdapter, QueryAdapter, syncCollections,
	ObjectAdapter, NodeAdapter,
	ResultAdapter, syncProperties,
	addPropertyTransforms, transformCollection, compose
) {

	var cachedBindings, isArray, undef, slice;

	// TODO: move most of this stuff, including adapter registration to cola.js
	// TODO: implement wire$build that auto-adds these deps to build
	adapterResolver.register(ArrayAdapter, 'collection');
	adapterResolver.register(NodeListAdapter, 'collection');
//	adapterResolver.register(ResultSetAdapter, 'collection');
	adapterResolver.register(QueryAdapter, 'collection');
	adapterResolver.register(NodeAdapter, 'object');
	adapterResolver.register(ObjectAdapter, 'object');
//	adapterResolver.register(ResultAdapter, 'object');

	function querySelector (selector, node) {
		return node.querySelector(selector);
	}

	isArray = Array.isArray || function(it) {
		return Object.prototype.toString.call(it) == '[object Array]';
	};

	slice = Array.prototype.slice;

	/**
	 * "globally" cached bindings.  Cache bindings here so that a bind can find,
	 * process, and remove them later
	 * @private
 	 */
	cachedBindings = [];

	/**
	 * @private
	 * @param target anything - target component for which to find cached bindings
	 * @param found {Function} function to call with existing cached bindings
	 * @param [notFound] {Function} function to call if no cached bindings found
	 */
	function findCachedBindings(target, found, notFound) {
		for(var i = 0, len = cachedBindings.length; i < len; i++) {
			if(cachedBindings[i].target === target) {
				return found(cachedBindings, i, cachedBindings[i]);
			}
		}

		return notFound(cachedBindings);
	}

	function mixin(dst, src) {
		for(var p in src) {
			dst[p] = src[p];
		}
		return dst;
	}

	function mergeBindings(bindingDef, bindings) {
		mixin(bindingDef.bindings, bindings);
	}

	function createPropertyTransform(transforms, wire) {

		if(typeof transforms == 'function') {
			// If it's a function, just use it
			return transforms;
		} else if(typeof transforms == 'string') {
			// If it's a string, assume it's the name of a component
			// that is a transform function, and resolve it.
			return wire.resolveRef(transforms);
		}

		if(!isArray(transforms)) {
			transforms = [transforms];
		}

		return when.reduce(transforms,
			function(txList, txSpec) {
				var name;

				// Determine the name of the transform and try
				// to resolve it as a component in the current
				// wire spec
				if(typeof txSpec == 'string') {
					name = txSpec;
				} else {
					for(name in txSpec) {
						if(name != 'inverse') break;
					}
				}

				return when(wire.resolveRef(name),
					function(transform) {
						txList.push(function() {
							var args = slice.call(arguments);
							return transform.apply(undef, args.concat(txSpec[name]));
						});
						return txList;
					}
				);
			}, [])
		.then(
			function(txList) {
				return txList.length > 1 ? compose(txList) : txList[0];
			}
		);
	}

	function setupBinding(bindingSpecs, name, wire) {
		var bindingSpec, binding;

		bindingSpec = mixin({}, bindingSpecs[name]);
		binding = {
			name: name,
			spec: bindingSpec
		};

		return bindingSpec.transform
			? when(createPropertyTransform(bindingSpec.transform, wire),
				function(propertyTransform) {
					binding.spec.transform = propertyTransform;
					return binding;
				})
			: binding;
	}

	function setupBindings(bindingSpecs, wire) {
		var promises = [];

		for(var name in bindingSpecs) {
			promises.push(setupBinding(bindingSpecs, name, wire));
		}

		return when.reduce(promises, function(bindings, bindingSpec) {
			bindings[bindingSpec.name] = bindingSpec.spec;
			return bindings;
		}, {});
	}

	function cacheBindings(resolver, proxy, wire, pluginOptions) {
		// wire the bindings immediately, in the same context as they
		// are declared.  Since bindings/bind may be in different
		// contexts, deferring the wiring until bind could cause
		// lots of confusion, since they'd be wired in that context,
		// not in the one where they are declared.
		when(wire(proxy.options),
			function(bindings) {

				return when(setupBindings(bindings, wire),
					function(bindings) {
						findCachedBindings(proxy.target,
							function(cachedBindings, i, bindingDef) {
								// Merge any existing bindings
								mergeBindings(bindingDef, bindings);
							},
							function(cachedBindings) {
								// Cache new bindings if none exist for
								// the current target
								var newBindings = {
									target: proxy.target,
									bindings: bindings,
									pluginOptions: pluginOptions
								};
								cachedBindings.push(newBindings);
							}
						);
					}
				);
			}
		).then(resolver.resolve, resolver.reject);
	}

	function removeCachedBindings(resolver, proxy /*, wire */) {
		// If there were any bindings that were never used (via "bind"), we
		// can remove them now since the component is being destroyed.
		findCachedBindings(proxy.target, function(cachedBindings, i) {
			cachedBindings.splice(i, 1);
		});

		resolver.resolve();
	}

	function collectPropertyTransforms(bindings) {
		var name, propertyTransforms, transform;

		propertyTransforms = {};
		for(name in bindings) {
			transform = bindings[name].transform;
			if(transform) {
				propertyTransforms[name] = transform;
			}
		}

		return propertyTransforms;
	}

	function createAdapter(obj, type, options) {
		// FIXME: This is just for initial testing
		var Adapter, adapter;
		Adapter = adapterResolver(obj, type);
		// if (!Adapter) throw new Error('wire/cola: could not find Adapter constructor for ' + type);
		adapter = Adapter ? new Adapter(obj, options) : obj;

		if (options.bindings && type == 'object') {
			adapter = addPropertyTransforms(adapter, collectPropertyTransforms(options.bindings));
		}

		return adapter;
	}

	function doBind(target, datasource, bindings, options, wire) {
		// TODO: create comparator from options (e.g. sortBy: ['prop1', 'prop2'])
		// TODO: create symbolizer from options (e.g. key: ['name', 'version'])
		var adapter1, adapter2, collectionTransform;

		options = mixin({
			querySelector: querySelector
		}, options || {});

		// TODO: ensure these are in the right order so transforms are always in the right order
		adapter1 = createAdapter(datasource, 'collection', options);

		collectionTransform = options.transform;
		if (collectionTransform) {
			if (typeof collectionTransform != 'function') {
				collectionTransform = compose(collectionTransform);
			}
			adapter1 = transformCollection(adapter1, collectionTransform);
		}

		options = mixin({ bindings: bindings }, options);
		adapter2 = createAdapter(target, 'collection', options);

		// FIXME: throw if we can't create an adapter?
		if (!(adapter1 && adapter2)) return;

		return syncCollections(adapter1, adapter2, createAdapter);
	}

	return {
		wire$plugin: function(ready, destroyed, pluginOptions) {

			var unmediators = [];

			// TODO: allow querySelector to be specified in pluginOptions?

			function bindFacet(resolver, proxy, wire) {
				// Find any cached bindings for this component, and if found
				// setup cola data binding.
				findCachedBindings(proxy.target,
					function(cachedBindings, i, bindingDef) {
						// Remove cached bindings
						cachedBindings.splice(i, 1);

						// Wire pluginOptions, then bind to the datasource
						when(wire(proxy.options), function(options) {
							var datasource;

							if(options.to) {
								datasource = options.to;
							} else {
								datasource = options;
								options = {};
							}

							// TODO: mixin proxy.options onto pluginOptions?
							options = mixin(options, bindingDef.pluginOptions);

							// Use cached bindings to setup cola data binding for
							// the current target component
							var unmediate = doBind(bindingDef.target, datasource, bindingDef.bindings, options);

							unmediators.push(unmediate);

							// TODO: Store cola info in wire$plugin so we can tear the bindings down
							// the component is destroyed?

						}).then(resolver.resolve, resolver.reject);

					},
					function() {
						// No bindings found: "bind" was used without "bindings"
						resolver.reject('bind: no bindings declared for component: ' + proxy.id);

					}
				);
			}

			function destroyMediators() {
				var unmediate, i;
				i = unmediators.length;
				while(unmediate = unmediators[--i]) unmediate();
			}

			function cacheBindingsAndOptions (resolver, proxy, wire) {
				return cacheBindings(resolver, proxy, wire, pluginOptions);
			}

			destroyed.then(destroyMediators);

			return {
				facets: {
					bindings: {
						configure: cacheBindingsAndOptions,
						destroy: removeCachedBindings
					},
					bind: {
						initialize: bindFacet
					}
				}
			};
		}
	};
});

})(typeof define == 'function'
	// use define for AMD if available
	? define
	: function(deps, factory) {
		module.exports = factory.apply(this, deps.map(function(x) {
			return require(x);
		}));
	}
);
<commit_msg>Last commit wasnt allowing function  directly in a prop transform array.  Now it does<commit_after>/** @license MIT License (c) copyright B Cavalier & J Hann */

/**
 * wire/cola plugin
 *
 * wire is part of the cujo.js family of libraries (http://cujojs.com/)
 *
 * Licensed under the MIT License at:
 * http://www.opensource.org/licenses/mit-license.php
 */

(function(define) {
define(['when', 'cola/AdapterResolver',
	'cola/ArrayAdapter', 'cola/dom/NodeListAdapter',
	'cola/ResultSetAdapter', 'cola/QueryAdapter', 'cola/mediator/syncCollections',
	'cola/ObjectAdapter', 'cola/dom/NodeAdapter',
	'cola/ResultAdapter', 'cola/mediator/syncProperties',
	'cola/addPropertyTransforms', 'cola/transformCollection', 'cola/transform/compose'],
function(when, adapterResolver,
	ArrayAdapter, NodeListAdapter, ResultSetAdapter, QueryAdapter, syncCollections,
	ObjectAdapter, NodeAdapter,
	ResultAdapter, syncProperties,
	addPropertyTransforms, transformCollection, compose
) {

	var cachedBindings, isArray, undef, slice;

	// TODO: move most of this stuff, including adapter registration to cola.js
	// TODO: implement wire$build that auto-adds these deps to build
	adapterResolver.register(ArrayAdapter, 'collection');
	adapterResolver.register(NodeListAdapter, 'collection');
//	adapterResolver.register(ResultSetAdapter, 'collection');
	adapterResolver.register(QueryAdapter, 'collection');
	adapterResolver.register(NodeAdapter, 'object');
	adapterResolver.register(ObjectAdapter, 'object');
//	adapterResolver.register(ResultAdapter, 'object');

	function querySelector (selector, node) {
		return node.querySelector(selector);
	}

	isArray = Array.isArray || function(it) {
		return Object.prototype.toString.call(it) == '[object Array]';
	};

	slice = Array.prototype.slice;

	/**
	 * "globally" cached bindings.  Cache bindings here so that a bind can find,
	 * process, and remove them later
	 * @private
 	 */
	cachedBindings = [];

	/**
	 * @private
	 * @param target anything - target component for which to find cached bindings
	 * @param found {Function} function to call with existing cached bindings
	 * @param [notFound] {Function} function to call if no cached bindings found
	 */
	function findCachedBindings(target, found, notFound) {
		for(var i = 0, len = cachedBindings.length; i < len; i++) {
			if(cachedBindings[i].target === target) {
				return found(cachedBindings, i, cachedBindings[i]);
			}
		}

		return notFound(cachedBindings);
	}

	function mixin(dst, src) {
		for(var p in src) {
			dst[p] = src[p];
		}
		return dst;
	}

	function mergeBindings(bindingDef, bindings) {
		mixin(bindingDef.bindings, bindings);
	}

	function createPropertyTransform(transforms, wire) {

		// Could optimize the single function/string case here
		// by avoiding the when.reduce.  If wire spec parsing perf
		// ever becomes a problem, we can optimize a bit here.

		if(!isArray(transforms)) {
			transforms = [transforms];
		}

		return when.reduce(transforms,
			function(txList, txSpec) {
				var name;

				if(typeof txSpec == 'function') {
					return txSpec;
				}

				// Determine the name of the transform and try
				// to resolve it as a component in the current
				// wire spec
				if(typeof txSpec == 'string') {
					name = txSpec;
				} else {
					for(name in txSpec) {
						if(name != 'inverse') break;
					}
				}

				return when(wire.resolveRef(name),
					function(transform) {
						txList.push(function() {
							var args = slice.call(arguments);
							return transform.apply(undef, args.concat(txSpec[name]));
						});
						return txList;
					}
				);
			}, [])
		.then(
			function(txList) {
				return txList.length > 1 ? compose(txList) : txList[0];
			}
		);
	}

	function setupBinding(bindingSpecs, name, wire) {
		var bindingSpec, binding;

		bindingSpec = mixin({}, bindingSpecs[name]);
		binding = {
			name: name,
			spec: bindingSpec
		};

		return bindingSpec.transform
			? when(createPropertyTransform(bindingSpec.transform, wire),
				function(propertyTransform) {
					binding.spec.transform = propertyTransform;
					return binding;
				})
			: binding;
	}

	function setupBindings(bindingSpecs, wire) {
		var promises = [];

		for(var name in bindingSpecs) {
			promises.push(setupBinding(bindingSpecs, name, wire));
		}

		return when.reduce(promises, function(bindings, bindingSpec) {
			bindings[bindingSpec.name] = bindingSpec.spec;
			return bindings;
		}, {});
	}

	function cacheBindings(resolver, proxy, wire, pluginOptions) {
		// wire the bindings immediately, in the same context as they
		// are declared.  Since bindings/bind may be in different
		// contexts, deferring the wiring until bind could cause
		// lots of confusion, since they'd be wired in that context,
		// not in the one where they are declared.
		when(wire(proxy.options),
			function(bindings) {

				return when(setupBindings(bindings, wire),
					function(bindings) {
						findCachedBindings(proxy.target,
							function(cachedBindings, i, bindingDef) {
								// Merge any existing bindings
								mergeBindings(bindingDef, bindings);
							},
							function(cachedBindings) {
								// Cache new bindings if none exist for
								// the current target
								var newBindings = {
									target: proxy.target,
									bindings: bindings,
									pluginOptions: pluginOptions
								};
								cachedBindings.push(newBindings);
							}
						);
					}
				);
			}
		).then(resolver.resolve, resolver.reject);
	}

	function removeCachedBindings(resolver, proxy /*, wire */) {
		// If there were any bindings that were never used (via "bind"), we
		// can remove them now since the component is being destroyed.
		findCachedBindings(proxy.target, function(cachedBindings, i) {
			cachedBindings.splice(i, 1);
		});

		resolver.resolve();
	}

	function collectPropertyTransforms(bindings) {
		var name, propertyTransforms, transform;

		propertyTransforms = {};
		for(name in bindings) {
			transform = bindings[name].transform;
			if(transform) {
				propertyTransforms[name] = transform;
			}
		}

		return propertyTransforms;
	}

	function createAdapter(obj, type, options) {
		// FIXME: This is just for initial testing
		var Adapter, adapter;
		Adapter = adapterResolver(obj, type);
		// if (!Adapter) throw new Error('wire/cola: could not find Adapter constructor for ' + type);
		adapter = Adapter ? new Adapter(obj, options) : obj;

		if (options.bindings && type == 'object') {
			adapter = addPropertyTransforms(adapter, collectPropertyTransforms(options.bindings));
		}

		return adapter;
	}

	function doBind(target, datasource, bindings, options, wire) {
		// TODO: create comparator from options (e.g. sortBy: ['prop1', 'prop2'])
		// TODO: create symbolizer from options (e.g. key: ['name', 'version'])
		var adapter1, adapter2, collectionTransform;

		options = mixin({
			querySelector: querySelector
		}, options || {});

		// TODO: ensure these are in the right order so transforms are always in the right order
		adapter1 = createAdapter(datasource, 'collection', options);

		collectionTransform = options.transform;
		if (collectionTransform) {
			if (typeof collectionTransform != 'function') {
				collectionTransform = compose(collectionTransform);
			}
			adapter1 = transformCollection(adapter1, collectionTransform);
		}

		options = mixin({ bindings: bindings }, options);
		adapter2 = createAdapter(target, 'collection', options);

		// FIXME: throw if we can't create an adapter?
		if (!(adapter1 && adapter2)) return;

		return syncCollections(adapter1, adapter2, createAdapter);
	}

	return {
		wire$plugin: function(ready, destroyed, pluginOptions) {

			var unmediators = [];

			// TODO: allow querySelector to be specified in pluginOptions?

			function bindFacet(resolver, proxy, wire) {
				// Find any cached bindings for this component, and if found
				// setup cola data binding.
				findCachedBindings(proxy.target,
					function(cachedBindings, i, bindingDef) {
						// Remove cached bindings
						cachedBindings.splice(i, 1);

						// Wire pluginOptions, then bind to the datasource
						when(wire(proxy.options), function(options) {
							var datasource;

							if(options.to) {
								datasource = options.to;
							} else {
								datasource = options;
								options = {};
							}

							// TODO: mixin proxy.options onto pluginOptions?
							options = mixin(options, bindingDef.pluginOptions);

							// Use cached bindings to setup cola data binding for
							// the current target component
							var unmediate = doBind(bindingDef.target, datasource, bindingDef.bindings, options);

							unmediators.push(unmediate);

							// TODO: Store cola info in wire$plugin so we can tear the bindings down
							// the component is destroyed?

						}).then(resolver.resolve, resolver.reject);

					},
					function() {
						// No bindings found: "bind" was used without "bindings"
						resolver.reject('bind: no bindings declared for component: ' + proxy.id);

					}
				);
			}

			function destroyMediators() {
				var unmediate, i;
				i = unmediators.length;
				while(unmediate = unmediators[--i]) unmediate();
			}

			function cacheBindingsAndOptions (resolver, proxy, wire) {
				return cacheBindings(resolver, proxy, wire, pluginOptions);
			}

			destroyed.then(destroyMediators);

			return {
				facets: {
					bindings: {
						configure: cacheBindingsAndOptions,
						destroy: removeCachedBindings
					},
					bind: {
						initialize: bindFacet
					}
				}
			};
		}
	};
});

})(typeof define == 'function'
	// use define for AMD if available
	? define
	: function(deps, factory) {
		module.exports = factory.apply(this, deps.map(function(x) {
			return require(x);
		}));
	}
);
<|endoftext|>


<commit_before>var path = require('path');

// see https://code.google.com/p/selenium/downloads/list for latest
var version = '2.37.0';

module.exports = {
  selenium: {
    path: path.join(__dirname, '.selenium', version, 'server.jar'),
    v: version
  },
  chromeDr: {
    path: path.join(__dirname, '.selenium', version, 'chromedriver'),
    // see http://chromedriver.storage.googleapis.com/index.html
    v: '2.6'
  }
};<commit_msg>working selenium version on linux is 2.35<commit_after>var path = require('path');

// see https://code.google.com/p/selenium/downloads/list for latest
var version = '2.35.0';

module.exports = {
  selenium: {
    path: path.join(__dirname, '.selenium', version, 'server.jar'),
    v: version
  },
  chromeDr: {
    path: path.join(__dirname, '.selenium', version, 'chromedriver'),
    // see http://chromedriver.storage.googleapis.com/index.html
    v: '2.6'
  }
};<|endoftext|>


<commit_before>(function () {
	"use strict";

	var CONFIG = {
		serverUid : "http",
		serverGid : "http",
		listenIPv4 : true,
		listenIPv6 : true,
		servicePort : 37320,
		workersMaxNum : 256,
		workersKeepIdle : 7200,	// Unit: second
		workersTimeout : 60,	// Unit: second
		messageCap : 1024 * 16	// Unit: octet
	},

	Messenger = function (salt, type, payload) {
		var messageTypeRegex = /^(?:header|body|end)$/;

		this.salt = salt;
		this.type = messageTypeRegex.test(type) === true ? type : "unknown";
		this.payload = payload;
	},
	RequestHeaderMessenger = function (salt, invoking, req) {
		Messenger.call(this, salt, "header", {
			invoking : invoking,
			params : req.params
		});
	},
	ResponseHeaderMessenger = function (salt, headers) {
		Messenger.call(this, salt, "header", {
			statusCode : 200,
			headers : headers
		});
	},

	NodePool = function () {},

	cluster = require("cluster");

	NodePool.prototype.balancer = function () {
		var server = require("./scgi.js").createServer(),

		url = require("url"),

		idleWorker = function () {
			this.isIdle = true;
			this.stopIdling = setTimeout(this.kill.bind(this), CONFIG.workersKeepIdle * 1000);
		},

		invokeWorker = function (path) {
			var worker = null, numOfActiveWorkers = 0;

			for (let workerId in cluster.workers) {
				numOfActiveWorkers += 1;

				if (cluster.workers[workerId].workFor === path && cluster.workers[workerId].isIdle === true) {
					worker = cluster.workers[workerId];
					clearTimeout(cluster.workers[workerId].stopIdling);
					break;
				}
			}

			if (worker === null) {
				if (numOfActiveWorkers >= CONFIG.workersMaxNum) {
					return null;
				}

				worker = cluster.fork();
				worker.workFor = path;
				worker.idle = idleWorker;
			}

			worker.isIdle = false;

			return worker;
		},

		workerMessageReceptor = function (workerMes) {
			var res = this.res, worker = this.worker;

			if (workerMes.salt !== this.salt) {
				return;
			}

			switch (workerMes.type) {
				case "header":
					if (! isNaN(workerMes.payload.statusCode)) {
						res.setStatus(workerMes.payload.statusCode);
					}

					workerMes.payload.headers.forEach(function (header) {
						res.setHeader(header);
					});

					res.flushHeaders();

					break;

				case "body":
					res.write(new Buffer(workerMes.payload));
					break;

				case "end":
					res.end();
					worker.removeListener("message", this.workerMessageReceiver);
					worker.idle();
					break;

				default:
					break;
			}
		},

		onReqData = function (bChunk) {
			var messageContainer = new Messenger(this.salt, "body", null), p = 0;

			while (p < bChunk.length) {
				messageContainer.payload = bChunk.slice(
					p,
					p = p + CONFIG.messageCap < bChunk.length ? p + CONFIG.messageCap : bChunk.length
				);
				this.worker.send(messageContainer);
			}
		},

		onReqEnd = function () {
			this.worker.send(new Messenger(this.salt, "end"));
			this.worker.on("message", this.workerMessageReceiver);
		},

		onResClose = function () {
			this.worker.kill();
		},

		timeoutResponse = function () {
			this.res.setStatus(408);
			this.res.flushHeaders(true);
			this.res.end();
			this.worker.kill();
		},

		responder = function (req, res) {
			var salt = Math.random(),
			requested = url.parse(req.params.SCRIPT_FILENAME.replace(/^[^:]*:scgi:/, "scgi:")),
			invoking = url.parse(requested.pathname).pathname,

			worker = invokeWorker(invoking),

			resources = {
				salt : salt,
				res : res,
				worker : worker
			};

			if (worker === null) {
				res.setStatus(503);
				res.flushHeaders(true);
				res.end();
				return;
			}

			resources.workerMessageReceiver = workerMessageReceptor.bind(resources);

			worker.send(new RequestHeaderMessenger(salt, invoking, req));

			req.on("data", onReqData.bind(resources));
			req.on("end", onReqEnd.bind(resources));
			res.on("close", onResClose.bind(resources));

			req.setTimeout(CONFIG.workersTimeout * 1000, timeoutResponse.bind(resources));
		};

		CONFIG.listenIPv4 && server.listen(CONFIG.servicePort, "0.0.0.0");
		CONFIG.listenIPv6 && server.listen(CONFIG.servicePort, "::");

		server.on("request", responder);
	};

	NodePool.prototype.worker = function () {
		var built = null, request = null,

		fs = require("fs"),

		genInstanceInterface = function (request) {
			var ret = {},

			salt = request.salt,

			responseStatus = NaN,
			responseHeaders = [],
			isHeaderSent = false,

			bCache = {
				chunks : [],
				cachedLength : 0
			},

			flushHeaders = function () {
				var messageContainer = new ResponseHeaderMessenger(salt, responseHeaders);

				if(! isNaN(responseStatus)) {
					messageContainer.payload.statusCode = responseStatus;
				}

				process.send(messageContainer);
				isHeaderSent = true;
			};

			ret.request = {
				params : request.header.params,
				body : Buffer.concat(request.body.chunks, request.body.length)
			};

			ret.setStatus = function (sCode, reasonPhrase) {
				responseStatus = parseInt(sCode, 10);

				if (reasonPhrase !== undefined) {
					responseHeaders.push(["Status:", sCode.toString(), reasonPhrase].join(" "));
				}
			};

			ret.setHeader = function (expr) {
				responseHeaders.push(expr);
			};

			ret.flush = function () {
				var messageContainer = new Messenger(salt, "body", null),
				bChunk = typeof bCache.chunks[0] === "string" ? bCache.chunks.join("") : Buffer.concat(bCache.chunks, bCache.chachedLength);

				isHeaderSent === false && flushHeaders();

				for (let p = 0; p < bChunk.length;) {
					messageContainer.payload = bChunk.slice(
						p,
						p = p + CONFIG.messageCap < bChunk.length ? p + CONFIG.messageCap : bChunk.length
					);
					process.send(messageContainer);
				}

				bCache.chunks = [];
				bCache.cachedLength = 0;
			};

			ret.echo = function(data) {
				var toBeCached = null;

				if (data === undefined || data === null || data.length === 0) {
					return;
				}

				if (Buffer.isBuffer(data) === true) {
					if (bCache.length > 0 && Buffer.isBuffer(bCache.chunks[0]) !== true) {
						ret.flush();
					}

					toBeCached = data;
				} else {
					if (bCache.length > 0 && typeof bCache.chunks[0] !== typeof "") {
						ret.flush();
					}

					toBeCached = typeof data === typeof "" ? data : data.toString();
				}

				if (bCache.cachedLength + toBeCached.length > CONFIG.messageCap) {
					ret.flush();
				}

				bCache.chunks.push(toBeCached);
				bCache.cachedLength += toBeCached.length;

				if (toBeCached.length > CONFIG.messageCap) {
					ret.flush();
				}
			};

			ret.end = function () {
				isHeaderSent === false && flushHeaders();
				ret.flush();
				process.send(new Messenger(salt, "end"));
			};

			return ret;
		},

		respondBalancerRequest = function (request) {
			var instanceInterface = genInstanceInterface(request);

			try {
				process.chdir(require("path").dirname(fs.realpathSync(request.header.invoking)));

				if (built === null || fs.statSync(request.header.invoking).ctime.getTime() > built.builtAt.getTime()) {
					delete require.cache[fs.realpathSync(request.header.invoking)];
					built = require(request.header.invoking);
					built.builtAt = new Date();
				}

				instanceInterface.setHeader("Content-Type: text/html; charset=UTF-8");
				built.exec(instanceInterface);
			} catch (e) {
				instanceInterface.setStatus(500);
				instanceInterface.end();
				cluster.worker.kill();
			}
		},

		balancerMessageReceptor = function (messenger) {
			switch (messenger.type) {
				case "header":
					request = {
						salt : messenger.salt,
						header : messenger.payload,
						body : {
							length : 0,
							chunks : []
						}
					};
					break;

				case "body":
					if (messenger.salt === request.salt) {
						let newBodyChunk = new Buffer(messenger.payload);

						request.body.chunks.push(newBodyChunk);
						request.body.length += newBodyChunk.length;
					}
					break;

				case "end":
					respondBalancerRequest(request);
					break;
				default:
					break;
			}
		};

		process.on("message", balancerMessageReceptor);
	};

	process.setuid(CONFIG.serverUid) && process.setgid(CONFIG.serverGid);

	if (cluster.isMaster === true) {
		new NodePool().balancer();
	} else if (cluster.isWorker === true) {
		new NodePool().worker();
	}
})();
<commit_msg>[core] More explicit counter measure for a quirk in Apache proxy module<commit_after>(function () {
	"use strict";

	var CONFIG = {
		serverUid : "http",
		serverGid : "http",
		listenIPv4 : true,
		listenIPv6 : true,
		servicePort : 37320,
		workersMaxNum : 256,
		workersKeepIdle : 7200,	// Unit: second
		workersTimeout : 60,	// Unit: second
		messageCap : 1024 * 16	// Unit: octet
	},

	Messenger = function (salt, type, payload) {
		var messageTypeRegex = /^(?:header|body|end)$/;

		this.salt = salt;
		this.type = messageTypeRegex.test(type) === true ? type : "unknown";
		this.payload = payload;
	},
	RequestHeaderMessenger = function (salt, invoking, req) {
		Messenger.call(this, salt, "header", {
			invoking : invoking,
			params : req.params
		});
	},
	ResponseHeaderMessenger = function (salt, headers) {
		Messenger.call(this, salt, "header", {
			statusCode : 200,
			headers : headers
		});
	},

	NodePool = function () {},

	cluster = require("cluster");

	NodePool.prototype.balancer = function () {
		var server = require("./scgi.js").createServer(),

		url = require("url"),

		idleWorker = function () {
			this.isIdle = true;
			this.stopIdling = setTimeout(this.kill.bind(this), CONFIG.workersKeepIdle * 1000);
		},

		invokeWorker = function (path) {
			var worker = null, numOfActiveWorkers = 0;

			for (let workerId in cluster.workers) {
				numOfActiveWorkers += 1;

				if (cluster.workers[workerId].workFor === path && cluster.workers[workerId].isIdle === true) {
					worker = cluster.workers[workerId];
					clearTimeout(cluster.workers[workerId].stopIdling);
					break;
				}
			}

			if (worker === null) {
				if (numOfActiveWorkers >= CONFIG.workersMaxNum) {
					return null;
				}

				worker = cluster.fork();
				worker.workFor = path;
				worker.idle = idleWorker;
			}

			worker.isIdle = false;

			return worker;
		},

		workerMessageReceptor = function (workerMes) {
			var res = this.res, worker = this.worker;

			if (workerMes.salt !== this.salt) {
				return;
			}

			switch (workerMes.type) {
				case "header":
					if (! isNaN(workerMes.payload.statusCode)) {
						res.setStatus(workerMes.payload.statusCode);
					}

					workerMes.payload.headers.forEach(function (header) {
						res.setHeader(header);
					});

					res.flushHeaders();

					break;

				case "body":
					res.write(new Buffer(workerMes.payload));
					break;

				case "end":
					res.end();
					worker.removeListener("message", this.workerMessageReceiver);
					worker.idle();
					break;

				default:
					break;
			}
		},

		onReqData = function (bChunk) {
			var messageContainer = new Messenger(this.salt, "body", null), p = 0;

			while (p < bChunk.length) {
				messageContainer.payload = bChunk.slice(
					p,
					p = p + CONFIG.messageCap < bChunk.length ? p + CONFIG.messageCap : bChunk.length
				);
				this.worker.send(messageContainer);
			}
		},

		onReqEnd = function () {
			this.worker.send(new Messenger(this.salt, "end"));
			this.worker.on("message", this.workerMessageReceiver);
		},

		onResClose = function () {
			this.worker.kill();
		},

		timeoutResponse = function () {
			this.res.setStatus(408);
			this.res.flushHeaders(true);
			this.res.end();
			this.worker.kill();
		},

		responder = function (req, res) {
			var salt = Math.random(),
			requested = url.parse(req.params.SCRIPT_FILENAME.replace(/^proxy:scgi:/, "scgi:")),
			invoking = url.parse(requested.pathname).pathname,

			worker = invokeWorker(invoking),

			resources = {
				salt : salt,
				res : res,
				worker : worker
			};

			if (worker === null) {
				res.setStatus(503);
				res.flushHeaders(true);
				res.end();
				return;
			}

			resources.workerMessageReceiver = workerMessageReceptor.bind(resources);

			worker.send(new RequestHeaderMessenger(salt, invoking, req));

			req.on("data", onReqData.bind(resources));
			req.on("end", onReqEnd.bind(resources));
			res.on("close", onResClose.bind(resources));

			req.setTimeout(CONFIG.workersTimeout * 1000, timeoutResponse.bind(resources));
		};

		CONFIG.listenIPv4 && server.listen(CONFIG.servicePort, "0.0.0.0");
		CONFIG.listenIPv6 && server.listen(CONFIG.servicePort, "::");

		server.on("request", responder);
	};

	NodePool.prototype.worker = function () {
		var built = null, request = null,

		fs = require("fs"),

		genInstanceInterface = function (request) {
			var ret = {},

			salt = request.salt,

			responseStatus = NaN,
			responseHeaders = [],
			isHeaderSent = false,

			bCache = {
				chunks : [],
				cachedLength : 0
			},

			flushHeaders = function () {
				var messageContainer = new ResponseHeaderMessenger(salt, responseHeaders);

				if(! isNaN(responseStatus)) {
					messageContainer.payload.statusCode = responseStatus;
				}

				process.send(messageContainer);
				isHeaderSent = true;
			};

			ret.request = {
				params : request.header.params,
				body : Buffer.concat(request.body.chunks, request.body.length)
			};

			ret.setStatus = function (sCode, reasonPhrase) {
				responseStatus = parseInt(sCode, 10);

				if (reasonPhrase !== undefined) {
					responseHeaders.push(["Status:", sCode.toString(), reasonPhrase].join(" "));
				}
			};

			ret.setHeader = function (expr) {
				responseHeaders.push(expr);
			};

			ret.flush = function () {
				var messageContainer = new Messenger(salt, "body", null),
				bChunk = typeof bCache.chunks[0] === "string" ? bCache.chunks.join("") : Buffer.concat(bCache.chunks, bCache.chachedLength);

				isHeaderSent === false && flushHeaders();

				for (let p = 0; p < bChunk.length;) {
					messageContainer.payload = bChunk.slice(
						p,
						p = p + CONFIG.messageCap < bChunk.length ? p + CONFIG.messageCap : bChunk.length
					);
					process.send(messageContainer);
				}

				bCache.chunks = [];
				bCache.cachedLength = 0;
			};

			ret.echo = function(data) {
				var toBeCached = null;

				if (data === undefined || data === null || data.length === 0) {
					return;
				}

				if (Buffer.isBuffer(data) === true) {
					if (bCache.length > 0 && Buffer.isBuffer(bCache.chunks[0]) !== true) {
						ret.flush();
					}

					toBeCached = data;
				} else {
					if (bCache.length > 0 && typeof bCache.chunks[0] !== typeof "") {
						ret.flush();
					}

					toBeCached = typeof data === typeof "" ? data : data.toString();
				}

				if (bCache.cachedLength + toBeCached.length > CONFIG.messageCap) {
					ret.flush();
				}

				bCache.chunks.push(toBeCached);
				bCache.cachedLength += toBeCached.length;

				if (toBeCached.length > CONFIG.messageCap) {
					ret.flush();
				}
			};

			ret.end = function () {
				isHeaderSent === false && flushHeaders();
				ret.flush();
				process.send(new Messenger(salt, "end"));
			};

			return ret;
		},

		respondBalancerRequest = function (request) {
			var instanceInterface = genInstanceInterface(request);

			try {
				process.chdir(require("path").dirname(fs.realpathSync(request.header.invoking)));

				if (built === null || fs.statSync(request.header.invoking).ctime.getTime() > built.builtAt.getTime()) {
					delete require.cache[fs.realpathSync(request.header.invoking)];
					built = require(request.header.invoking);
					built.builtAt = new Date();
				}

				instanceInterface.setHeader("Content-Type: text/html; charset=UTF-8");
				built.exec(instanceInterface);
			} catch (e) {
				instanceInterface.setStatus(500);
				instanceInterface.end();
				cluster.worker.kill();
			}
		},

		balancerMessageReceptor = function (messenger) {
			switch (messenger.type) {
				case "header":
					request = {
						salt : messenger.salt,
						header : messenger.payload,
						body : {
							length : 0,
							chunks : []
						}
					};
					break;

				case "body":
					if (messenger.salt === request.salt) {
						let newBodyChunk = new Buffer(messenger.payload);

						request.body.chunks.push(newBodyChunk);
						request.body.length += newBodyChunk.length;
					}
					break;

				case "end":
					respondBalancerRequest(request);
					break;
				default:
					break;
			}
		};

		process.on("message", balancerMessageReceptor);
	};

	process.setuid(CONFIG.serverUid) && process.setgid(CONFIG.serverGid);

	if (cluster.isMaster === true) {
		new NodePool().balancer();
	} else if (cluster.isWorker === true) {
		new NodePool().worker();
	}
})();
<|endoftext|>


<commit_before>module.exports = function(skill, info, bot, message, db) {
    var userData = message.text.match(/\<(.*?)\>/g);
    console.log('messaage text: ' + message.text);
    console.log('userdata' + userData);
  if (userData) {
    // if there is a user is mentioned initiate the challenge!
    //for (var i = 0, len = userData.length; i < len; i++) {
        //FU(userData[i].replace(/[^\w\s]/gi, ''));
        //console.log('userdata[i]' + userData[i]);
        //console.log('userdata[i]' + userData[i].replace(/[^\w\s]/gi, ''));
    //}
    console.log(userData[0].replace(/[^\w\s]/gi, ''));
    var challenger = getSlackName(message.user.replace(/[^\w\s]/gi, ''));
    var challenged = getSlackName(userData[0].replace(/[^\w\s]/gi, ''));
    bot.reply(message, challenger + ' has challenged ' + challenged);

    //bot.reply(message,'Let\'s rumble' + userData[0].replace(/[^\w\s]/gi, ''));
  } else {//if no user challenged
    bot.reply(message, 'You didn\'t challenge anyone you chicken shit! :chicken: :poop:');
  }

function getSlackName(userID) {
    var slackName;
    bot.api.users.info({user: userID}, (error, response) => {
    console.log(response.user.real_name);
    slackName = JSON.stringify(response.user.name);
    })
    console.log('slackname: ' + slackName)
    return slackName;
}

function FU(user) {
    //DM some shade!
    bot.api.im.open({ user: user }, function (err, response) {
      if (err) {
        return console.log(err)
      }
    var fuckArray = [
    'https://giphy.com/gifs/cheezburger-olympics-U7P2vnWfPkIQ8',
    'https://giphy.com/gifs/louis-ck-middle-finger-fuck-you-Qd71uU3LzyxXO'
    ];
    var randomFuck = Math.floor(Math.random()* fuckArray.length);

    var dmChannel = response.channel.id
    bot.say({channel: dmChannel, text: 'Someone is throwing shade your way... :middle_finger:'})
    bot.say({channel: dmChannel, text: fuckArray[randomFuck]})
    })

}

  var gameEngine = require('./Rock-Paper-Spock');

    //bot.api.users.info({user: message.user}, (error, response) => {
        //bot.reply(message, 'Rock Paper Scissors (lizard, spock, spiderman, batman, wizard, glock?)');
    //})

  var instance = new gameEngine(gameEngine.DefaultRules);
  instance.addPlayer({id: 1, sign: "spock"});
  instance.addPlayer({id: 2, sign: "rock"});
  instance.addPlayer({id: 3, sign: "spock"});
  instance.addPlayer(4, "rock").addPlayer(5, "paper");
  instance.play();
  console.log(instance.winner);
  //note players that won-lost, add support for W-L records
  //bot.reply(message, 'test successful. maybe code something more useful next time?');
};
<commit_msg>Update RockPaperScissors.js<commit_after>module.exports = function(skill, info, bot, message, db) {
    var userData = message.text.match(/\<(.*?)\>/g);
    console.log('messaage text: ' + message.text);
    console.log('userdata' + userData);
  if (userData) {
    // if there is a user is mentioned initiate the challenge!
    //for (var i = 0, len = userData.length; i < len; i++) {
        //FU(userData[i].replace(/[^\w\s]/gi, ''));
        //console.log('userdata[i]' + userData[i]);
        //console.log('userdata[i]' + userData[i].replace(/[^\w\s]/gi, ''));
    //}
    console.log(userData[0].replace(/[^\w\s]/gi, ''));
    var challenger = getSlackName(message.user.replace(/[^\w\s]/gi, ''));
    var challenged = getSlackName(userData[0].replace(/[^\w\s]/gi, ''));
    bot.reply(message, challenger + ' has challenged ' + challenged);

    //bot.reply(message,'Let\'s rumble' + userData[0].replace(/[^\w\s]/gi, ''));
  } else {//if no user challenged
    bot.reply(message, 'You didn\'t challenge anyone you chicken shit! :chicken: :poop:');
  }

function getSlackName(userID) {
    var slackResp;
    bot.api.users.info({user: userID}, (error, response) => {
    console.log(response.user.real_name);
    slackResp = JSON.parse(response);
    console.log('slackname: ' + slackResp.user.real_name);
    return slackResp.user.real_name;
    })

}

function FU(user) {
    //DM some shade!
    bot.api.im.open({ user: user }, function (err, response) {
      if (err) {
        return console.log(err)
      }
    var fuckArray = [
    'https://giphy.com/gifs/cheezburger-olympics-U7P2vnWfPkIQ8',
    'https://giphy.com/gifs/louis-ck-middle-finger-fuck-you-Qd71uU3LzyxXO'
    ];
    var randomFuck = Math.floor(Math.random()* fuckArray.length);

    var dmChannel = response.channel.id
    bot.say({channel: dmChannel, text: 'Someone is throwing shade your way... :middle_finger:'})
    bot.say({channel: dmChannel, text: fuckArray[randomFuck]})
    })

}

  var gameEngine = require('./Rock-Paper-Spock');

    //bot.api.users.info({user: message.user}, (error, response) => {
        //bot.reply(message, 'Rock Paper Scissors (lizard, spock, spiderman, batman, wizard, glock?)');
    //})

  var instance = new gameEngine(gameEngine.DefaultRules);
  instance.addPlayer({id: 1, sign: "spock"});
  instance.addPlayer({id: 2, sign: "rock"});
  instance.addPlayer({id: 3, sign: "spock"});
  instance.addPlayer(4, "rock").addPlayer(5, "paper");
  instance.play();
  console.log(instance.winner);
  //note players that won-lost, add support for W-L records
  //bot.reply(message, 'test successful. maybe code something more useful next time?');
};
<|endoftext|>


<commit_before>'use strict';

var startTime;
var lastMeasure;
var startMeasure = function(name) {
    startTime = performance.now();
    lastMeasure = name;
}
var stopMeasure = function() {
    var last = lastMeasure;
    if (lastMeasure) {
        window.setTimeout(function () {
            lastMeasure = null;
            var stop = performance.now();
            var duration = 0;
            console.log(last+" took "+(stop-startTime));
        }, 0);
    }
}

function _random(max) {
    return Math.round(Math.random()*1000)%max;
}

class Store {
    constructor() {
        this.data = [];
        this.backup = null;
        this.selected = null;
        this.id = 1;
    }
    buildData(count = 1000) {
        var adjectives = ["pretty", "large", "big", "small", "tall", "short", "long", "handsome", "plain", "quaint", "clean", "elegant", "easy", "angry", "crazy", "helpful", "mushy", "odd", "unsightly", "adorable", "important", "inexpensive", "cheap", "expensive", "fancy"];
        var colours = ["red", "yellow", "blue", "green", "pink", "brown", "purple", "brown", "white", "black", "orange"];
        var nouns = ["table", "chair", "house", "bbq", "desk", "car", "pony", "cookie", "sandwich", "burger", "pizza", "mouse", "keyboard"];
        var data = [];
        for (var i = 0; i < count; i++)
            data.push({id: this.id++, label: adjectives[_random(adjectives.length)] + " " + colours[_random(colours.length)] + " " + nouns[_random(nouns.length)] });
        return data;
    }
    updateData(mod = 10) {
        for (let i=0;i<this.data.length;i+=10) {
            this.data[i].label += ' !!!';
            // this.data[i] = Object.assign({}, this.data[i], {label: this.data[i].label +' !!!'});
        }
    }
    delete(id) {
        const idx = this.data.findIndex(d => d.id==id);
        this.data = this.data.filter((e,i) => i!=idx);
        return this;
    }
    run() {
        this.data = this.buildData();
        this.selected = null;
    }
    add() {
        this.data = this.data.concat(this.buildData(1000));
        this.selected = null;
    }
    update() {
        this.updateData();
        this.selected = null;
    }
    select(id) {
        this.selected = id;
    }
    hideAll() {
        this.backup = this.data;
        this.data = [];
        this.selected = null;
    }
    showAll() {
        this.data = this.backup;
        this.backup = null;
        this.selected = null;
    }
    runLots() {
        this.data = this.buildData(10000);
        this.selected = null;
    }
    clear() {
        this.data = [];
        this.selected = null;
    }
    swapRows() {
        if(this.data.length > 10) {
            var a = this.data[4];
            this.data[4] = this.data[9];
            this.data[9] = a;
        }
    }
}

Slim.tag('main-app',

`

Slim.js

                            <button click="create1k" type='button' class='btn btn-primary btn-block' id='run'>Create 1,000 rows</button>

                            <button click="create10k" type='button' class='btn btn-primary btn-block' id='runlots'>Create 10,000 rows</button>

                            <button click="append1k" type='button' class='btn btn-primary btn-block' id='add'>Append 1,000 rows</button>

                            <button click="update10" type='button' class='btn btn-primary btn-block' id='update'>Update every 10th row</button>

                            <button click="testClear" type='button' class='btn btn-primary btn-block' id='clear'>Clear</button>

                            <button click="swap" type='button' class='btn btn-primary btn-block' id='swaprows'>Swap Rows</button>

                    [[data.id]]

                        [[data.label]]

`,

class extends Slim {
    onBeforeCreated() {
        this.items = [];
        this.store = new Store();
    }

    deleteOne(e) {
        startMeasure('delete');
        this.store.delete(e.target.data.id);
        console.log(e.target.data);
        this.items = this.store.data;
        stopMeasure();
    }

    update10() {
        startMeasure('update');
        this.store.update();
        this.items = this.store.data;
        stopMeasure();
    }

    testClear() {
        startMeasure('clear');
        this.store.clear();
        this.items = this.store.data;
        stopMeasure();
    }

    append1k() {
        startMeasure('add');
        this.store.add();
        this.items = this.store.data;
        stopMeasure();
    }

    swap() {
        startMeasure('swap');
        this.store.swapRows();
        this.items = this.store.data;
        stopMeasure();
    }

    create10k() {
        this.store.clear();
        this.store.runLots();
        startMeasure('runLots');
        this.items = this.store.data;
        stopMeasure();
    }

    create1k() {
        this.store.clear();
        this.store.run();
        startMeasure('run');
        this.items = this.store.data;
        stopMeasure();
    }
});<commit_msg>removing unwanted log<commit_after>'use strict';

var startTime;
var lastMeasure;
var startMeasure = function(name) {
    startTime = performance.now();
    lastMeasure = name;
}
var stopMeasure = function() {
    var last = lastMeasure;
    if (lastMeasure) {
        window.setTimeout(function () {
            lastMeasure = null;
            var stop = performance.now();
            var duration = 0;
            console.log(last+" took "+(stop-startTime));
        }, 0);
    }
}

function _random(max) {
    return Math.round(Math.random()*1000)%max;
}

class Store {
    constructor() {
        this.data = [];
        this.backup = null;
        this.selected = null;
        this.id = 1;
    }
    buildData(count = 1000) {
        var adjectives = ["pretty", "large", "big", "small", "tall", "short", "long", "handsome", "plain", "quaint", "clean", "elegant", "easy", "angry", "crazy", "helpful", "mushy", "odd", "unsightly", "adorable", "important", "inexpensive", "cheap", "expensive", "fancy"];
        var colours = ["red", "yellow", "blue", "green", "pink", "brown", "purple", "brown", "white", "black", "orange"];
        var nouns = ["table", "chair", "house", "bbq", "desk", "car", "pony", "cookie", "sandwich", "burger", "pizza", "mouse", "keyboard"];
        var data = [];
        for (var i = 0; i < count; i++)
            data.push({id: this.id++, label: adjectives[_random(adjectives.length)] + " " + colours[_random(colours.length)] + " " + nouns[_random(nouns.length)] });
        return data;
    }
    updateData(mod = 10) {
        for (let i=0;i<this.data.length;i+=10) {
            this.data[i].label += ' !!!';
            // this.data[i] = Object.assign({}, this.data[i], {label: this.data[i].label +' !!!'});
        }
    }
    delete(id) {
        const idx = this.data.findIndex(d => d.id==id);
        this.data = this.data.filter((e,i) => i!=idx);
        return this;
    }
    run() {
        this.data = this.buildData();
        this.selected = null;
    }
    add() {
        this.data = this.data.concat(this.buildData(1000));
        this.selected = null;
    }
    update() {
        this.updateData();
        this.selected = null;
    }
    select(id) {
        this.selected = id;
    }
    hideAll() {
        this.backup = this.data;
        this.data = [];
        this.selected = null;
    }
    showAll() {
        this.data = this.backup;
        this.backup = null;
        this.selected = null;
    }
    runLots() {
        this.data = this.buildData(10000);
        this.selected = null;
    }
    clear() {
        this.data = [];
        this.selected = null;
    }
    swapRows() {
        if(this.data.length > 10) {
            var a = this.data[4];
            this.data[4] = this.data[9];
            this.data[9] = a;
        }
    }
}

Slim.tag('main-app',

`

Slim.js

                            <button click="create1k" type='button' class='btn btn-primary btn-block' id='run'>Create 1,000 rows</button>

                            <button click="create10k" type='button' class='btn btn-primary btn-block' id='runlots'>Create 10,000 rows</button>

                            <button click="append1k" type='button' class='btn btn-primary btn-block' id='add'>Append 1,000 rows</button>

                            <button click="update10" type='button' class='btn btn-primary btn-block' id='update'>Update every 10th row</button>

                            <button click="testClear" type='button' class='btn btn-primary btn-block' id='clear'>Clear</button>

                            <button click="swap" type='button' class='btn btn-primary btn-block' id='swaprows'>Swap Rows</button>

                    [[data.id]]

                        [[data.label]]

`,

class extends Slim {
    onBeforeCreated() {
        this.items = [];
        this.store = new Store();
    }

    deleteOne(e) {
        startMeasure('delete');
        this.store.delete(e.target.data.id);
        this.items = this.store.data;
        stopMeasure();
    }

    update10() {
        startMeasure('update');
        this.store.update();
        this.items = this.store.data;
        stopMeasure();
    }

    testClear() {
        startMeasure('clear');
        this.store.clear();
        this.items = this.store.data;
        stopMeasure();
    }

    append1k() {
        startMeasure('add');
        this.store.add();
        this.items = this.store.data;
        stopMeasure();
    }

    swap() {
        startMeasure('swap');
        this.store.swapRows();
        this.items = this.store.data;
        stopMeasure();
    }

    create10k() {
        this.store.clear();
        this.store.runLots();
        startMeasure('runLots');
        this.items = this.store.data;
        stopMeasure();
    }

    create1k() {
        this.store.clear();
        this.store.run();
        startMeasure('run');
        this.items = this.store.data;
        stopMeasure();
    }
});<|endoftext|>


<commit_before>const pkg = require('../package.json')
const Licenses = require('./Licenses')
const JSBuilder = require('./JSBuilder')
const ElectronBuilder = require('./ElectronBuilder')
const ReleaseAssets = require('./ReleaseAssets')
const Distribution = require('./Distribution')

const argv = require('yargs').argv

const argvPlatform = (Array.isArray(argv.platform) ? new Set(argv.platform) : new Set([argv.platform || 'all']))
const platforms = argvPlatform.has('all') ? ['darwin', 'linux', 'win32'] : Array.from(argvPlatform)
const dist = argv.distribution

//Distribution.distribute(['win32'], pkg).then(() => console.log('ok'), (e) => console.log(e))
Promise.resolve()
  .then(() => dist ? JSBuilder.pruneNPM() : Promise.resolve())
  .then(JSBuilder.runWebpack)
  .then(() => ElectronBuilder.packageApp(platforms, pkg))
  .then(() => dist ? Licenses.buildLicensesIntoReleases(platforms) : Promise.resolve())
  .then(() => dist ? ReleaseAssets.copyAssetsIntoReleases(platforms) : Promise.resolve())
  .then(() => dist ? Distribution.distribute(platforms, pkg) : Promise.resolve())
  .then(
    () => { },
    (err) => {
      console.log(err)
      console.log(err.stack)
    }
  )
<commit_msg>Fixed standard<commit_after>const pkg = require('../package.json')
const Licenses = require('./Licenses')
const JSBuilder = require('./JSBuilder')
const ElectronBuilder = require('./ElectronBuilder')
const ReleaseAssets = require('./ReleaseAssets')
const Distribution = require('./Distribution')

const argv = require('yargs').argv

const argvPlatform = (Array.isArray(argv.platform) ? new Set(argv.platform) : new Set([argv.platform || 'all']))
const platforms = argvPlatform.has('all') ? ['darwin', 'linux', 'win32'] : Array.from(argvPlatform)
const dist = argv.distribution

Promise.resolve()
  .then(() => dist ? JSBuilder.pruneNPM() : Promise.resolve())
  .then(JSBuilder.runWebpack)
  .then(() => ElectronBuilder.packageApp(platforms, pkg))
  .then(() => dist ? Licenses.buildLicensesIntoReleases(platforms) : Promise.resolve())
  .then(() => dist ? ReleaseAssets.copyAssetsIntoReleases(platforms) : Promise.resolve())
  .then(() => dist ? Distribution.distribute(platforms, pkg) : Promise.resolve())
  .then(
    () => { },
    (err) => {
      console.log(err)
      console.log(err.stack)
    }
  )
<|endoftext|>


<commit_before>/*!
 * @license ipc-promise Copyright(c) 2015 sasa+1
 * https://github.com/sasaplus1/ipc-promise
 * Released under the MIT license.
 */

/**
 * export to AMD/CommonJS/global.
 *
 * @param {Object} root root object.
 * @param {Function} factory factory method.
 */
(function(root, factory){
  'use strict';

  if (typeof define === 'function' && define.amd) {
    define(['ipc', 'events'], factory);
  } else if (typeof exports === 'object') {
    module.exports = factory(require('ipc'), require('events'));
  } else {
    root.ipcPromise = factory(global.require('ipc'), global.require('events'));
  }
}((this || 0).self || global, function(ipc, events){
  'use strict';

  // constants
  var COMMON_EVENT_NAME = 'ipc-promise-common-event',
      SUCCESS_EVENT_SUFFIX = '-success',
      FAILURE_EVENT_SUFFIX = '-failure',
      COMMON_SUCCESS_EVENT_NAME = COMMON_EVENT_NAME + SUCCESS_EVENT_SUFFIX,
      COMMON_FAILURE_EVENT_NAME = COMMON_EVENT_NAME + FAILURE_EVENT_SUFFIX;

  // common event emitter
  var cee = new events.EventEmitter();

  /**
   * common event handler for ipc.
   *
   * @private
   * @param {Event} event event object.
   * @param {Object} arg argument object.
   */
  function commonEventHandler(event, arg) {
    // send from renderer process always.

    // add listener to common event emitter for main process.
    cee.on(arg.event + SUCCESS_EVENT_SUFFIX, function(result) {
      // send success to ipc for renderer process.
      event.sender.send(COMMON_SUCCESS_EVENT_NAME, {
        data: result,
        event: arg.event,
        id: arg.id
      });
    });
    cee.on(arg.event + FAILURE_EVENT_SUFFIX, function(result) {
      // send failure to ipc for renderer process.
      event.sender.send(COMMON_FAILURE_EVENT_NAME, {
        data: result,
        event: arg.event,
        id: arg.id
      });
    });

    // emit to common event emitter for main process.
    cee.emit(arg.event, arg.data);
  }

  /**
   * trigger event.
   *
   * @param {String} event event name of common event emitter on main process.
   * @param {*} data data for send.
   * @return {Promise} promise.
   */
  function send(event, data) {
    // call from renderer process always.

    return new Promise(function(resolve, reject) {
      var id = Math.floor(Math.random() * Number.MAX_SAFE_INTEGER),
          onSuccess, onFailure;

      // add listener to ipc for renderer process.
      ipc.on(COMMON_SUCCESS_EVENT_NAME, onSuccess = function(params) {
        if (params.id !== id || params.event !== event) {
          return;
        }

        // remove this listener.
        ipc.removeListener(COMMON_SUCCESS_EVENT_NAME, onSuccess);
        ipc.removeListener(COMMON_FAILURE_EVENT_NAME, onFailure);

        resolve(params.data);
      });
      ipc.on(COMMON_FAILURE_EVENT_NAME, onFailure = function(params) {
        if (params.id !== id || params.event !== event) {
          return;
        }

        // remove this listener.
        ipc.removeListener(COMMON_SUCCESS_EVENT_NAME, onSuccess);
        ipc.removeListener(COMMON_FAILURE_EVENT_NAME, onFailure);

        reject(params.data);
      });

      // send to ipc for main process.
      ipc.send(COMMON_EVENT_NAME, {
        data: data,
        event: event,
        id: id
      });
    });
  }

  /**
   * listen event.
   *
   * @param {String} event event name.
   * @param {Function} listener listener function.
   */
  function on(event, listener) {
    // call from main process always.

    // add listener to common event emitter for main process.
    cee.on(event, function(data) {
      listener(data)
        .then(function(result) {
          cee.emit(event + SUCCESS_EVENT_SUFFIX, result);
        })
        .catch(function(result) {
          cee.emit(event + FAILURE_EVENT_SUFFIX, result);
        });
    });
  }

  // main process
  if (typeof window === 'undefined') {
    // add common event handler for ipc of main process.
    ipc.on(COMMON_EVENT_NAME, commonEventHandler);
  }

  return {
    on: on,
    send: send
  };
}));
<commit_msg>pass to event<commit_after>/*!
 * @license ipc-promise Copyright(c) 2015 sasa+1
 * https://github.com/sasaplus1/ipc-promise
 * Released under the MIT license.
 */

/**
 * export to AMD/CommonJS/global.
 *
 * @param {Object} root root object.
 * @param {Function} factory factory method.
 */
(function(root, factory){
  'use strict';

  if (typeof define === 'function' && define.amd) {
    define(['ipc', 'events'], factory);
  } else if (typeof exports === 'object') {
    module.exports = factory(require('ipc'), require('events'));
  } else {
    root.ipcPromise = factory(global.require('ipc'), global.require('events'));
  }
}((this || 0).self || global, function(ipc, events){
  'use strict';

  // constants
  var COMMON_EVENT_NAME = 'ipc-promise-common-event',
      SUCCESS_EVENT_SUFFIX = '-success',
      FAILURE_EVENT_SUFFIX = '-failure',
      COMMON_SUCCESS_EVENT_NAME = COMMON_EVENT_NAME + SUCCESS_EVENT_SUFFIX,
      COMMON_FAILURE_EVENT_NAME = COMMON_EVENT_NAME + FAILURE_EVENT_SUFFIX;

  // common event emitter
  var cee = new events.EventEmitter();

  /**
   * common event handler for ipc.
   *
   * @private
   * @param {Event} event event object.
   * @param {Object} arg argument object.
   */
  function commonEventHandler(event, arg) {
    // send from renderer process always.

    // add listener to common event emitter for main process.
    cee.on(arg.event + SUCCESS_EVENT_SUFFIX, function(result) {
      // send success to ipc for renderer process.
      event.sender.send(COMMON_SUCCESS_EVENT_NAME, {
        data: result,
        event: arg.event,
        id: arg.id
      });
    });
    cee.on(arg.event + FAILURE_EVENT_SUFFIX, function(result) {
      // send failure to ipc for renderer process.
      event.sender.send(COMMON_FAILURE_EVENT_NAME, {
        data: result,
        event: arg.event,
        id: arg.id
      });
    });

    // emit to common event emitter for main process.
    cee.emit(arg.event, arg.data, event);
  }

  /**
   * trigger event.
   *
   * @param {String} event event name of common event emitter on main process.
   * @param {*} data data for send.
   * @return {Promise} promise.
   */
  function send(event, data) {
    // call from renderer process always.

    return new Promise(function(resolve, reject) {
      var id = Math.floor(Math.random() * Number.MAX_SAFE_INTEGER),
          onSuccess, onFailure;

      // add listener to ipc for renderer process.
      ipc.on(COMMON_SUCCESS_EVENT_NAME, onSuccess = function(params) {
        if (params.id !== id || params.event !== event) {
          return;
        }

        // remove this listener.
        ipc.removeListener(COMMON_SUCCESS_EVENT_NAME, onSuccess);
        ipc.removeListener(COMMON_FAILURE_EVENT_NAME, onFailure);

        resolve(params.data);
      });
      ipc.on(COMMON_FAILURE_EVENT_NAME, onFailure = function(params) {
        if (params.id !== id || params.event !== event) {
          return;
        }

        // remove this listener.
        ipc.removeListener(COMMON_SUCCESS_EVENT_NAME, onSuccess);
        ipc.removeListener(COMMON_FAILURE_EVENT_NAME, onFailure);

        reject(params.data);
      });

      // send to ipc for main process.
      ipc.send(COMMON_EVENT_NAME, {
        data: data,
        event: event,
        id: id
      });
    });
  }

  /**
   * listen event.
   *
   * @param {String} event event name.
   * @param {Function} listener listener function.
   */
  function on(event, listener) {
    // call from main process always.

    // add listener to common event emitter for main process.
    cee.on(event, function(data, ipcEvent) {
      listener(data, ipcEvent)
        .then(function(result) {
          cee.emit(event + SUCCESS_EVENT_SUFFIX, result);
        })
        .catch(function(result) {
          cee.emit(event + FAILURE_EVENT_SUFFIX, result);
        });
    });
  }

  // main process
  if (typeof window === 'undefined') {
    // add common event handler for ipc of main process.
    ipc.on(COMMON_EVENT_NAME, commonEventHandler);
  }

  return {
    on: on,
    send: send
  };
}));
<|endoftext|>


<commit_before>var schedule = [
{
  date: "12/1",
  author: "ymyzk",
  author_url: "http://www.ymyzk.com",
  entry_title: "CAMPHOR- アドベントカレンダー 2014 を始めます!",
  entry_url: "http://blog.camph.net/news/advent-calendar-2014/"
},
{
  date: "12/2",
  author: "ohmuraken",
  author_url: "https://github.com/ohmuraken",
  entry_title: "彼女のつくりかた (京大11月祭にて)",
  entry_url: "http://blog.camph.net/news/howtomakemygirlfriend2/"
},
{
  date: "12/3",
  author: "morishin",
  author_url: "https://twitter.com/morishin127",
  entry_title: "CAMPHOR-のYo活用",
  entry_url: "http://blog.camph.net/news/useful-yo/"
},
{
  date: "12/4",
  author: "kohey18",
  author_url: "https://github.com/kohey18",
  entry_title: "「hubot start tv」で家のテレビの電源を付ける。",
  entry_url: "http://tech.camph.net/hubot_start_tv/"
},
{
  date: "12/5",
  author: "Shtr28",
  author_url: "https://twitter.com/Shtr28",
  entry_title: "Python 3でお手軽並列計算 ~concurrent.futures を使った ngram 抽出~",
  entry_url: "http://tech.camph.net/python3-concurrent-futures/"
},
{
  date: "12/6",
  author: "yaitaimo",
  author_url: "https://github.com/yaitaimo",
  entry_title: "CAMPHOR-HOUSEの庭を美白した話",
  entry_url: "http://blog.camph.net/event/camphor-house-garden/"
},
{
  date: "12/7",
  author: "tomonkey1",
  author_url: "https://github.com/tomonkey1",
  entry_title: "宅建挑戦記",
  entry_url: "http://blog.camph.net/event/takken/"
},
{
  date: "12/8",
  author: "asadaman",
  author_url: "https://github.com/asadaman",
  entry_title: "ロボットに負けたくない",
  entry_url: "http://blog.camph.net/news/robo/"
},
{
  date: "12/9",
  author: "akaaariiiiin",
  author_url: "https://github.com/akaaariiiiin",
  entry_title: "Java の MigLayout",
  entry_url: "http://tech.camph.net/java-miglayout/"
},
{
  date: "12/10",
  author: "To-Mikasa",
  author_url: "https://github.com/To-Mikasa",
  entry_title: "ノンデザイナーがそれっぽいWebデザインを作る話",
  entry_url: "http://blog.camph.net/news/non-designer/"
},
{
  date: "12/11",
  author: "ryota-ka",
  author_url: "http://ryota-ka.me/",
  entry_title: "iOS 初心者が Swift を使って3日でゲームを作った話",
  entry_url: "http://tech.camph.net/an-ios-beginner-made-a-game-app-with-swift-in-3-days/"
},
{
  date: "12/12",
  author: "siriusjack",
  author_url: "https://github.com/siriusjack",
  entry_title: "食べられるドングリの見分け方(ドイツ編)",
  entry_url: "http://blog.camph.net/news/nuts_eating_in_germany/"
},
{
  date: "12/13",
  author: "ivstivs",
  author_url: "https://github.com/ivstivs",
  entry_title: "ProjectileとHelm",
  entry_url: "http://tech.camph.net/projectile-and-helm/"
},
{
  date: "12/14",
  author: "kakenn",
  author_url: "http://shuto.info",
  entry_title: "格安3Dプリンター「daVinci 2.0」を買ってみた。",
  entry_url: "http://blog.camph.net/news/buy-davinci-2-0/"
},
{
  date: "12/15",
  author: "ymyzk",
  author_url: "http://www.ymyzk.com",
  entry_title: "sphinxcontrib.httpdomain で RESTful API のドキュメントを作る",
  entry_url: "https://blog.ymyzk.com/2014/12/restful-api-docs-with-sphinxcontrib-httpdomain/"
},
{
  date: "12/16",
  author: "cotton_ori",
  author_url: "https://twitter.com/cotton_ori",
  entry_title: "知らない人たちとハッカソンに参加した話",
  entry_url: "http://wataori.hatenadiary.jp/entry/2014/12/16/003000"
},
{
  date: "12/17",
  author: "pepoipod",
  author_url: "https://github.com/pepoipod",
  entry_title: "UnityFree + LeapでUnityちゃんを投げを作る",
  entry_url: "http://tech.camph.net/unityfree-leap/"
},
{
  date: "12/18",
  author: "ohmuraken",
  author_url: "https://github.com/ohmuraken",
  entry_title: "CAMPHOR- HOUSEについて",
  entry_url: "http://blog.camph.net/news/about-house/"
},
{
  date: "12/19",
  author: "kohey18",
  author_url: "https://github.com/kohey18",
  entry_title: "Gyazoの使い方を熱く語るぞ!",
  entry_url: "http://blog.camph.net/tool/useful_gyazo/"
},
{
  date: "12/20",
  author: "murata_atsumi",
  author_url: "https://twitter.com/murata_atsumi",
  entry_title: "ノンデザイナーでもできる！写真を使ったイケてるメイン画像の作り方",
  entry_url: "http://tech.camph.net/mainimage-designing/"
},
{
  date: "12/21",
  author: "morishin",
  author_url: "https://twitter.com/morishin127",
  entry_title: "Pythonでローディングのぐるぐるを表示する",
  entry_url: "http://tech.camph.net/python-guruguru/"
}
,
{
  date: "12/22",
  author: "yaitaimo",
  author_url: "https://github.com/yaitaimo",
  entry_title: "Alfred Workflowsの作り方 — Python Ver. –",
  entry_url: "http://tech.camph.net/alfred-workflows-python/"
}
,
{
  date: "12/23",
  author: "ryota-ka",
  author_url: "http://ryota-ka.me/",
  entry_title: "準備中",
  entry_url: "#"
}
,
{
  date: "12/24",
  author: "ohmuraken",
  author_url: "https://github.com/ohmuraken",
  entry_title: "サイボウズさんとSelenium勉強会を開催しました",
  entry_url: "#"
}
,
{
  date: "12/25",
  author: "準備中",
  author_url: "#",
  entry_title: "準備中",
  entry_url: "#"
}
];
<commit_msg>Update data.js<commit_after>var schedule = [
{
  date: "12/1",
  author: "ymyzk",
  author_url: "http://www.ymyzk.com",
  entry_title: "CAMPHOR- アドベントカレンダー 2014 を始めます!",
  entry_url: "http://blog.camph.net/news/advent-calendar-2014/"
},
{
  date: "12/2",
  author: "ohmuraken",
  author_url: "https://github.com/ohmuraken",
  entry_title: "彼女のつくりかた (京大11月祭にて)",
  entry_url: "http://blog.camph.net/news/howtomakemygirlfriend2/"
},
{
  date: "12/3",
  author: "morishin",
  author_url: "https://twitter.com/morishin127",
  entry_title: "CAMPHOR-のYo活用",
  entry_url: "http://blog.camph.net/news/useful-yo/"
},
{
  date: "12/4",
  author: "kohey18",
  author_url: "https://github.com/kohey18",
  entry_title: "「hubot start tv」で家のテレビの電源を付ける。",
  entry_url: "http://tech.camph.net/hubot_start_tv/"
},
{
  date: "12/5",
  author: "Shtr28",
  author_url: "https://twitter.com/Shtr28",
  entry_title: "Python 3でお手軽並列計算 ~concurrent.futures を使った ngram 抽出~",
  entry_url: "http://tech.camph.net/python3-concurrent-futures/"
},
{
  date: "12/6",
  author: "yaitaimo",
  author_url: "https://github.com/yaitaimo",
  entry_title: "CAMPHOR-HOUSEの庭を美白した話",
  entry_url: "http://blog.camph.net/event/camphor-house-garden/"
},
{
  date: "12/7",
  author: "tomonkey1",
  author_url: "https://github.com/tomonkey1",
  entry_title: "宅建挑戦記",
  entry_url: "http://blog.camph.net/event/takken/"
},
{
  date: "12/8",
  author: "asadaman",
  author_url: "https://github.com/asadaman",
  entry_title: "ロボットに負けたくない",
  entry_url: "http://blog.camph.net/news/robo/"
},
{
  date: "12/9",
  author: "akaaariiiiin",
  author_url: "https://github.com/akaaariiiiin",
  entry_title: "Java の MigLayout",
  entry_url: "http://tech.camph.net/java-miglayout/"
},
{
  date: "12/10",
  author: "To-Mikasa",
  author_url: "https://github.com/To-Mikasa",
  entry_title: "ノンデザイナーがそれっぽいWebデザインを作る話",
  entry_url: "http://blog.camph.net/news/non-designer/"
},
{
  date: "12/11",
  author: "ryota-ka",
  author_url: "http://ryota-ka.me/",
  entry_title: "iOS 初心者が Swift を使って3日でゲームを作った話",
  entry_url: "http://tech.camph.net/an-ios-beginner-made-a-game-app-with-swift-in-3-days/"
},
{
  date: "12/12",
  author: "siriusjack",
  author_url: "https://github.com/siriusjack",
  entry_title: "食べられるドングリの見分け方(ドイツ編)",
  entry_url: "http://blog.camph.net/news/nuts_eating_in_germany/"
},
{
  date: "12/13",
  author: "ivstivs",
  author_url: "https://github.com/ivstivs",
  entry_title: "ProjectileとHelm",
  entry_url: "http://tech.camph.net/projectile-and-helm/"
},
{
  date: "12/14",
  author: "kakenn",
  author_url: "http://shuto.info",
  entry_title: "格安3Dプリンター「daVinci 2.0」を買ってみた。",
  entry_url: "http://blog.camph.net/news/buy-davinci-2-0/"
},
{
  date: "12/15",
  author: "ymyzk",
  author_url: "http://www.ymyzk.com",
  entry_title: "sphinxcontrib.httpdomain で RESTful API のドキュメントを作る",
  entry_url: "https://blog.ymyzk.com/2014/12/restful-api-docs-with-sphinxcontrib-httpdomain/"
},
{
  date: "12/16",
  author: "cotton_ori",
  author_url: "https://twitter.com/cotton_ori",
  entry_title: "知らない人たちとハッカソンに参加した話",
  entry_url: "http://wataori.hatenadiary.jp/entry/2014/12/16/003000"
},
{
  date: "12/17",
  author: "pepoipod",
  author_url: "https://github.com/pepoipod",
  entry_title: "UnityFree + LeapでUnityちゃんを投げを作る",
  entry_url: "http://tech.camph.net/unityfree-leap/"
},
{
  date: "12/18",
  author: "ohmuraken",
  author_url: "https://github.com/ohmuraken",
  entry_title: "CAMPHOR- HOUSEについて",
  entry_url: "http://blog.camph.net/news/about-house/"
},
{
  date: "12/19",
  author: "kohey18",
  author_url: "https://github.com/kohey18",
  entry_title: "Gyazoの使い方を熱く語るぞ!",
  entry_url: "http://blog.camph.net/tool/useful_gyazo/"
},
{
  date: "12/20",
  author: "murata_atsumi",
  author_url: "https://twitter.com/murata_atsumi",
  entry_title: "ノンデザイナーでもできる！写真を使ったイケてるメイン画像の作り方",
  entry_url: "http://tech.camph.net/mainimage-designing/"
},
{
  date: "12/21",
  author: "morishin",
  author_url: "https://twitter.com/morishin127",
  entry_title: "Pythonでローディングのぐるぐるを表示する",
  entry_url: "http://tech.camph.net/python-guruguru/"
}
,
{
  date: "12/22",
  author: "yaitaimo",
  author_url: "https://github.com/yaitaimo",
  entry_title: "Alfred Workflowsの作り方 — Python Ver. –",
  entry_url: "http://tech.camph.net/alfred-workflows-python/"
}
,
{
  date: "12/23",
  author: "ryota-ka",
  author_url: "http://ryota-ka.me/",
  entry_title: "初心者でもできる！関数型プログラミング入門",
  entry_url: "http://tech.camph.net/functional-php/"
}
,
{
  date: "12/24",
  author: "ohmuraken",
  author_url: "https://github.com/ohmuraken",
  entry_title: "サイボウズさんとSelenium勉強会を開催しました",
  entry_url: "#"
}
,
{
  date: "12/25",
  author: "準備中",
  author_url: "#",
  entry_title: "準備中",
  entry_url: "#"
}
];
<|endoftext|>


<commit_before>'use strict';

const {Molecule} = require('openchemlib-extended-minimal');

const defaultOptions = {
    atomLabel: 'H',
    ignoreLabile: true,
    use: 'median'
};

module.exports = function options(molecule, options) {
    if (typeof molecule === 'string') {
        molecule = Molecule.fromMolfile(molecule);
    } else if (!(molecule instanceof Molecule)) {
        throw new Error('molecule must be a molfile string or Molecule instance');
    }
    options = Object.assign({}, defaultOptions, options);
    if(options.atomLabel === 'H'){
        molecule.addImplicitHydrogens();
    }
    //@TODO Should be removed
    if(options.atomLabel === 'C'){
        molecule.removeExplicitHydrogens();
    }

    return [molecule, options];
};
<commit_msg>change addImplicitHydrogens for protons and carbons<commit_after>'use strict';

const {Molecule} = require('openchemlib-extended-minimal');

const defaultOptions = {
    atomLabel: 'H',
    ignoreLabile: true,
    use: 'median'
};

module.exports = function options(molecule, options) {
    if (typeof molecule === 'string') {
        molecule = Molecule.fromMolfile(molecule);
    } else if (!(molecule instanceof Molecule)) {
        throw new Error('molecule must be a molfile string or Molecule instance');
    }
    options = Object.assign({}, defaultOptions, options);
    //if(options.atomLabel === 'H'){
    molecule.addImplicitHydrogens();
    //}
    //@TODO Should be removed
    //if(options.atomLabel === 'C'){
    //    molecule.removeExplicitHydrogens();
    //}

    return [molecule, options];
};
<|endoftext|>


<commit_before>var Maybe = require('data.maybe');

var Types = require('./nsnjson.types');

function Encoding() {}

Encoding.isNull = function(data) {
  return (data == null);
}

Encoding.isBoolean = function(data) {
  return (typeof(data) == 'boolean') || (data instanceof Boolean);
}

Encoding.isNumber = function(data) {
  return (typeof(data) == 'number') || (data instanceof Number);
}

Encoding.isString = function(data) {
  return (typeof(data) == 'string') || (data instanceof String);
}

Encoding.isArray = function(data) {
  return (data instanceof Array);
}

Encoding.isObject = function(data) {
  return (data instanceof Object);
}

Encoding.customize = function(EncodingClass, customEncoders) {
  var jsonTypes = [Types.NULL, Types.NUMBER, Types.STRING, Types.BOOLEAN, Types.ARRAY, Types.OBJECT];

  if (customEncoders && (customEncoders instanceof Object)) {
    for (var i = 0, jsonTypesCount = jsonTypes.length; i < jsonTypesCount; i++) {
      var jsonType = jsonTypes[i];

      if (customEncoders.hasOwnProperty(jsonType)) {
        var customEncoder = customEncoders[jsonType];

        if (customEncoder instanceof Function) {
          switch (jsonType) {
            case Types.NULL:    EncodingClass.prototype.encodeNull    = customEncoder; break;
            case Types.NUMBER:  EncodingClass.prototype.encodeNumber  = customEncoder; break;
            case Types.STRING:  EncodingClass.prototype.encodeString  = customEncoder; break;
            case Types.BOOLEAN: EncodingClass.prototype.encodeBoolean = customEncoder; break;
            case Types.ARRAY:   EncodingClass.prototype.encodeArray   = customEncoder; break;
            case Types.OBJECT:  EncodingClass.prototype.encodeObject  = customEncoder; break;
          }
        }
      }
    }
  }

  return new EncodingClass();
}

Encoding.prototype.encodeNull = function() {
  throw new Error('Method { Encoding @ encodeNull } is not implemented!');
}

Encoding.prototype.encodeNumber = function(value) {
  throw new Error('Method { Encoding @ encodeNumber } is not implemented!');
}

Encoding.prototype.encodeString = function(value) {
  throw new Error('Method { Encoding @ encodeString } is not implemented!');
}

Encoding.prototype.encodeBoolean = function(value) {
  throw new Error('Method { Encoding @ encodeBoolean } is not implemented!');
}

Encoding.prototype.encodeArray = function(array) {
  throw new Error('Method { Encoding @ encodeArray } is not implemented!');
}

Encoding.prototype.encodeObject = function(object) {
  throw new Error('Method { Encoding @ encodeObject } is not implemented!');
}

Encoding.prototype.encode = function(data) {
  if (Encoding.isNull(data)) {
    return this.encodeNull();
  }

  if (Encoding.isNumber(data)) {
    return this.encodeNumber(data);
  }

  if (Encoding.isString(data)) {
    return this.encodeString(data);
  }

  if (Encoding.isBoolean(data)) {
    return this.encodeBoolean(data);
  }

  if (Encoding.isArray(data)) {
    return this.encodeArray(data);
  }

  if (Encoding.isObject(data)) {
    return this.encodeObject(data);
  }

  return Maybe.Nothing();
}

module.exports = Encoding;<commit_msg>Refactor method { Encoding @ customize }<commit_after>var Maybe = require('data.maybe');

var Types = require('./nsnjson.types');

function Encoding() {}

Encoding.isNull = function(data) {
  return (data == null);
}

Encoding.isBoolean = function(data) {
  return (typeof(data) == 'boolean') || (data instanceof Boolean);
}

Encoding.isNumber = function(data) {
  return (typeof(data) == 'number') || (data instanceof Number);
}

Encoding.isString = function(data) {
  return (typeof(data) == 'string') || (data instanceof String);
}

Encoding.isArray = function(data) {
  return (data instanceof Array);
}

Encoding.isObject = function(data) {
  return (data instanceof Object);
}

Encoding.customize = function(EncodingClass, customEncoders) {
  if (customEncoders && (customEncoders instanceof Object)) {
    for (var i = 0; i < Types.count; i++) {
      var type = Types.list[i];

      if (customEncoders.hasOwnProperty(type)) {
        var customEncoder = customEncoders[type];

        if (customEncoder instanceof Function) {
          switch (jsonType) {
            case Types.NULL:    EncodingClass.prototype.encodeNull    = customEncoder; break;
            case Types.NUMBER:  EncodingClass.prototype.encodeNumber  = customEncoder; break;
            case Types.STRING:  EncodingClass.prototype.encodeString  = customEncoder; break;
            case Types.BOOLEAN: EncodingClass.prototype.encodeBoolean = customEncoder; break;
            case Types.ARRAY:   EncodingClass.prototype.encodeArray   = customEncoder; break;
            case Types.OBJECT:  EncodingClass.prototype.encodeObject  = customEncoder; break;
          }
        }
      }
    }
  }

  return new EncodingClass();
}

Encoding.prototype.encodeNull = function() {
  throw new Error('Method { Encoding @ encodeNull } is not implemented!');
}

Encoding.prototype.encodeNumber = function(value) {
  throw new Error('Method { Encoding @ encodeNumber } is not implemented!');
}

Encoding.prototype.encodeString = function(value) {
  throw new Error('Method { Encoding @ encodeString } is not implemented!');
}

Encoding.prototype.encodeBoolean = function(value) {
  throw new Error('Method { Encoding @ encodeBoolean } is not implemented!');
}

Encoding.prototype.encodeArray = function(array) {
  throw new Error('Method { Encoding @ encodeArray } is not implemented!');
}

Encoding.prototype.encodeObject = function(object) {
  throw new Error('Method { Encoding @ encodeObject } is not implemented!');
}

Encoding.prototype.encode = function(data) {
  if (Encoding.isNull(data)) {
    return this.encodeNull();
  }

  if (Encoding.isNumber(data)) {
    return this.encodeNumber(data);
  }

  if (Encoding.isString(data)) {
    return this.encodeString(data);
  }

  if (Encoding.isBoolean(data)) {
    return this.encodeBoolean(data);
  }

  if (Encoding.isArray(data)) {
    return this.encodeArray(data);
  }

  if (Encoding.isObject(data)) {
    return this.encodeObject(data);
  }

  return Maybe.Nothing();
}

module.exports = Encoding;<|endoftext|>


<commit_before>/*
 * Copyright (C) 2007-2009 Diego Perini
 * All rights reserved.
 *
 * this is just a small example to show
 * how an extension for NWMatcher could be
 * adapted to handle special jQuery selectors
 *
 * Child Selectors
 * :even, :odd, :eq, :lt, :gt, :first, :last, :nth
 *
 * Pseudo Selectors
 * :has, :button, :header, :input, :checkbox, :radio, :file, :image
 * :password, :reset, :submit, :text, :hidden, :visible, :parent
 *
 */

// for structural pseudo-classes extensions
var jquery_ChildSelectors = function(match, source) {

  var status = true,
  // do not change this, it is searched & replaced
  ACCEPT_NODE = 'r[r.length]=c[k];continue main;';

  if (match[2]) {
    match[2] = match[2].replace(/^\((.*)\)$/, '$1');
  }

  switch (match[1]) {
    case 'even':
      source = source.replace(ACCEPT_NODE, 'x=1-x;if(x==1){' + ACCEPT_NODE + '}');
      break;
    case 'odd':
      source = source.replace(ACCEPT_NODE, 'x=1-x;if(x==0){' + ACCEPT_NODE + '}');
      break;
    case 'eq':
      source = source.replace(ACCEPT_NODE, 'if(x++==' + match[2] + '){' + ACCEPT_NODE + '}');
      break;
    case 'lt':
      source = source.replace(ACCEPT_NODE, 'if(x++<' + match[2] + '){' + ACCEPT_NODE + '}');
      break;
    case 'gt':
      source = source.replace(ACCEPT_NODE, 'if(x++>' + match[2] + '){' + ACCEPT_NODE + '}');
      break;
    case 'first':
      source = 'n=this.byTag(e.nodeName,e.ownerDocument);if(n&&n[0]==e){' + source + '}';
      break;
    case 'last':
      source = 'n=this.byTag(e.nodeName,e.ownerDocument);if(n&&n[n.length-1]==e){' + source + '}';
      break;
    case 'nth':
      match[2] = match[2].replace(/\(["']*|['"]*\)/g, '');
      source = 'n=this.byTag(e.nodeName,e.ownerDocument);if(n&&n[' + match[2] + ']==e){' + source + '}';
      break;
    default:
      status = false;
      break;
  }

  // compiler will add this to "source"
  return {
    'source': source,
    'status': status
  };

};

// for element pseudo-classes extensions
var jquery_PseudoSelectors = function(match, source) {

  var status = true,
  // do not change this, it is searched & replaced
  ACCEPT_NODE = 'r[r.length]=c[k];continue main;';

  switch(match[1]) {
    case 'has':
      if (match[2]) {
        match[2] = match[2].replace(/^\((.*)\)$/, '$1');
      }
      source = source.replace(ACCEPT_NODE, 'if(this.byTag("' + match[2] + '",e)[0]){' + ACCEPT_NODE + '}');
      break;
    case 'checkbox':
    case 'file':
    case 'image':
    case 'password':
    case 'radio':
    case 'reset':
    case 'submit':
    case 'text':
      // :checkbox, :file, :image, :password, :radio, :reset, :submit, :text, ... ;-)
      source = 'if(e.type&&e.type=="' + match[1] + '"){' + source + '}';
      break;
    case 'button':
    case 'input':
      source = 'if(e.type||/button/i.test(e.nodeName)){' + source + '}';
      break;
    case 'header':
      source = 'if(/h[1-6]/i.test(e.nodeName)){' + source + '}';
      break;
    case 'hidden':
      source = 'if(e.type=="hidden"||e.style.display=="none"||e.style.visibility=="hidden"){' + source + '}';
      break;
    case 'visible':
      source = 'if(e.type!="hidden"&&e.style.display!="none"&&e.style.visibility!="hidden"){' + source + '}';
      break;
    case 'parent':
      source += 'if(e.firstChild){' + source + '}';
      break;
    default:
      status = false;
      break;
  }

  // compiler will add this to "source"
  return {
    'source': source,
    'status': status
  };

};

// the following is taken directly from latest jQuery
// /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^-]|$)/;
var RE1 = /^\:(first|last|even|odd|nth|eq|gt|lt)(\((?:even|odd|[^\)]*)\))?(.*)/;
var RE2 = /^\:((?:[-\w]|\\.)+)(\(([\x22\x27]*)?(.*?(\(.*?\))?[^(]*?)\3\))?(.*)/;

// must register in this order due to how the selectors
// are written, the second begins with a grab all rule...
NW.Dom.registerSelector('jQuery-child', RE1, jquery_ChildSelectors);
NW.Dom.registerSelector('jQuery-pseudo', RE2, jquery_PseudoSelectors);

(function(global) {

  // # cleaned
  var cnt = 0,

  context = global.document,

  root = context.documentElement,

  // remove comment nodes and empty text nodes
  // unique child with empty text nodes are kept
  // to pass Prototype selector test unit :-)
  cleanDOM =
    function(node) {
      var next, val;
      while (node) {
        next = node.nextSibling;
        if (node.nodeType == 1 && node.firstChild) {
          cleanDOM(node.firstChild);
        } else if (node.nodeType == 3) {
          val = node.nodeValue.replace(/\s+/g, ' ');
          if (val == ' ' && node != node.parentNode.childNodes[0]) {
            node.parentNode.removeChild(node);
            cnt++;
          }
        } else if (node.nodeType == 8) {
          node.parentNode.removeChild(node);
        }
        node = next;
      }
    },

  start = root.addEventListener ?
    function() {
      context.removeEventListener('DOMContentLoaded', start, false);
      cleanDOM(root);
      NW.Dom.select('*:nth-child(n)');
      // XML parsing ?
      root.normalize();
      top.status += 'Removed ' + cnt + ' empty text nodes.';
    } :
    function() {
      if (context.readyState == 'complete') {
        context.detachEvent('onreadystatechange', start);
        cleanDOM(root);
        NW.Dom.select('*:nth-child(n)');
        // will crash IE6
        //root.normalize();
        top.status += 'Removed ' + cnt + ' empty text nodes.';
      }
    };

  if (context.addEventListener) {
    context.addEventListener('DOMContentLoaded', start, false);
  } else if (context.attachEvent) {
    context.attachEvent('onreadystatechange', start);
  } else {
    global.onload = start;
  }

})(this);
<commit_msg>syncronize changes done to nwmatcher, optimized augmentation of the result set<commit_after>/*
 * Copyright (C) 2007-2009 Diego Perini
 * All rights reserved.
 *
 * this is just a small example to show
 * how an extension for NWMatcher could be
 * adapted to handle special jQuery selectors
 *
 * Child Selectors
 * :even, :odd, :eq, :lt, :gt, :first, :last, :nth
 *
 * Pseudo Selectors
 * :has, :button, :header, :input, :checkbox, :radio, :file, :image
 * :password, :reset, :submit, :text, :hidden, :visible, :parent
 *
 */

// for structural pseudo-classes extensions
var jquery_ChildSelectors = function(match, source) {

  var status = true,
  // do not change this, it is searched & replaced
  ACCEPT_NODE = 'r[X++]=N;continue main;';

  if (match[2]) {
    match[2] = match[2].replace(/^\((.*)\)$/, '$1');
  }

  switch (match[1]) {
    case 'even':
      source = source.replace(ACCEPT_NODE, 'x=1-x;if(x==1){' + ACCEPT_NODE + '}');
      break;
    case 'odd':
      source = source.replace(ACCEPT_NODE, 'x=1-x;if(x==0){' + ACCEPT_NODE + '}');
      break;
    case 'eq':
      source = source.replace(ACCEPT_NODE, 'if(x++==' + match[2] + '){' + ACCEPT_NODE + '}');
      break;
    case 'lt':
      source = source.replace(ACCEPT_NODE, 'if(x++<' + match[2] + '){' + ACCEPT_NODE + '}');
      break;
    case 'gt':
      source = source.replace(ACCEPT_NODE, 'if(x++>' + match[2] + '){' + ACCEPT_NODE + '}');
      break;
    case 'first':
      source = 'n=this.byTag(e.nodeName,e.ownerDocument);if(n&&n[0]==e){' + source + '}';
      break;
    case 'last':
      source = 'n=this.byTag(e.nodeName,e.ownerDocument);if(n&&n[n.length-1]==e){' + source + '}';
      break;
    case 'nth':
      match[2] = match[2].replace(/\(["']*|['"]*\)/g, '');
      source = 'n=this.byTag(e.nodeName,e.ownerDocument);if(n&&n[' + match[2] + ']==e){' + source + '}';
      break;
    default:
      status = false;
      break;
  }

  // compiler will add this to "source"
  return {
    'source': source,
    'status': status
  };

};

// for element pseudo-classes extensions
var jquery_PseudoSelectors = function(match, source) {

  var status = true,
  // do not change this, it is searched & replaced
  ACCEPT_NODE = 'r[X++]=N;continue main;';

  switch(match[1]) {
    case 'has':
      if (match[2]) {
        match[2] = match[2].replace(/^\((.*)\)$/, '$1');
      }
      source = source.replace(ACCEPT_NODE, 'if(this.byTag("' + match[2] + '",e)[0]){' + ACCEPT_NODE + '}');
      break;
    case 'checkbox':
    case 'file':
    case 'image':
    case 'password':
    case 'radio':
    case 'reset':
    case 'submit':
    case 'text':
      // :checkbox, :file, :image, :password, :radio, :reset, :submit, :text, ... ;-)
      source = 'if(e.type&&e.type=="' + match[1] + '"){' + source + '}';
      break;
    case 'button':
    case 'input':
      source = 'if(e.type||/button/i.test(e.nodeName)){' + source + '}';
      break;
    case 'header':
      source = 'if(/h[1-6]/i.test(e.nodeName)){' + source + '}';
      break;
    case 'hidden':
      source = 'if(e.type=="hidden"||e.style.display=="none"||e.style.visibility=="hidden"){' + source + '}';
      break;
    case 'visible':
      source = 'if(e.type!="hidden"&&e.style.display!="none"&&e.style.visibility!="hidden"){' + source + '}';
      break;
    case 'parent':
      source += 'if(e.firstChild){' + source + '}';
      break;
    default:
      status = false;
      break;
  }

  // compiler will add this to "source"
  return {
    'source': source,
    'status': status
  };

};

// the following is taken directly from latest jQuery
// /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^-]|$)/;
var RE1 = /^\:(first|last|even|odd|nth|eq|gt|lt)(\((?:even|odd|[^\)]*)\))?(.*)/;
var RE2 = /^\:((?:[-\w]|\\.)+)(\(([\x22\x27]*)?(.*?(\(.*?\))?[^(]*?)\3\))?(.*)/;

// must register in this order due to how the selectors
// are written, the second begins with a grab all rule...
NW.Dom.registerSelector('jQuery-child', RE1, jquery_ChildSelectors);
NW.Dom.registerSelector('jQuery-pseudo', RE2, jquery_PseudoSelectors);

(function(global) {

  // # cleaned
  var cnt = 0,

  context = global.document,

  root = context.documentElement,

  // remove comment nodes and empty text nodes
  // unique child with empty text nodes are kept
  // to pass Prototype selector test unit :-)
  cleanDOM =
    function(node) {
      var next, val;
      while (node) {
        next = node.nextSibling;
        if (node.nodeType == 1 && node.firstChild) {
          cleanDOM(node.firstChild);
        } else if (node.nodeType == 3) {
          val = node.nodeValue.replace(/\s+/g, ' ');
          if (val == ' ' && node != node.parentNode.childNodes[0]) {
            node.parentNode.removeChild(node);
            cnt++;
          }
        } else if (node.nodeType == 8) {
          node.parentNode.removeChild(node);
        }
        node = next;
      }
    },

  start = root.addEventListener ?
    function() {
      context.removeEventListener('DOMContentLoaded', start, false);
      cleanDOM(root);
      NW.Dom.select('*:nth-child(n)');
      // XML parsing ?
      root.normalize();
      top.status += 'Removed ' + cnt + ' empty text nodes.';
    } :
    function() {
      if (context.readyState == 'complete') {
        context.detachEvent('onreadystatechange', start);
        cleanDOM(root);
        NW.Dom.select('*:nth-child(n)');
        // will crash IE6
        //root.normalize();
        top.status += 'Removed ' + cnt + ' empty text nodes.';
      }
    };

  if (context.addEventListener) {
    context.addEventListener('DOMContentLoaded', start, false);
  } else if (context.attachEvent) {
    context.attachEvent('onreadystatechange', start);
  } else {
    global.onload = start;
  }

})(this);
<|endoftext|>