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

	var CONFIG = {
		serverUid : "http",
		serverGid : "http",
		listenIPv4 : true,
		listenIPv6 : true,
		servicePort : 37320,
		workersMaxNum : 64,
		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.write("Timed out.");
			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.write("No vacancy for your request.");
				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"),

		parseStr = function (str) {
			var ret = {};

			str.toString().split("&").forEach(function (term) {
				var eqSplit = term.split("="),
				fieldName = decodeURIComponent(eqSplit.shift());

				if (fieldName === "") {
					return;
				}

				ret[fieldName] = decodeURIComponent(eqSplit.join("="));
			});

			return ret;
		},

		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),
				meta : {}
			};

			ret.request.meta.GET = parseStr(request.header.params.QUERY_STRING || "");
			ret.request.meta.POST = parseStr(request.header.params.CONTENT_TYPE === "application/x-www-form-urlencoded" ? ret.request.body.toString() : "");

			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.echo("Error during script execution.");
				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] meta is now named formData [core] Better POST form data setting<commit_after>(function () {
	"use strict";

	var CONFIG = {
		serverUid : "http",
		serverGid : "http",
		listenIPv4 : true,
		listenIPv6 : true,
		servicePort : 37320,
		workersMaxNum : 64,
		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.write("Timed out.");
			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.write("No vacancy for your request.");
				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"),

		parseStr = function (str) {
			var ret = {};

			str.toString().split("&").forEach(function (term) {
				var eqSplit = term.split("="),
				fieldName = decodeURIComponent(eqSplit.shift());

				if (fieldName === "") {
					return;
				}

				ret[fieldName] = decodeURIComponent(eqSplit.join("="));
			});

			return ret;
		},

		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),
				formData : {}
			};

			ret.request.formData.GET = parseStr(request.header.params.QUERY_STRING || "");
			ret.request.formData.POST = parseStr(request.header.params.REQUEST_METHOD.toUpperCase() === "POST" && request.header.params.CONTENT_TYPE.toLowerCase() === "application/x-www-form-urlencoded" ? ret.request.body.toString() : "");

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

/*global Windows:true */

var cordova = require('cordova'),
    CompassHeading = require('org.apache.cordova.core.device-orientation.CompassHeading'),
    CompassError = require('org.apache.cordova.core.device-orientation.CompassError')

module.exports = {

    onReadingChanged:null,
    getHeading:function(win,lose) {
        var deviceCompass = Windows.Devices.Sensors.Compass.getDefault();
        if(!deviceCompass) {
            setTimeout(function(){
                lose(CompassError.COMPASS_NOT_SUPPORTED);
            },0);
        }
        else {

            deviceCompass.reportInterval = Math.max(16,deviceCompass.minimumReportInterval);

            this.onReadingChanged = function(e) {
                var reading = e.reading;
                var heading = new CompassHeading(reading.headingMagneticNorth, reading.headingTrueNorth,null,reading.timestamp);
                win(heading);
            };
            deviceCompass.addEventListener("readingchanged",this.onReadingChanged);
        }
    },
    stopHeading:function(win,lose) {
        var deviceCompass = Windows.Devices.Sensors.Compass.getDefault();
        if(!deviceCompass) {
            setTimeout(function(){
                lose(CompassError.COMPASS_NOT_SUPPORTED);
            },0);
        }
        else {
            deviceCompass.removeEventListener("readingchanged",this.onReadingChanged);
            this.onReadingChanged = null;
            deviceCompass.reportInterval = 0;
            win();
        }

    }
};

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

/*global Windows:true */

var cordova = require('cordova'),
    CompassHeading = require('org.apache.cordova.device-orientation.CompassHeading'),
    CompassError = require('org.apache.cordova.device-orientation.CompassError')

module.exports = {

    onReadingChanged:null,
    getHeading:function(win,lose) {
        var deviceCompass = Windows.Devices.Sensors.Compass.getDefault();
        if(!deviceCompass) {
            setTimeout(function(){
                lose(CompassError.COMPASS_NOT_SUPPORTED);
            },0);
        }
        else {

            deviceCompass.reportInterval = Math.max(16,deviceCompass.minimumReportInterval);

            this.onReadingChanged = function(e) {
                var reading = e.reading;
                var heading = new CompassHeading(reading.headingMagneticNorth, reading.headingTrueNorth,null,reading.timestamp);
                win(heading);
            };
            deviceCompass.addEventListener("readingchanged",this.onReadingChanged);
        }
    },
    stopHeading:function(win,lose) {
        var deviceCompass = Windows.Devices.Sensors.Compass.getDefault();
        if(!deviceCompass) {
            setTimeout(function(){
                lose(CompassError.COMPASS_NOT_SUPPORTED);
            },0);
        }
        else {
            deviceCompass.removeEventListener("readingchanged",this.onReadingChanged);
            this.onReadingChanged = null;
            deviceCompass.reportInterval = 0;
            win();
        }

    }
};

require("cordova/commandProxy").add("Compass",module.exports);});
<|endoftext|>


<commit_before>var express = require('express');
var app = express.createServer();
var stylus = require('stylus');

var str = require('fs').readFileSync(__dirname + '/views/style.styl', 'utf8');

app.set('view engine', 'jade');
app.set('views', __dirname + '/views');

app.configure(function(){
    app.use(express.methodOverride());
    app.use(express.bodyParser());
    app.use(app.router);
    app.use(express.static(__dirname + '/public'));
    app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});

var Subject = require('./models/subject').Subject;
var subject = new Subject();

app.get('/', function(request, response) {
	subject.findAll(function(error, subjects) {
		response.render('index', {
			layout: false,
			locals: {
				pageTitle: 'Do we have a quorum?',
				subjects: subjects
			}
		});
	});
	response.end();
});

app.get('/*.css', function(file) {
	response.render(str, {
		layout: false,
		filename: file + '.styl'
	});
});

app.listen(process.env.PORT || 8001);<commit_msg>Attempting different approach for stylus<commit_after>var express = require('express');
var app = express.createServer();

var css = require('stylus')
  , str = require('fs').readFileSync(__dirname + '/views/style.styl', 'utf8');

css.render(str, { filename: 'views/style.styl' }, function(err, css){
  if (err) throw err;
  console.log(css);
});

app.set('view engine', 'jade');
app.set('views', __dirname + '/views');

app.configure(function(){
    app.use(express.methodOverride());
    app.use(express.bodyParser());
    app.use(app.router);
    app.use(express.static(__dirname + '/public'));
    app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});

var Subject = require('./models/subject').Subject;
var subject = new Subject();

app.get('/', function(request, response) {
	subject.findAll(function(error, subjects) {
		response.render('index', {
			layout: false,
			locals: {
				pageTitle: 'Do we have a quorum?',
				subjects: subjects
			}
		});
	});
	response.end();
});

/*app.get('/*.css', function(file) {
	response.render(str, {
		layout: false,
		filename: file + '.styl'
	});
});*/

app.listen(process.env.PORT || 8001);<|endoftext|>


<commit_before>
// This file is the app starting point.
// It launches the server contained in the 'server' variable.

/*jshint node:true, laxcomma:true*/
/*eslint global-require:"warn"*/

'use strict';

// To have docker messages with beautiful colors on console.
var kuler = require('kuler');

var heartbeats = require('heartbeats');

var instances = require('./helpers/instances');

// config : variable containing app configuration elements.
// start : callback function declared a bit later.
module.exports = function(config, start) {

  // App configuration initialisation before web server launch.
  config.set('theme', __dirname);
  config.set('timeout', 1E6);

  // Web server launch.
  // err : to catch errors.
  // If all good, the 'server' variable contains the server.
  start(function online(err, server) {

    // Use socket.io on the server.
    var io = require('socket.io').listen(server);

    io.sockets.on('connection', function (socket){

      // Caching the instances list to have a reference for comparisons to come.
        var cacheInstances = {};

      // THE HEARTBEATS HEART

        // Repeat every 5000 milliseconds = every 5 seconds.
        var heart1 = heartbeats.createHeart(10000);

        // For infinite repeat we use {repeat : 0}.
        heart1.createEvent(1, {repeat : 0}, function(heartbeat, last){

          // Instructions done on each heart beat.

  console.log("########## BEAT ! ##########");

            instances.getInstances(function(err,beatInstances){

              // If there are some differences between cacheInstances (reference) and beatInstances (just get) :
                // Update cacheInstances with beatInstances.
                // Broadcast to all users this new version to update the 'containers' variable in template.html.
              if(!(JSON.stringify(cacheInstances) === JSON.stringify(beatInstances) )) {

                cacheInstances = beatInstances;
                socket.broadcast.emit('refreshInstances', beatInstances);

              }

            });

        });

    });

    if (err instanceof Error) {
      console.error(kuler('Unable to init the server.', 'red'), kuler(err.toString(), 'orangered'));
      process.exit(3);
      return;
    }
    var pack = config.get('package');
    if (pack) {
      console.info(kuler('App detected.', 'olive'), kuler(pack.name
        + ' ' + pack.version, 'limegreen'));
    }
    console.info(kuler('Server is listening.', 'olive'),  kuler(config.get('baseURL')
      + '/', 'limegreen'));

  });
};<commit_msg>Test heartbeat on vilodex.<commit_after>
// This file is the app starting point.
// It launches the server contained in the 'server' variable.

/*jshint node:true, laxcomma:true*/
/*eslint global-require:"warn"*/

'use strict';

// To have docker messages with beautiful colors on console.
var kuler = require('kuler');

var heartbeats = require('heartbeats');

var instances = require('./helpers/instances');

// config : variable containing app configuration elements.
// start : callback function declared a bit later.
module.exports = function(config, start) {

  // App configuration initialisation before web server launch.
  config.set('theme', __dirname);
  config.set('timeout', 1E6);

  // Web server launch.
  // err : to catch errors.
  // If all good, the 'server' variable contains the server.
  start(function online(err, server) {

    // Use socket.io on the server.
    var io = require('socket.io').listen(server);

    io.sockets.on('connection', function (socket){

      // Caching the instances list to have a reference for comparisons to come.
        var cacheInstances = {};

      // THE HEARTBEATS HEART

        // Repeat every 5000 milliseconds = every 5 seconds.
        var heart1 = null;
        heart1 = heartbeats.createHeart(10000);

        // For infinite repeat we use {repeat : 0}.
        heart1.createEvent(1, {repeat : 0}, function(heartbeat, last){

          // Instructions done on each heart beat.

  console.log("########## BEAT ! ##########");

            instances.getInstances(function(err,beatInstances){

              // If there are some differences between cacheInstances (reference) and beatInstances (just get) :
                // Update cacheInstances with beatInstances.
                // Broadcast to all users this new version to update the 'containers' variable in template.html.
              if(!(JSON.stringify(cacheInstances) === JSON.stringify(beatInstances) )) {

                cacheInstances = beatInstances;
                socket.broadcast.emit('refreshInstances', beatInstances);

              }

            });

        });

    });

    if (err instanceof Error) {
      console.error(kuler('Unable to init the server.', 'red'), kuler(err.toString(), 'orangered'));
      process.exit(3);
      return;
    }
    var pack = config.get('package');
    if (pack) {
      console.info(kuler('App detected.', 'olive'), kuler(pack.name
        + ' ' + pack.version, 'limegreen'));
    }
    console.info(kuler('Server is listening.', 'olive'),  kuler(config.get('baseURL')
      + '/', 'limegreen'));

  });
};<|endoftext|>


<commit_before>'use strict'

const path = require('path')

const stringifyHtml = require('./lib/stringifyHtml')
const makeFilesObj = require('./lib/makeFilesObj')
const hashFilesObj = require('./lib/hashFilesObj')
const writeJsDL = require('./lib/writeJsDL')
const writeJsUL = require('./lib/writeJsUL')
const replaceHtml = require('./lib/replaceHtml')
const writeNewHtml = require('./lib/writeNewHtml')
const botGenerator = require(('./src/botGenerator'))

function WebFlight (options) {
  Object.keys(options).forEach((key) => {
    this[key] = options[key]
  })
  this.count = 0
}

// options :: Object
  // originalHtml: .html file to be rebuilt
  // filesFolder: folder with files to be torrented
  // filesRoute: path on the server for files
  // jsOutputDL: location and name for webflight.js file
  // jsOutputUL: location and name for file seeding torrents
  // htmlOutput: location and name for rebuilt html file
  // route: route to redirect

WebFlight.prototype.start = function () {
  const originalHtmlString = stringifyHtml(this.originalHtml)
  const filesObj = makeFilesObj(this.filesFolder, this.filesRoute)

  hashFilesObj(filesObj)
    .then(writeJsDL.bind(null, this.jsOutputDL))
    .then(writeJsUL.bind(null, this.jsOutputUL))
    .then(replaceHtml.bind(null, originalHtmlString, path.basename(this.jsOutputDL)))
    .then(writeNewHtml.bind(null, this.htmlOutput))
    .then(botGenerator.bind(null, this))
}

WebFlight.prototype.redirect = function (req, res, next) {
  const destination = req.originalUrl

  if (destination === '/count.check.4wf') {
    res.send({count: this.count})
  }

  if (path.extname(destination) === '.html' || path.extname(destination) === '') {
    console.log(++this.count, 'entering')

    setTimeout(function () { console.log(--this.count, 'exiting') }.bind(this), 10000)
  }

  if (this.routes[destination]) {

    res.sendFile(this.htmlOutput)
  } else {
    next()
  }
}

module.exports = WebFlight
<commit_msg>adds model for new options obj<commit_after>'use strict'

const path = require('path')

const stringifyHtml = require('./lib/stringifyHtml')
const makeFilesObj = require('./lib/makeFilesObj')
const hashFilesObj = require('./lib/hashFilesObj')
const writeJsDL = require('./lib/writeJsDL')
const writeJsUL = require('./lib/writeJsUL')
const replaceHtml = require('./lib/replaceHtml')
const writeNewHtml = require('./lib/writeNewHtml')
const botGenerator = require(('./src/botGenerator'))

function WebFlight (options) {
  Object.keys(options).forEach((key) => {
    this[key] = options[key]
  })
  this.count = 0
}

/**
new config obj. enables collections of asset Paths/ Routes
  configObj = {
   assetsPath: ''/['', ''],
   assetsRoute: ''/['', ''],
   wfPath: ''/Default(__dirname + '/wfPath'),
   wfRoute: ''/Default('/wfRoute'),
   seedScript: ''/Default('wf-seed.js'),
   routes: {
     '/about.html': 'path/to/about.html'
   }
  }
*/

WebFlight.prototype.start = function () {
  const originalHtmlString = stringifyHtml(this.originalHtml)
  const filesObj = makeFilesObj(this.filesFolder, this.filesRoute)

  hashFilesObj(filesObj)
    .then(writeJsDL.bind(null, this.jsOutputDL))
    .then(writeJsUL.bind(null, this.jsOutputUL))
    .then(replaceHtml.bind(null, originalHtmlString, path.basename(this.jsOutputDL)))
    .then(writeNewHtml.bind(null, this.htmlOutput))
    .then(botGenerator.bind(null, this))
}

WebFlight.prototype.redirect = function (req, res, next) {
  const destination = req.originalUrl

  if (destination === '/count.check.4wf') {
    res.send({count: this.count})
  }

  if (path.extname(destination) === '.html' || path.extname(destination) === '') {
    console.log(++this.count, 'entering')

    setTimeout(function () { console.log(--this.count, 'exiting') }.bind(this), 10000)
  }

  if (this.routes[destination]) {

    res.sendFile(this.htmlOutput)
  } else {
    next()
  }
}

module.exports = WebFlight
<|endoftext|>


<commit_before>/**
 * Created by jordan on 25/01/15.
 */

var soundManager = (function () {
    var instance;

    function initSoundManager(numChannels) {
        this.channel_max = numChannels || 10;
        this.audioChannels = [];
        this.nextChannel = 0;

        this.loopChannel = new Audio();
        this.loopChannel.addEventListener('ended', function() {
            this.currentTime = 0;
            this.play();
        }, false);

        for (var a = 0; a < this.channel_max; a++) {
            this.audioChannels[a] = new Audio();					// expected end time for this channel
        }
    }

    function createInstance() {
        var _soundManager = new initSoundManager();

        _soundManager.playSound = function(sound) {
            this.nextChannel = this.nextChannel == this.audioChannels-1 ? 0 : this.nextChannel++;

            this.audioChannels[this.nextChannel].src = document.getElementById(sound).src;
            this.audioChannels[this.nextChannel].load();
            this.audioChannels[this.nextChannel].play();
        };

        _soundManager.stopAllSounds = function() {
            for (var a = 0; a < this.audioChannels.length;a++) {
                this.audioChannels[a]['channel'].stop();
            }
        };

        _soundManager.playLoop = function(sound) {
            this.loopChannel.src = document.getElementById(sound).src;
            this.loopChannel.load();
            this.loopChannel.volume = 0.45;
            this.loopChannel.play();
        };

        return _soundManager;
    }

    return {
        getInstance: function () {
            if (!instance) {
                instance = createInstance();
            }
            return instance;
        }
    };
})();<commit_msg>Fixed sound manager clobbering effects<commit_after>/**
 * Created by jordan on 25/01/15.
 */

var soundManager = (function () {
    var instance;

    function initSoundManager(numChannels) {
        this.channel_max = numChannels || 10;
        this.audioChannels = [];
        this.nextChannel = 0;

        this.loopChannel = new Audio();
        this.loopChannel.addEventListener('ended', function() {
            this.currentTime = 0;
            this.play();
        }, false);

        for (var a = 0; a < this.channel_max; a++) {
            this.audioChannels[a] = new Audio();					// expected end time for this channel
        }
    }

    function createInstance() {
        var _soundManager = new initSoundManager();

        _soundManager.playSound = function(sound) {
            this.nextChannel++;
            if(this.nextChannel == this.channel_max)
            {
                this.nextChannel = 0;
            }

            this.audioChannels[this.nextChannel].src = document.getElementById(sound).src;
            this.audioChannels[this.nextChannel].load();
            this.audioChannels[this.nextChannel].play();
        };

        _soundManager.stopAllSounds = function() {
            for (var a = 0; a < this.audioChannels.length;a++) {
                this.audioChannels[a].stop();
            }
        };

        _soundManager.playLoop = function(sound) {
            this.loopChannel.src = document.getElementById(sound).src;
            this.loopChannel.load();
            this.loopChannel.volume = 0.45;
            this.loopChannel.play();
        };

        return _soundManager;
    }

    return {
        getInstance: function () {
            if (!instance) {
                instance = createInstance();
            }
            return instance;
        }
    };
})();<|endoftext|>


<commit_before>import * as macro from '../../../macro';
import DataAccessHelper from '../../Core/DataAccessHelper';
import vtkTexture from '../../../Rendering/Core/Texture';

// ----------------------------------------------------------------------------
// vtkMTLReader methods
// ----------------------------------------------------------------------------

function vtkMTLReader(publicAPI, model) {
  // Set our className
  model.classHierarchy.push('vtkMTLReader');

  function imageReady() {
    model.requestCount--;
    if (model.requestCount === 0) {
      publicAPI.invokeBusy(false);
    }
  }

  function parseLine(line) {
    if (line[0] === '#' || line.length === 0) {
      return;
    }

    const tokens = line
      .split(/[ \t]+/)
      .map((s) => s.trim())
      .filter((s) => s.length);
    if (tokens[0] === 'newmtl') {
      tokens.shift();
      model.currentMaterial = tokens.join(' ').trim();
    } else if (model.currentMaterial) {
      if (tokens.length < 2) {
        return;
      }
      if (!model.materials[model.currentMaterial]) {
        model.materials[model.currentMaterial] = {};
      }
      model.materials[model.currentMaterial][tokens[0]] = tokens.slice(1);
      if (tokens[0] === 'map_Kd') {
        const image = new Image();
        image.src = [model.baseURL, tokens[1]].join('/');
        image.onload = imageReady;
        model.materials[model.currentMaterial].image = image;
        model.requestCount++;
      }
    }
  }

  // Create default dataAccessHelper if not available
  if (!model.dataAccessHelper) {
    model.dataAccessHelper = DataAccessHelper.get('http');
  }

  // Internal method to fetch Array
  function fetchData(url) {
    const compression = model.compression;
    const progressCallback = model.progressCallback;
    return model.dataAccessHelper.fetchText(publicAPI, url, {
      compression,
      progressCallback,
    });
  }

  // Set DataSet url
  publicAPI.setUrl = (url, option = {}) => {
    if (url.indexOf('.mtl') === -1 && !option.fullpath) {
      model.baseURL = url;
      model.url = `${url}/index.mtl`;
    } else {
      model.url = url;

      // Remove the file in the URL
      const path = url.split('/');
      path.pop();
      model.baseURL = path.join('/');
    }

    model.compression = option.compression;

    // Fetch metadata
    return publicAPI.loadData();
  };

  // Fetch the actual data arrays
  publicAPI.loadData = () =>
    new Promise((resolve, reject) => {
      fetchData(model.url).then(
        (content) => {
          publicAPI.parse(content);
          resolve();
        },
        (err) => {
          reject();
        }
      );
    });

  publicAPI.parse = (content) => {
    publicAPI.modified();
    model.materials = {};
    content.split('\n').forEach(parseLine);
  };

  // return Busy state
  publicAPI.isBusy = () => !!model.requestCount;

  publicAPI.getMaterialNames = () => Object.keys(model.materials);
  publicAPI.getMaterial = (name) => model.materials[name];

  publicAPI.listImages = () =>
    Object.keys(model.materials)
      .map((name) => model.materials[name].map_Kd)
      .filter((fileName) => !!fileName)
      .map((s) => s[0].trim());

  publicAPI.setImageSrc = (imagePath, src) => {
    const selectedName = Object.keys(model.materials).find(
      (name) =>
        model.materials[name].map_Kd &&
        model.materials[name].map_Kd[0].trim() === imagePath.trim()
    );
    const material = model.materials[selectedName];
    if (material && material.image) {
      material.image.src = src;
    }
  };

  publicAPI.applyMaterialToActor = (name, actor) => {
    const material = model.materials[name];
    if (material && actor) {
      const white = [1, 1, 1];
      const actorProp = {
        ambientColor: material.Ka ? material.Ka.map((i) => Number(i)) : white,
        specularColor: material.Ks ? material.Ks.map((i) => Number(i)) : white,
        diffuseColor: material.Kd ? material.Kd.map((i) => Number(i)) : white,
        opacity: material.d ? Number(material.d) : 1,
        specularPower: material.Ns ? Number(material.Ns) : 1,
      };
      const illum = Number(material.illum || 2);
      ['ambient', 'diffuse', 'specular'].forEach((k, idx) => {
        actorProp[k] = idx <= illum ? 1.0 : 0.0;
      });
      if (material.image) {
        const texture = vtkTexture.newInstance({ interpolate: true });
        texture.setImage(material.image);
        actor.addTexture(texture);
      }
      actor.getProperty().set(actorProp);
    }
  };
}

// ----------------------------------------------------------------------------
// Object factory
// ----------------------------------------------------------------------------

const DEFAULT_VALUES = {
  numberOfOutputs: 1,
  requestCount: 0,
  materials: {},
  // baseURL: null,
  // dataAccessHelper: null,
  // url: null,
};

// ----------------------------------------------------------------------------

export function extend(publicAPI, model, initialValues = {}) {
  Object.assign(model, DEFAULT_VALUES, initialValues);

  // Build VTK API
  macro.obj(publicAPI, model);
  macro.get(publicAPI, model, ['url', 'baseURL']);
  macro.setGet(publicAPI, model, ['dataAccessHelper', 'splitGroup']);
  macro.event(publicAPI, model, 'busy');

  // Object methods
  vtkMTLReader(publicAPI, model);
}

// ----------------------------------------------------------------------------

export const newInstance = macro.newInstance(extend, 'vtkMTLReader');

// ----------------------------------------------------------------------------

export default { newInstance, extend };
<commit_msg>fix(MTLReader): ESLint<commit_after>import * as macro from '../../../macro';
import DataAccessHelper from '../../Core/DataAccessHelper';
import vtkTexture from '../../../Rendering/Core/Texture';

// ----------------------------------------------------------------------------
// vtkMTLReader methods
// ----------------------------------------------------------------------------

function vtkMTLReader(publicAPI, model) {
  // Set our className
  model.classHierarchy.push('vtkMTLReader');

  function imageReady() {
    model.requestCount--;
    if (model.requestCount === 0) {
      publicAPI.invokeBusy(false);
    }
  }

  function parseLine(line) {
    if (line[0] === '#' || line.length === 0) {
      return;
    }

    const tokens = line
      .split(/[ \t]+/)
      .map((s) => s.trim())
      .filter((s) => s.length);
    if (tokens[0] === 'newmtl') {
      tokens.shift();
      model.currentMaterial = tokens.join(' ').trim();
    } else if (model.currentMaterial) {
      if (tokens.length < 2) {
        return;
      }
      if (!model.materials[model.currentMaterial]) {
        model.materials[model.currentMaterial] = {};
      }
      model.materials[model.currentMaterial][tokens[0]] = tokens.slice(1);
      if (tokens[0] === 'map_Kd') {
        const image = new Image();
        image.src = [model.baseURL, tokens[1]].join('/');
        image.onload = imageReady;
        model.materials[model.currentMaterial].image = image;
        model.requestCount++;
      }
    }
  }

  // Create default dataAccessHelper if not available
  if (!model.dataAccessHelper) {
    model.dataAccessHelper = DataAccessHelper.get('http');
  }

  // Internal method to fetch Array
  function fetchData(url) {
    const { compression, progressCallback } = model;
    return model.dataAccessHelper.fetchText(publicAPI, url, {
      compression,
      progressCallback,
    });
  }

  // Set DataSet url
  publicAPI.setUrl = (url, option = {}) => {
    if (url.indexOf('.mtl') === -1 && !option.fullpath) {
      model.baseURL = url;
      model.url = `${url}/index.mtl`;
    } else {
      model.url = url;

      // Remove the file in the URL
      const path = url.split('/');
      path.pop();
      model.baseURL = path.join('/');
    }

    model.compression = option.compression;

    // Fetch metadata
    return publicAPI.loadData();
  };

  // Fetch the actual data arrays
  publicAPI.loadData = () =>
    new Promise((resolve, reject) => {
      fetchData(model.url).then(
        (content) => {
          publicAPI.parse(content);
          resolve();
        },
        (err) => {
          reject();
        }
      );
    });

  publicAPI.parse = (content) => {
    publicAPI.modified();
    model.materials = {};
    content.split('\n').forEach(parseLine);
  };

  // return Busy state
  publicAPI.isBusy = () => !!model.requestCount;

  publicAPI.getMaterialNames = () => Object.keys(model.materials);
  publicAPI.getMaterial = (name) => model.materials[name];

  publicAPI.listImages = () =>
    Object.keys(model.materials)
      .map((name) => model.materials[name].map_Kd)
      .filter((fileName) => !!fileName)
      .map((s) => s[0].trim());

  publicAPI.setImageSrc = (imagePath, src) => {
    const selectedName = Object.keys(model.materials).find(
      (name) =>
        model.materials[name].map_Kd &&
        model.materials[name].map_Kd[0].trim() === imagePath.trim()
    );
    const material = model.materials[selectedName];
    if (material && material.image) {
      material.image.src = src;
    }
  };

  publicAPI.applyMaterialToActor = (name, actor) => {
    const material = model.materials[name];
    if (material && actor) {
      const white = [1, 1, 1];
      const actorProp = {
        ambientColor: material.Ka ? material.Ka.map((i) => Number(i)) : white,
        specularColor: material.Ks ? material.Ks.map((i) => Number(i)) : white,
        diffuseColor: material.Kd ? material.Kd.map((i) => Number(i)) : white,
        opacity: material.d ? Number(material.d) : 1,
        specularPower: material.Ns ? Number(material.Ns) : 1,
      };
      const illum = Number(material.illum || 2);
      ['ambient', 'diffuse', 'specular'].forEach((k, idx) => {
        actorProp[k] = idx <= illum ? 1.0 : 0.0;
      });
      if (material.image) {
        const texture = vtkTexture.newInstance({ interpolate: true });
        texture.setImage(material.image);
        actor.addTexture(texture);
      }
      actor.getProperty().set(actorProp);
    }
  };
}

// ----------------------------------------------------------------------------
// Object factory
// ----------------------------------------------------------------------------

const DEFAULT_VALUES = {
  numberOfOutputs: 1,
  requestCount: 0,
  materials: {},
  // baseURL: null,
  // dataAccessHelper: null,
  // url: null,
};

// ----------------------------------------------------------------------------

export function extend(publicAPI, model, initialValues = {}) {
  Object.assign(model, DEFAULT_VALUES, initialValues);

  // Build VTK API
  macro.obj(publicAPI, model);
  macro.get(publicAPI, model, ['url', 'baseURL']);
  macro.setGet(publicAPI, model, ['dataAccessHelper', 'splitGroup']);
  macro.event(publicAPI, model, 'busy');

  // Object methods
  vtkMTLReader(publicAPI, model);

  // To support destructuring
  if (!model.compression) {
    model.compression = null;
  }
  if (!model.progressCallback) {
    model.progressCallback = null;
  }
}

// ----------------------------------------------------------------------------

export const newInstance = macro.newInstance(extend, 'vtkMTLReader');

// ----------------------------------------------------------------------------

export default { newInstance, extend };
<|endoftext|>


<commit_before>import Atom from '../reactiveCollection/Atom'
import {transaction} from 'mobservable'

export default function (arg) {
  var itemsCache = {}
  var queriesCache = {}

  var client = arg.fth.service(arg.serviceName)
  var watcher = arg.fth.service(arg.serviceName+'/subscriptions')

  watcher.on('change', function({key, type, value}) {
    console.log('received change for', key, value)
    if (type === 'query') {
      var obs = queriesCache[key]
      obs.setValue({
        loading: false,
        loaded: new Date().toISOString(),
        value: type === 'item' ? value : value.data.map(o => o.id),
      })
      // on profite d'avoir déjà les valeurs des items pour mettre à jour le cache
      // mais on ne le fait pas dans la même transaction que la query pour permettre aux fonctions de rendu de s'abonner aux items
      transaction(() => {
        value.data.forEach(item => {
          var obs = itemsCache[item.id]
          if (obs) {
            obs.setValue({
              loading: false,
              loaded: new Date(),
              value: item,
            })
          }
        })
      })
    } else { // type === 'item'
      var obs = itemsCache[key]
      obs.setValue({
        loading: false,
        loaded: new Date().toISOString(),
        value: value,
      })
    }
  })

  var watch = function (type, key, params) {
    console.log('start watching', type, arg.serviceName, params)
    return watcher.create({id: key, type: type, params: params})
  }
  var unwatch = function (key) {
    return watcher.remove(key)
  }

  var model = {
    name: arg.serviceName,
    get: function (itemId) {
      var key = 'item::'+itemId
      if (! (key in itemsCache)) {
        var item = new Atom({loading: true, loaded: false, value: {}})
        itemsCache[key] = item
        item.onBecomeUnobserved(function () {
          console.log('item disposed', arg.serviceName, itemId)
          unwatch(key)
          delete itemsCache[key];
        })
        watch('item', key, itemId)
      }
      return itemsCache[key].getValue()
    },
    query: function (params) {
      params = params || {}
      var key = 'query::'+JSON.stringify(params)
      if (! queriesCache[key]) {
        var item = new Atom({loading: true, loaded: false, value: []})
        queriesCache[key] = item
        item.onBecomeUnobserved(function () {
          console.log('query disposed', arg.serviceName, params)
          unwatch(key)
          delete queriesCache[key]
        })
        watch('query', key, params)
      }
      return queriesCache[key].getValue()
    },
  }

  var actions = {
    add: function (data) {
      return ['create', data]
    },
    remove: function (itemId) {
      return ['remove', itemId]
    },
    patch: function (itemId, patch) {
      return ['patch', itemId, patch]
    },
  }
  if (arg.actions) Object.assign(actions, arg.actions)

  Object.keys(actions).forEach(function(actionName) {
    model[actionName] = function () {
      var requestArgs = actions[actionName].apply(null, arguments)
      var resp = client[requestArgs[0]](requestArgs[1], requestArgs[2])
      return resp.catch(err => {
        console.error(arg.serviceName, actionName, err)
        throw err
      }).then(function () {
        console.log('done', requestArgs[0], requestArgs[1], requestArgs[2])
        return resp
      })
    }
  })

  return model
}
<commit_msg>resubscribing to feathers services when reconnecting<commit_after>import Atom from '../reactiveCollection/Atom'
import {transaction} from 'mobservable'

export default function (arg) {
  var itemsCache = {}
  var queriesCache = {}

  var client = arg.fth.service(arg.serviceName)
  var watcher = arg.fth.service(arg.serviceName+'/subscriptions')

  watcher.on('change', function({key, type, value}) {
    console.log('received change for', key, value)
    if (type === 'query') {
      var obs = queriesCache[key]
      obs.setValue({
        loading: false,
        loaded: new Date().toISOString(),
        value: type === 'item' ? value : value.data.map(o => o.id),
      })
      // on profite d'avoir déjà les valeurs des items pour mettre à jour le cache
      // mais on ne le fait pas dans la même transaction que la query pour permettre aux fonctions de rendu de s'abonner aux items
      transaction(() => {
        value.data.forEach(item => {
          var obs = itemsCache[item.id]
          if (obs) {
            obs.setValue({
              loading: false,
              loaded: new Date(),
              value: item,
            })
          }
        })
      })
    } else { // type === 'item'
      var obs = itemsCache[key]
      obs.setValue({
        loading: false,
        loaded: new Date().toISOString(),
        value: value,
      })
    }
  })

  var watch = function (type, key, params) {
    console.log('start watching', type, arg.serviceName, params)
    return watcher.create({id: key, type: type, params: params})
  }
  var unwatch = function (key) {
    return watcher.remove(key)
  }

  arg.fth.io.on('disconnect', function () {
    console.log('disconnected', arg.serviceName)
  })

  arg.fth.io.on('connect', function () {
    console.log("reconnected, resubscribing to everything", arg.serviceName)
    Object.keys(queriesCache).forEach(queryKey => {
      var params = JSON.parse(queryKey.split('::')[1])
      watch('query', queryKey, params)
    })
    Object.keys(itemsCache).forEach(itemKey => {
      var itemId =itemKey.split('::')[1]
      watch('item', itemKey, itemId)
    })
  })

  var model = {
    name: arg.serviceName,
    get: function (itemId) {
      var key = 'item::'+itemId
      if (! (key in itemsCache)) {
        var item = new Atom({loading: true, loaded: false, value: {}})
        itemsCache[key] = item
        item.onBecomeUnobserved(function () {
          console.log('item disposed', arg.serviceName, itemId)
          unwatch(key)
          delete itemsCache[key];
        })
        watch('item', key, itemId)
      }
      return itemsCache[key].getValue()
    },
    query: function (params) {
      params = params || {}
      var key = 'query::'+JSON.stringify(params)
      if (! queriesCache[key]) {
        var item = new Atom({loading: true, loaded: false, value: []})
        queriesCache[key] = item
        item.onBecomeUnobserved(function () {
          console.log('query disposed', arg.serviceName, params)
          unwatch(key)
          delete queriesCache[key]
        })
        watch('query', key, params)
      }
      return queriesCache[key].getValue()
    },
  }

  var actions = {
    add: function (data) {
      return ['create', data]
    },
    remove: function (itemId) {
      return ['remove', itemId]
    },
    patch: function (itemId, patch) {
      return ['patch', itemId, patch]
    },
  }
  if (arg.actions) Object.assign(actions, arg.actions)

  Object.keys(actions).forEach(function(actionName) {
    model[actionName] = function () {
      var requestArgs = actions[actionName].apply(null, arguments)
      var resp = client[requestArgs[0]](requestArgs[1], requestArgs[2])
      return resp.catch(err => {
        console.error(arg.serviceName, actionName, err)
        throw err
      }).then(function () {
        console.log('done', requestArgs[0], requestArgs[1], requestArgs[2])
        return resp
      })
    }
  })

  return model
}
<|endoftext|>


<commit_before>import Asset from '../../Asset/asset'

/**
 * Class representing a Real Asset
 * @memberof module:assets
 * @extends module:assets.Asset
 */
class RealAsset extends Asset {
  /**
   * Construct a new Real Asset instance
   * @param {object} params - RealAsset creation options
   * @param {number} params.assetManagerId - ID of Asset's Asset Manager __(required)__
   * @param {number} params.assetId - ID of the Asset __(required)__
   * @param {string} [params.assetClass=RealAsset] - Class of the Asset (a subclass of RealAsset may define its own assetClass)
   * @param {string} [params.assetType] - Type of the Asset. Auto-set based on the class or subclass constructor
   * @param {string} [params.assetTypeDisplay] - Auto-set to the spaced class name (e.g. `Listed Derivative` for `ListedDerivative()`)
   * @param {boolean} [params.fungible=false] - Auto-set to `false` __(read-only)__
   * @param {string} [params.assetIssuerId] - ID of the Real Asset's issuer
   * @param {string} [params.assetStatus=Active] - Status of the Real Asset
   * @param {string} [params.countryId] - ID of Real Asset's country
   * @param {string} [params.venueId] - ID of Real Asset's venue if applicable
   * @param {string} [params.currency] - Real Asset currency (e.g. USD, SGD)
   * @param {string} [params.description] - Description of the Real Asset
   * @param {string} [params.displayName] - Display name of the Asset
   * @param {boolean} [params.rollPrice=true] - Whether to roll the price for the Asset
   * @param {string} [params.clientId] - ID of the associated client
   * @param {object} [params.comments] - Object of Comments attached to the Real Asset
   * @param {object} [params.links] - Object of array of Links attached to the Real Asset
   * @param {object} [params.references={ AMaaS: Reference() }] - Object of References associated with the Real Asset. * The AMaaS Reference is auto-created and populated
   * @param {string} [params.createdBy] - ID of the user that created the Real Asset
   * @param {string} [params.updatedBy] - ID of the user that updated the Real Asset
   * @param {date} [params.createdTime] - Time that the Real Asset was created
   * @param {date} [params.updatedTime] - Time that the Real Asset was updated
   * @param {number} [params.version] - Version number
  */
  constructor({
    assetManagerId,
    assetId,
    assetClass='RealAsset',
    assetIssuerId,
    assetStatus='Active',
    countryId,
    venueId,
    currency,
    description='',
    displayName,
    rollPrice,
    clientId,
    comments,
    links,
    references,
    createdBy,
    updatedBy,
    createdTime,
    updatedTime,
    version
  }) {
    super({
      assetManagerId,
      assetId,
      assetClass,
      fungible: false,
      assetIssuerId,
      assetStatus,
      countryId,
      venueId,
      currency,
      description,
      displayName,
      rollPrice,
      clientId,
      comments,
      links,
      references,
      createdBy,
      updatedBy,
      createdTime,
      updatedTime,
      version
    })
  }
}

export default RealAsset
<commit_msg>Add ownerships to RealAsset class<commit_after>import Asset from '../../Asset/asset'

/**
 * Class representing a Real Asset
 * @memberof module:assets
 * @extends module:assets.Asset
 */
class RealAsset extends Asset {
  /**
   * Construct a new Real Asset instance
   * @param {object} params - RealAsset creation options
   * @param {number} params.assetManagerId - ID of Asset's Asset Manager __(required)__
   * @param {number} params.assetId - ID of the Asset __(required)__
   * @param {string} [params.assetClass=RealAsset] - Class of the Asset (a subclass of RealAsset may define its own assetClass)
   * @param {string} [params.assetType] - Type of the Asset. Auto-set based on the class or subclass constructor
   * @param {string} [params.assetTypeDisplay] - Auto-set to the spaced class name (e.g. `Listed Derivative` for `ListedDerivative()`)
   * @param {boolean} [params.fungible=false] - Auto-set to `false` __(read-only)__
   * @param {string} [params.assetIssuerId] - ID of the Real Asset's issuer
   * @param {string} [params.assetStatus=Active] - Status of the Real Asset
   * @param {string} [params.countryId] - ID of Real Asset's country
   * @param {string} [params.venueId] - ID of Real Asset's venue if applicable
   * @param {string} [params.currency] - Real Asset currency (e.g. USD, SGD)
   * @param {string} [params.description] - Description of the Real Asset
   * @param {string} [params.displayName] - Display name of the Asset
   * @param {boolean} [params.rollPrice=true] - Whether to roll the price for the Asset
   * @param {string} [params.clientId] - ID of the associated client
   * @param {object} [params.comments] - Object of Comments attached to the Real Asset
   * @param {object} [params.links] - Object of array of Links attached to the Real Asset
   * @param {object} [params.references={ AMaaS: Reference() }] - Object of References associated with the Real Asset. * The AMaaS Reference is auto-created and populated
   * @param {string} [params.createdBy] - ID of the user that created the Real Asset
   * @param {string} [params.updatedBy] - ID of the user that updated the Real Asset
   * @param {date} [params.createdTime] - Time that the Real Asset was created
   * @param {date} [params.updatedTime] - Time that the Real Asset was updated
   * @param {number} [params.version] - Version number
   * @param {object} [params.ownerships]
  */
  constructor({
    assetManagerId,
    assetId,
    assetClass='RealAsset',
    assetIssuerId,
    assetStatus='Active',
    countryId,
    venueId,
    currency,
    description='',
    displayName,
    rollPrice,
    clientId,
    comments,
    links,
    references,
    createdBy,
    updatedBy,
    createdTime,
    updatedTime,
    version,
    ownerships
  }) {
    super({
      assetManagerId,
      assetId,
      assetClass,
      fungible: false,
      assetIssuerId,
      assetStatus,
      countryId,
      venueId,
      currency,
      description,
      displayName,
      rollPrice,
      clientId,
      comments,
      links,
      references,
      createdBy,
      updatedBy,
      createdTime,
      updatedTime,
      version
    })
  }
}

export default RealAsset
<|endoftext|>


<commit_before>"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var bodyParser = require("body-parser");
var express = require("express");
var morgan = require("morgan");
var mongoose = require("mongoose");
var path = require("path");
var session = require("express-session");
var passport = require("passport");
var connectMongo = require("connect-mongo");
var config_1 = require("./config/config");
var passport_1 = require("./config/passport");
var routes_1 = require("./routes");
var app = express();
exports.app = app;
var MongoStore = connectMongo(session);
app.set('port', (process.env.PORT || 3000));
app.use('/', express.static(path.join(__dirname, '../public')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(morgan('dev'));
mongoose.connect(config_1.default.db);
var db = mongoose.connection;
mongoose.Promise = global.Promise;
app.use(session({
    secret: config_1.default.sessionSecret,
    resave: true,
    saveUninitialized: true,
    store: new MongoStore({ mongooseConnection: db })
}));
passport_1.default();
app.use(passport.initialize());
app.use(passport.session());
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function () {
    console.log('Connected to MongoDB');
    routes_1.default(app);
    //app.get('/*', function (req, res) {
    app.get('/*', function (req, res) {
     //  res.sendFile(path.join(__dirname, '../public/index.html'));
     res.sendFile(path.join(__dirname, '../public/index.html'));

    });
    if (!module.parent) {
        app.listen(app.get('port'), function () {
            console.log('Server listening on port ' + app.get('port'));
        });
    }
});
//# sourceMappingURL=app.js.map<commit_msg>Going to Heroku testing<commit_after>"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var bodyParser = require("body-parser");
var express = require("express");
var morgan = require("morgan");
var mongoose = require("mongoose");
var path = require("path");
var session = require("express-session");
var passport = require("passport");
var connectMongo = require("connect-mongo");
var config_1 = require("./config/config");
var passport_1 = require("./config/passport");
var routes_1 = require("./routes");
var app = express();
exports.app = app;
var MongoStore = connectMongo(session);
app.set('port', (process.env.PORT || 3000));
app.use('/static', express.static(path.join(__dirname, '../public')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(morgan('dev'));
mongoose.connect(config_1.default.db);
var db = mongoose.connection;
mongoose.Promise = global.Promise;
app.use(session({
    secret: config_1.default.sessionSecret,
    resave: true,
    saveUninitialized: true,
    store: new MongoStore({ mongooseConnection: db })
}));
passport_1.default();
app.use(passport.initialize());
app.use(passport.session());
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function () {
    console.log('Connected to MongoDB');
    routes_1.default(app);
    //app.get('/*', function (req, res) {
    app.get('/*', function (req, res) {
     //  res.sendFile(path.join(__dirname, '../public/index.html'));
     res.sendFile(path.join(__dirname, '../public/index.html'));

    });
    if (!module.parent) {
        app.listen(app.get('port'), function () {
            console.log('Server listening on port ' + app.get('port'));
        });
    }
});
//# sourceMappingURL=app.js.map<|endoftext|>


<commit_before>var fs = require('fs');
var Spawn = require('node-spawn');
var _ = require('underscore');
var socket = require('socket.io-client')('http://fruitiex.org:9191');
var one = require('onecolor');

// maximum values observed in a while
var bands = {
    bass: {
        minBin: 4,
        maxBin: 8,
        value: 0,
        peak: 0,
        peakBin: 0
    },
    snare: {
        minBin: 9,
        maxBin: 16,
        value: 0,
        peak: 0,
        peakBin: 0
    },
    hihat: {
        minBin: 51,
        maxBin: 1800,
        value: 0,
        peak: 0,
        peakBin: 0
    }
}
var ival = 0;
//var minVal = 100;
var dPeak = 0.995;

var audioBuffer = new Buffer(0);
var windowSize = 4096;
var avgFactor = 0.85;
var binChangeAvg = 0.95;
var fft = require('kissfft').fft;

var hue = 0;
var samplingRate = 44100;
var minF = 0;
var maxF = 22050;
var emitBand = 0;
var avg = Array.apply(null, new Array(windowSize / 2)).map(Number.prototype.valueOf, 0);

var findPeakBins = function(output) {
    _.each(bands, function(band) {
        var peak = 0;
        for (var i = band.minBin; i < band.maxBin; i++) {
            if (output[i] - avg[i] > peak) {
                peak = output[i] - avg[i];
                //band.peakBin = band.peakBin * binChangeAvg + (1 - binChangeAvg) * i;
                band.peakBin = i;
            }
        }
    });
};

var avgResult = function(output) {
    var retval = [];
    _.each(output, function(band, index) {
        if (band) {
            avg[index] = avg[index] * avgFactor + band * (1 - avgFactor);
            retval[index] = avg[index];
        }
    });

    return output;
};

var printSpectrum = function(output) {
    hue += 0.0005;

    // adjust intensity by approx. kick drum frequencies
    //var intensity = getAmplitude(100, 6);
    var intensity = output[Math.round(bands.bass.peakBin)];
    bands.bass.peak = Math.max(1, Math.max(bands.bass.peak * dPeak, intensity));
    bands.bass.value = bands.bass.value * avgFactor + (1 - avgFactor) * (Math.exp(Math.pow(intensity / bands.bass.peak, 4)) - 1) / (Math.E - 1);
    bands.bass.value = Math.max(bands.bass.value, (Math.exp(Math.pow(intensity / bands.bass.peak, 4)) - 1) / (Math.E - 1));
    //bands.bass.value = (Math.exp(Math.pow(intensity / bands.bass.peak, 2)) - 1) / (Math.E - 1);
    //minVal = Math.min(minVal * (2 - dVal), intensity);
    //console.log(minVal);
    //
    intensity = output[Math.round(bands.snare.peakBin)];
    bands.snare.peak = Math.max(1, Math.max(bands.snare.peak * dPeak, intensity));
    bands.snare.value = bands.snare.value * avgFactor + (1 - avgFactor) * (Math.exp(Math.pow(intensity / bands.snare.peak, 4)) - 1) / (Math.E - 1);
    bands.snare.value = Math.max(bands.snare.value, (Math.exp(Math.pow(intensity / bands.snare.peak, 4)) - 1) / (Math.E - 1));

    intensity = output[Math.round(bands.hihat.peakBin)];
    bands.hihat.peak = Math.max(0.01, Math.max(bands.hihat.peak * dPeak, intensity));
    bands.hihat.value = bands.hihat.value * avgFactor + (1 - avgFactor) * (Math.exp(Math.pow(intensity / bands.hihat.peak, 4)) - 1) / (Math.E - 1);
    //bands.hihat.value = Math.max(bands.hihat.value, (Math.exp(Math.pow(intensity / bands.hihat.peak, 4)) - 1) / (Math.E - 1));

    //bands.bass.value = Math.max(bands.bass.value * avgFactor, bands.bass.value * 100 - 25);
    var bass = bands.bass.value
        console.log(Math.floor(bands.bass.value * 100) + '\t'
                + Math.floor(bands.snare.value * 100) + '\t'
                + Math.floor(bands.hihat.value * 100) + '\t'
                + Math.round(bands.bass.peakBin) + '\t'
                + Math.round(bands.snare.peakBin) + '\t'
                + Math.round(bands.hihat.peakBin));
    //socket.emit('color', 'hsl(' + Math.round(hue) + ', 100%, ' + Math.round(((intensity - minVal) / (imaxVal - minVal)) * 50) + '%)');
    //var colorBass = onecolor.color('hsl(' + Math.round(hue)
    var vuColor = one('#000')
        .red(bands.bass.value)
        .blue(bands.snare.value)
        //.green(bands.hihat.value)
        .hue(hue
            //+ (bands.bass.peakBin + bands.snare.peakBin + bands.hihat.peakBin) / 10000
            , true);
    socket.emit('color', vuColor.css());
};

var runFFT = function(newData) {
    audioBuffer = Buffer.concat([audioBuffer, newData]);

    if (audioBuffer.length < windowSize) {
        // too little data, try again next time
        console.log('too little data');
        return;
    }

    audioBuffer = audioBuffer.slice(audioBuffer.length - windowSize);

    var samples = [];
    for (var i = 0; i < windowSize; i+= 2) {
        var sample = audioBuffer.readInt16LE(i, true) / 32767.0;
        samples.push(sample);
    }

    var complex = [];
    _.each(samples, function(val) {
        complex.push(val, 0);
    });
    var input = new Float32Array(complex);
    var output = new Float32Array(complex.length);
    fft(input, output, function(err, outputObj) {
        var output = [];
        for (var i = 0; i < (windowSize / 2); i++) {
            var real = outputObj[(i * 2)];
            var imag = outputObj[(i * 2) + 1];
            output[i] = Math.sqrt((real * real) + (imag * imag));
        }
        /*
        output = _.map(output, function(band) {
        return 20 * Math.log10(band);
        });
        */

        var newAvg = avgResult(output);
        findPeakBins(newAvg, output);
        printSpectrum(newAvg);
    });
};

var spawn = Spawn({
    cmd: 'pacat',
    args: ['--record', '--raw', '--channels=1', '--format=s16le'],
    onStdout: runFFT
});

spawn.start();
<commit_msg>don't let a band's peak go under half of global peak<commit_after>var fs = require('fs');
var Spawn = require('node-spawn');
var _ = require('underscore');
var socket = require('socket.io-client')('http://fruitiex.org:9191');
var one = require('onecolor');

// maximum values observed in a while
var bands = {
    bass: {
        minBin: 4,
        maxBin: 8,
        value: 0,
        peak: 0,
        peakBin: 0
    },
    snare: {
        minBin: 9,
        maxBin: 16,
        value: 0,
        peak: 0,
        peakBin: 0
    },
    hihat: {
        minBin: 51,
        maxBin: 1800,
        value: 0,
        peak: 0,
        peakBin: 0
    }
}
var dPeak = 0.9975;

var audioBuffer = new Buffer(0);
var windowSize = 4096;
var avgFactor = 0.85;
var fft = require('kissfft').fft;

var hue = 0;
var avg = Array.apply(null, new Array(windowSize / 2)).map(Number.prototype.valueOf, 0);
var globalPeak = 0;

var findPeakBins = function(output) {
    globalPeak = globalPeak * dPeak;
    _.each(bands, function(band) {
        var peak = 0;
        for (var i = band.minBin; i < band.maxBin; i++) {
            if (output[i] - avg[i] > peak) {
                peak = output[i] - avg[i];
                //var binChangeAvg = 0.95;
                //band.peakBin = band.peakBin * binChangeAvg + (1 - binChangeAvg) * i;
                band.peakBin = i;
            }
            if (output[i] > globalPeak) {
                globalPeak = output[i];
            }
        }
    });
};

var avgResult = function(output) {
    var retval = [];
    _.each(output, function(band, index) {
        if (band) {
            avg[index] = avg[index] * avgFactor + band * (1 - avgFactor);
            retval[index] = avg[index];
        }
    });

    return output;
};

var printSpectrum = function(output) {
    hue += 0.0005;

    // adjust intensity by approx. kick drum frequencies
    //var intensity = getAmplitude(100, 6);
    console.log(globalPeak);
    var intensity = output[Math.round(bands.bass.peakBin)];
    bands.bass.peak = Math.max(1, Math.max(bands.bass.peak * dPeak, intensity));
    // don't let peak fall too low if there's still energy in other bands
    bands.bass.peak = Math.max(globalPeak / 2, bands.bass.peak);
    bands.bass.value = bands.bass.value * avgFactor + (1 - avgFactor) * (Math.exp(Math.pow(intensity / bands.bass.peak, 4)) - 1) / (Math.E - 1);
    bands.bass.value = Math.max(bands.bass.value, (Math.exp(Math.pow(intensity / bands.bass.peak, 4)) - 1) / (Math.E - 1));
    //bands.bass.value = (Math.exp(Math.pow(intensity / bands.bass.peak, 2)) - 1) / (Math.E - 1);
    //minVal = Math.min(minVal * (2 - dVal), intensity);
    //console.log(minVal);
    //
    intensity = output[Math.round(bands.snare.peakBin)];
    bands.snare.peak = Math.max(1, Math.max(bands.snare.peak * dPeak, intensity));
    // don't let peak fall too low if there's still energy in other bands
    bands.snare.peak = Math.max(globalPeak / 2, bands.snare.peak);
    bands.snare.value = bands.snare.value * avgFactor + (1 - avgFactor) * (Math.exp(Math.pow(intensity / bands.snare.peak, 4)) - 1) / (Math.E - 1);
    bands.snare.value = Math.max(bands.snare.value, (Math.exp(Math.pow(intensity / bands.snare.peak, 4)) - 1) / (Math.E - 1));

    intensity = output[Math.round(bands.hihat.peakBin)];
    bands.hihat.peak = Math.max(0.01, Math.max(bands.hihat.peak * dPeak, intensity));
    // don't let peak fall too low if there's still energy in other bands
    bands.hihat.peak = Math.max(globalPeak / 2, bands.hihat.peak);
    bands.hihat.value = bands.hihat.value * avgFactor + (1 - avgFactor) * (Math.exp(Math.pow(intensity / bands.hihat.peak, 4)) - 1) / (Math.E - 1);
    //bands.hihat.value = Math.max(bands.hihat.value, (Math.exp(Math.pow(intensity / globalPeak, 4)) - 1) / (Math.E - 1));

    //bands.bass.value = Math.max(bands.bass.value * avgFactor, bands.bass.value * 100 - 25);
    var bass = bands.bass.value
        console.log(Math.floor(bands.bass.value * 100) + '\t'
                + Math.floor(bands.snare.value * 100) + '\t'
                + Math.floor(bands.hihat.value * 100) + '\t'
                + Math.round(bands.bass.peakBin) + '\t'
                + Math.round(bands.snare.peakBin) + '\t'
                + Math.round(bands.hihat.peakBin));
    //socket.emit('color', 'hsl(' + Math.round(hue) + ', 100%, ' + Math.round(((intensity - minVal) / (imaxVal - minVal)) * 50) + '%)');
    //var colorBass = onecolor.color('hsl(' + Math.round(hue)
    var vuColor = one('#000')
        .red(bands.bass.value)
        .blue(bands.snare.value)
        //.green(bands.hihat.value)
        .hue(hue
            //+ (bands.bass.peakBin + bands.snare.peakBin + bands.hihat.peakBin) / 10000
            , true);
    socket.emit('color', vuColor.css());
};

var runFFT = function(newData) {
    audioBuffer = Buffer.concat([audioBuffer, newData]);

    if (audioBuffer.length < windowSize) {
        // too little data, try again next time
        console.log('too little data');
        return;
    }

    audioBuffer = audioBuffer.slice(audioBuffer.length - windowSize);

    var samples = [];
    for (var i = 0; i < windowSize; i+= 2) {
        var sample = audioBuffer.readInt16LE(i, true) / 32767.0;
        samples.push(sample);
    }

    var complex = [];
    _.each(samples, function(val) {
        complex.push(val, 0);
    });
    var input = new Float32Array(complex);
    var output = new Float32Array(complex.length);
    fft(input, output, function(err, outputObj) {
        var output = [];
        for (var i = 0; i < (windowSize / 2); i++) {
            var real = outputObj[(i * 2)];
            var imag = outputObj[(i * 2) + 1];
            output[i] = Math.sqrt((real * real) + (imag * imag));
        }
        /*
        output = _.map(output, function(band) {
        return 20 * Math.log10(band);
        });
        */

        var newAvg = avgResult(output);
        findPeakBins(newAvg, output);
        printSpectrum(newAvg);
    });
};

var spawn = Spawn({
    cmd: 'pacat',
    args: ['--record', '--raw', '--channels=1', '--format=s16le'],
    onStdout: runFFT
});

spawn.start();
<|endoftext|>


<commit_before>"use strict";
// smtp network server

var net         = require('./tls_socket');
var logger      = require('./logger');
var config      = require('./config');
var conn        = require('./connection');
var out         = require('./outbound');
var plugins     = require('./plugins');
var constants   = require('./constants');
var os          = require('os');

var cluster;
try { cluster = require('cluster') } // cluster can be installed with npm
catch (err) {
    logger.logdebug("no cluster available, running single-process");
}

// Need these here so we can run hooks
for (var key in logger) {
    if (key.match(/^log\w/)) {
        exports[key] = (function (key) {
            return function () {
                var args = ["[server] "];
                for (var i=0, l=arguments.length; i<l; i++) {
                    args.push(arguments[i]);
                }
                logger[key].apply(logger, args);
            }
        })(key);
    }
}

var Server = exports;

var defaults = {
    port: 25,
    listen_host: '0.0.0.0',
    inactivity_timeout: 600
};

function apply_defaults(obj) {
    var key;
    for (key in defaults) {
        obj[key] = obj[key] || defaults[key];
    }
}

Server.createServer = function (params) {
    var config_data = config.get('smtp.ini');
    var param_key;
    for (param_key in params) {
        if (typeof params[param_key] !== 'function') {
            config_data.main[param_key] = params[param_key];
        }
    }

    // config_data defaults
    apply_defaults(config_data.main);

    plugins.load_plugins();

    var server = net.createServer(function (client) {
        client.setTimeout((config_data.main.inactivity_timeout || 300) * 1000);
        conn.createConnection(client, server);
    });
    server.notes = {};
    if (cluster && config_data.main.nodes) {

        var c = cluster(server);
        var cluster_modules = config.get('cluster_modules', 'list');

        if (config_data.main.nodes !== 'cpus') {
            c.set('workers', config_data.main.nodes);
        }
        if (config_data.main.user) {
            c.set('user', config_data.main.user);
        }

        for (var i=0,l=cluster_modules.length; i < l; i++) {
            var matches = /^(\w+)\s*(?::\s*(.*))?$/.exec(cluster_modules[i]);
            if (!matches) {
                Server.logerror("cluster_modules in invalid format: " + cluster_modules[i]);
                continue;
            }
            var module = matches[1];
            var params = matches[2];
            if (params) {
                c.use(cluster[module](JSON.parse(params)));
            }
            else {
                c.use(cluster[module]());
            }
        }

        c.set('host', config_data.main.listen_host);
        c.listen(parseInt(config_data.main.port));
        c.on('listening', listening);
        Server.cluster = c;
        c.on('start', function () {
            plugins.run_hooks('init_master', Server);
        });
        if (c.isWorker) {
            plugins.run_hooks('init_child', Server);
        }
    }
    else {
        server.listen(config_data.main.port, config_data.main.listen_host, listening);

        plugins.run_hooks('init_master', Server);
    }
};

Server.init_master_respond = function (retval, msg) {
    Server.ready = 1;
    switch(retval) {
        case constants.ok:
        case constants.cont:
                break;
        default:
                Server.logerror("init_master stopped startup: " + msg);
                process.exit();
    }
}

Server.init_child_respond = function (retval, msg) {
    switch(retval) {
        case constants.ok:
        case constants.cont:
                break;
        default:
                Server.logerror("init_child returned with error. Killing Haraka. " + msg);
                process.kill(process.env.CLUSTER_MASTER_PID);
    }
}

function listening () {
    var config_data = config.get('smtp.ini');
    logger.lognotice("Listening on port " + config_data.main.port);
    out.load_queue();
    Server.ready = 1;

    if (config_data.main.user) {
        // drop privileges
        Server.lognotice('Switching from current uid: ' + process.getuid());
        process.setuid(config_data.main.user);
        Server.lognotice('New uid: ' + process.getuid());
    }
}
<commit_msg>Only run init_master in the master<commit_after>"use strict";
// smtp network server

var net         = require('./tls_socket');
var logger      = require('./logger');
var config      = require('./config');
var conn        = require('./connection');
var out         = require('./outbound');
var plugins     = require('./plugins');
var constants   = require('./constants');
var os          = require('os');

var cluster;
try { cluster = require('cluster') } // cluster can be installed with npm
catch (err) {
    logger.logdebug("no cluster available, running single-process");
}

// Need these here so we can run hooks
for (var key in logger) {
    if (key.match(/^log\w/)) {
        exports[key] = (function (key) {
            return function () {
                var args = ["[server] "];
                for (var i=0, l=arguments.length; i<l; i++) {
                    args.push(arguments[i]);
                }
                logger[key].apply(logger, args);
            }
        })(key);
    }
}

var Server = exports;

var defaults = {
    port: 25,
    listen_host: '0.0.0.0',
    inactivity_timeout: 600
};

function apply_defaults(obj) {
    var key;
    for (key in defaults) {
        obj[key] = obj[key] || defaults[key];
    }
}

Server.createServer = function (params) {
    var config_data = config.get('smtp.ini');
    var param_key;
    for (param_key in params) {
        if (typeof params[param_key] !== 'function') {
            config_data.main[param_key] = params[param_key];
        }
    }

    // config_data defaults
    apply_defaults(config_data.main);

    plugins.load_plugins();

    var server = net.createServer(function (client) {
        client.setTimeout((config_data.main.inactivity_timeout || 300) * 1000);
        conn.createConnection(client, server);
    });
    server.notes = {};
    if (cluster && config_data.main.nodes) {

        var c = cluster(server);
        var cluster_modules = config.get('cluster_modules', 'list');

        if (config_data.main.nodes !== 'cpus') {
            c.set('workers', config_data.main.nodes);
        }
        if (config_data.main.user) {
            c.set('user', config_data.main.user);
        }

        for (var i=0,l=cluster_modules.length; i < l; i++) {
            var matches = /^(\w+)\s*(?::\s*(.*))?$/.exec(cluster_modules[i]);
            if (!matches) {
                Server.logerror("cluster_modules in invalid format: " + cluster_modules[i]);
                continue;
            }
            var module = matches[1];
            var params = matches[2];
            if (params) {
                c.use(cluster[module](JSON.parse(params)));
            }
            else {
                c.use(cluster[module]());
            }
        }

        c.set('host', config_data.main.listen_host);
        c.listen(parseInt(config_data.main.port));
        c.on('listening', listening);
        Server.cluster = c;
        if (c.isMaster) {
            plugins.run_hooks('init_master', Server);
        }
        if (c.isWorker) {
            plugins.run_hooks('init_child', Server);
        }
    }
    else {
        server.listen(config_data.main.port, config_data.main.listen_host, listening);

        plugins.run_hooks('init_master', Server);
    }
};

Server.init_master_respond = function (retval, msg) {
    Server.ready = 1;
    switch(retval) {
        case constants.ok:
        case constants.cont:
                break;
        default:
                Server.logerror("init_master stopped startup: " + msg);
                process.exit();
    }
}

Server.init_child_respond = function (retval, msg) {
    switch(retval) {
        case constants.ok:
        case constants.cont:
                break;
        default:
                Server.logerror("init_child returned with error. Killing Haraka. " + msg);
                process.kill(process.env.CLUSTER_MASTER_PID);
    }
}

function listening () {
    var config_data = config.get('smtp.ini');
    logger.lognotice("Listening on port " + config_data.main.port);
    out.load_queue();
    Server.ready = 1;

    if (config_data.main.user) {
        // drop privileges
        Server.lognotice('Switching from current uid: ' + process.getuid());
        process.setuid(config_data.main.user);
        Server.lognotice('New uid: ' + process.getuid());
    }
}
<|endoftext|>