<commit_before>var std = require('std'),
	events = require('events'),
	Connection = require('./Connection'),
	requestTypes = require('./requestTypes'),
	error = require('./error')

module.exports = std.Class(Connection, function(supr) {
	var MS_TO_S = 1000

	var states = {
		HEADER_LEN_0: 0, HEADER_LEN_1: 1, HEADER_LEN_2: 2, HEADER_LEN_3: 3,
		HEADER_EC_0: 4, HEADER_EC_1: 5,
		RESPONSE_MSG_0: 6, RESPONSE_MSG_1: 7, RESPONSE_MSG_2: 8, RESPONSE_MSG_3: 9,
		RESPONSE_MAGIC: 10,
		RESPONSE_CHKSUM_0: 11, RESPONSE_CHKSUM_1: 12, RESPONSE_CHKSUM_2: 13, RESPONSE_CHKSUM_3: 14,
		RESPONSE_MSG: 15,

		OFFSET_LEN_0: 16, OFFSET_LEN_1: 17, OFFSET_LEN_2: 18, OFFSET_LEN_3: 19,
		OFFSET_OFFSETS_0: 20, OFFSET_OFFSETS_1: 21, OFFSET_OFFSETS_2: 22, OFFSET_OFFSETS_3: 23,
		OFFSET_OFFSETS_4: 24, OFFSET_OFFSETS_5: 25, OFFSET_OFFSETS_6: 26, OFFSET_OFFSETS_7: 27,
	}

	var defaults = {
		maxSize: 1048576 //1MB
	}

	var fetch_defaults = {
		type: requestTypes.FETCH,
		next: states.RESPONSE_MSG_0,
		last: 'lastmessage',
		encode: function (t) {
			return this._encodeFetchRequest(t)
		},

		partition: 0,
		offset: 0,
	}

	var offset_defaults = {
		type: requestTypes.OFFSETS,
		next: states.OFFSET_LEN_0,
		last: 'lastoffset',
		encode: function (t) {
			return this._encodeOffsetsRequest(t)
		},

		partition: 0,
		offsets: 1,
	}

	this._init = function(opts) {
		supr(this, '_init', arguments)
		opts = std.extend(opts, defaults)
		this._buffer = new Buffer(opts.maxSize)
		this._toRead = 0
		this._requests = []
		this._connected = false
		this._state = states.HEADER_LEN_0
		fetch_defaults.encode = fetch_defaults.encode.bind(this)
		offset_defaults.encode = offset_defaults.encode.bind(this)
	}

	this.connect = function() {
		supr(this, 'connect', arguments)
		this._connection.on('connect', std.bind(this, '_onConnect'))
		return this
	}

	this.fetchTopic = function(args) {
		var request = std.extend(args.name == undefined ? { name: args } : args, fetch_defaults)
		this._pushRequest(request)
		return this
	}

	this.fetchOffsets = function(args) {
		var request = std.extend(args.name == undefined ? { name: args } : args, offset_defaults)
		this._pushRequest(request)
		return this
	}

	this._onConnect = function() {
		this._connected = true
		this._connection.on('data', std.bind(this, '_onData'))
		for (i in this._requests) this._writeRequest(this._requests[i])
	}

	this._pushRequest = function(request) {
		this._requests.push(request)
		this._writeRequest(request)
	}

	this._writeRequest = function(request) {
		if (this._connected) this._connection.write(request.encode(request))
	}

	this._encodeFetchRequest = function(t) {
		var request = std.pack('n', requestTypes.FETCH)
			+ std.pack('n', t.name.length) + t.name
			+ std.pack('N', t.partition)
			+ std.pack('N2', t.offset & 0xffff0000 >> 32, t.offset & 0x0000ffff)
			+ std.pack('N', this._buffer.length)

		var requestSize = 2 + 2 + t.name.length + 4 + 8 + 4

		return this._bufferPacket(std.pack('N', requestSize) + request)
	}

	this._encodeOffsetsRequest = function(t) {
		var time = new Date().getTime() / MS_TO_S
		var request = std.pack('n', requestTypes.OFFSETS)
			+ std.pack('n', t.name.length) + t.name
			+ std.pack('N', t.partition)
			+ std.pack('N2', time & 0xffff0000 >> 32, time & 0x0000ffff)
			+ std.pack('N', t.offsets)

		var requestSize = 2 + 2 + t.name.length + 4 + 8 + 4
		return this._bufferPacket(std.pack('N', requestSize) + request)
	}

	this._onData = function(buf) {
/**
 * the following tests buffer sizes smaller than what normally
 * comes off the socket.  It breaks the normal boundaries and helps
 * ensure the parsing code is robust
 *
		var buffer = new Buffer(buf.length - 2)
		buf.copy(buffer, 0, 0, buf.length - 2)
		this._processData(buffer)

		buffer = new Buffer(2)
		buf.copy(buffer, 0, buf.length - 2, buf.length)
		this._processData(buffer)
	}

	this._processData = function (buf) {
*/
		var index = 0
		while (index != buf.length) {
			var bytes = 1
			var next = this._state + 1
			delete this._callback
			switch (this._state) {
				case states.HEADER_LEN_0:
					this._totalLen = buf[index] << 24
				    break

				case states.HEADER_LEN_1:
				    this._totalLen += buf[index] << 16
				    break

				case states.HEADER_LEN_2:
				    this._totalLen += buf[index] << 8
				    break

				case states.HEADER_LEN_3:
				    this._totalLen += buf[index]
				    break

				case states.HEADER_EC_0:
					this._totalLen--
				    break

				case states.HEADER_EC_1:
					this._toRead = this._totalLen
					next = this._requests[0].next
					this._totalLen--
				    break

				case states.RESPONSE_MSG_0:
				    this._msgLen = buf[index] << 24
					this._requests[0].offset++
				    this._payloadLen = 0
				    break

				case states.RESPONSE_MSG_1:
			    	this._msgLen += buf[index] << 16
					this._requests[0].offset++
				    break

				case states.RESPONSE_MSG_2:
			    	this._msgLen += buf[index] << 8
					this._requests[0].offset++
				    break

				case states.RESPONSE_MSG_3:
			    	this._msgLen += buf[index]
					this._requests[0].offset++
				    break

				case states.RESPONSE_MAGIC:
			    	this._magic = buf[index]
					this._requests[0].offset++
			        this._msgLen--
				    break

				case states.RESPONSE_CHKSUM_0:
			    	this._chksum = buf[index] << 24
					this._requests[0].offset++
		        	this._msgLen--
				    break

				case states.RESPONSE_CHKSUM_1:
				    this._chksum += buf[index] << 16
					this._requests[0].offset++
					this._msgLen--
				    break

				case states.RESPONSE_CHKSUM_2:
		        	this._chksum += buf[index] << 8
					this._requests[0].offset++
				    this._msgLen--
				    break

				case states.RESPONSE_CHKSUM_3:
		        	this._chksum += buf[index]
					this._requests[0].offset++
				    this._msgLen--
				    break

				case states.RESPONSE_MSG:
					next = states.RESPONSE_MSG

					// try to avoid a memcpy if possible
					var payload = null
					if (this._payloadLen == 0 && buf.length - index >= this._msgLen) {
						payload = buf.toString('utf8', index, index + this._msgLen)
						bytes = this._msgLen
					} else {
						var end = index + this._msgLen - this._payloadLen
						if (end > buf.length) end = buf.length
						buf.copy(this._buffer, this._payloadLen, index, end)
						this._payloadLen += end - index
						bytes = end - index
						if (this._payloadLen == this._msgLen) {
							payload = this._buffer.toString('utf8', 0, this._payloadLen)
						}
					}
					if (payload != null) {
						this._requests[0].offset += payload.length
						next = states.RESPONSE_MSG_0
						this.emit('message', this._requests[0].name, payload, this._requests[0].offset)
					}
					break

				case states.OFFSET_LEN_0:
					this._msgLen = buf[index] << 24
					break

				case states.OFFSET_LEN_1:
					this._msgLen += buf[index] << 16
					break

				case states.OFFSET_LEN_2:
					this._msgLen += buf[index] << 8
					break

				case states.OFFSET_LEN_3:
					this._msgLen += buf[index]
					break

				case states.OFFSET_OFFSETS_0:
					this._requests[0].offset = buf[index] << 56
					break

				case states.OFFSET_OFFSETS_1:
					this._requests[0].offset += buf[index] << 48
					break

				case states.OFFSET_OFFSETS_2:
					this._requests[0].offset += buf[index] << 40
					break

				case states.OFFSET_OFFSETS_3:
					this._requests[0].offset += buf[index] << 32
					break

				case states.OFFSET_OFFSETS_4:
					this._requests[0].offset += buf[index] << 24
					break

				case states.OFFSET_OFFSETS_5:
					this._requests[0].offset += buf[index] << 16
					break

				case states.OFFSET_OFFSETS_6:
					this._requests[0].offset += buf[index] << 8
					break

				case states.OFFSET_OFFSETS_7:
					this._requests[0].offset += buf[index]
					next = states.OFFSET_OFFSETS_0
					this.emit('offset', this._requests[0].name, this._requests[0].offset)
			}
			index += bytes
			this._toRead -= bytes
			this._state = next
			if (this._toRead == 0) this._last()
		}
	}

	this._last = function() {
		var last = this._requests.shift()
		this.emit(last.last, last.name, last.offset)
		this._state = states.HEADER_LEN_0

	}
})<commit_msg>add error handling<commit_after>var std = require('std'),
	events = require('events'),
	Connection = require('./Connection'),
	requestTypes = require('./requestTypes'),
	error = require('./error')

module.exports = std.Class(Connection, function(supr) {
	var MS_TO_S = 1000

	var states = {
		HEADER_LEN_0: 0, HEADER_LEN_1: 1, HEADER_LEN_2: 2, HEADER_LEN_3: 3,
		HEADER_EC_0: 4, HEADER_EC_1: 5,
		RESPONSE_MSG_0: 6, RESPONSE_MSG_1: 7, RESPONSE_MSG_2: 8, RESPONSE_MSG_3: 9,
		RESPONSE_MAGIC: 10,
		RESPONSE_CHKSUM_0: 11, RESPONSE_CHKSUM_1: 12, RESPONSE_CHKSUM_2: 13, RESPONSE_CHKSUM_3: 14,
		RESPONSE_MSG: 15,

		OFFSET_LEN_0: 16, OFFSET_LEN_1: 17, OFFSET_LEN_2: 18, OFFSET_LEN_3: 19,
		OFFSET_OFFSETS_0: 20, OFFSET_OFFSETS_1: 21, OFFSET_OFFSETS_2: 22, OFFSET_OFFSETS_3: 23,
		OFFSET_OFFSETS_4: 24, OFFSET_OFFSETS_5: 25, OFFSET_OFFSETS_6: 26, OFFSET_OFFSETS_7: 27,
	}

	var defaults = {
		maxSize: 1048576 //1MB
	}

	var fetch_defaults = {
		type: requestTypes.FETCH,
		next: states.RESPONSE_MSG_0,
		last: 'lastmessage',
		encode: function (t) {
			return this._encodeFetchRequest(t)
		},

		partition: 0,
		offset: 0,
	}

	var offset_defaults = {
		type: requestTypes.OFFSETS,
		next: states.OFFSET_LEN_0,
		last: 'lastoffset',
		encode: function (t) {
			return this._encodeOffsetsRequest(t)
		},

		partition: 0,
		offsets: 1,
	}

	this._init = function(opts) {
		supr(this, '_init', arguments)
		opts = std.extend(opts, defaults)
		this._buffer = new Buffer(opts.maxSize)
		this._toRead = 0
		this._requests = []
		this._connected = false
		this._state = states.HEADER_LEN_0
		fetch_defaults.encode = fetch_defaults.encode.bind(this)
		offset_defaults.encode = offset_defaults.encode.bind(this)
	}

	this.connect = function() {
		supr(this, 'connect', arguments)
		this._connection.on('connect', std.bind(this, '_onConnect'))
		return this
	}

	this.fetchTopic = function(args) {
		var request = std.extend(args.name == undefined ? { name: args } : args, fetch_defaults)
		this._pushRequest(request)
		return this
	}

	this.fetchOffsets = function(args) {
		var request = std.extend(args.name == undefined ? { name: args } : args, offset_defaults)
		this._pushRequest(request)
		return this
	}

	this._onConnect = function() {
		this._connected = true
		this._connection.on('data', std.bind(this, '_onData'))
		for (i in this._requests) this._writeRequest(this._requests[i])
	}

	this._pushRequest = function(request) {
		this._requests.push(request)
		this._writeRequest(request)
	}

	this._writeRequest = function(request) {
		if (this._connected) this._connection.write(request.encode(request))
	}

	this._encodeFetchRequest = function(t) {
		var request = std.pack('n', requestTypes.FETCH)
			+ std.pack('n', t.name.length) + t.name
			+ std.pack('N', t.partition)
			+ std.pack('N2', t.offset & 0xffff0000 >> 32, t.offset & 0x0000ffff)
			+ std.pack('N', this._buffer.length)

		var requestSize = 2 + 2 + t.name.length + 4 + 8 + 4

		return this._bufferPacket(std.pack('N', requestSize) + request)
	}

	this._encodeOffsetsRequest = function(t) {
		var time = new Date().getTime() / MS_TO_S
		var request = std.pack('n', requestTypes.OFFSETS)
			+ std.pack('n', t.name.length) + t.name
			+ std.pack('N', t.partition)
			+ std.pack('N2', time & 0xffff0000 >> 32, time & 0x0000ffff)
			+ std.pack('N', t.offsets)

		var requestSize = 2 + 2 + t.name.length + 4 + 8 + 4
		return this._bufferPacket(std.pack('N', requestSize) + request)
	}

	this._onData = function(buf) {
/**
 * the following tests buffer sizes smaller than what normally
 * comes off the socket.  It breaks the normal boundaries and helps
 * ensure the parsing code is robust
 *
		var buffer = new Buffer(buf.length - 2)
		buf.copy(buffer, 0, 0, buf.length - 2)
		this._processData(buffer)

		buffer = new Buffer(2)
		buf.copy(buffer, 0, buf.length - 2, buf.length)
		this._processData(buffer)
	}

	this._processData = function (buf) {
*/
		var index = 0
		while (index != buf.length) {
			var bytes = 1
			var next = this._state + 1
			delete this._callback
			switch (this._state) {
				case states.HEADER_LEN_0:
					this._totalLen = buf[index] << 24
				    break

				case states.HEADER_LEN_1:
				    this._totalLen += buf[index] << 16
				    break

				case states.HEADER_LEN_2:
				    this._totalLen += buf[index] << 8
				    break

				case states.HEADER_LEN_3:
				    this._totalLen += buf[index]
				    break

				case states.HEADER_EC_0:
					this._error = buf[index] << 8
					this._totalLen--
				    break

				case states.HEADER_EC_1:
					this._error += buf[index]
					this._toRead = this._totalLen
					next = this._requests[0].next
					this._totalLen--
					if (this._error != error.NoError) this.emit('error', this._error, error[this._error])
				    break

				case states.RESPONSE_MSG_0:
				    this._msgLen = buf[index] << 24
					this._requests[0].offset++
				    this._payloadLen = 0
				    break

				case states.RESPONSE_MSG_1:
			    	this._msgLen += buf[index] << 16
					this._requests[0].offset++
				    break

				case states.RESPONSE_MSG_2:
			    	this._msgLen += buf[index] << 8
					this._requests[0].offset++
				    break

				case states.RESPONSE_MSG_3:
			    	this._msgLen += buf[index]
					this._requests[0].offset++
				    break

				case states.RESPONSE_MAGIC:
			    	this._magic = buf[index]
					this._requests[0].offset++
			        this._msgLen--
				    break

				case states.RESPONSE_CHKSUM_0:
			    	this._chksum = buf[index] << 24
					this._requests[0].offset++
		        	this._msgLen--
				    break

				case states.RESPONSE_CHKSUM_1:
				    this._chksum += buf[index] << 16
					this._requests[0].offset++
					this._msgLen--
				    break

				case states.RESPONSE_CHKSUM_2:
		        	this._chksum += buf[index] << 8
					this._requests[0].offset++
				    this._msgLen--
				    break

				case states.RESPONSE_CHKSUM_3:
		        	this._chksum += buf[index]
					this._requests[0].offset++
				    this._msgLen--
				    break

				case states.RESPONSE_MSG:
					next = states.RESPONSE_MSG

					// try to avoid a memcpy if possible
					var payload = null
					if (this._payloadLen == 0 && buf.length - index >= this._msgLen) {
						payload = buf.toString('utf8', index, index + this._msgLen)
						bytes = this._msgLen
					} else {
						var end = index + this._msgLen - this._payloadLen
						if (end > buf.length) end = buf.length
						buf.copy(this._buffer, this._payloadLen, index, end)
						this._payloadLen += end - index
						bytes = end - index
						if (this._payloadLen == this._msgLen) {
							payload = this._buffer.toString('utf8', 0, this._payloadLen)
						}
					}
					if (payload != null) {
						this._requests[0].offset += payload.length
						next = states.RESPONSE_MSG_0
						this.emit('message', this._requests[0].name, payload, this._requests[0].offset)
					}
					break

				case states.OFFSET_LEN_0:
					this._msgLen = buf[index] << 24
					break

				case states.OFFSET_LEN_1:
					this._msgLen += buf[index] << 16
					break

				case states.OFFSET_LEN_2:
					this._msgLen += buf[index] << 8
					break

				case states.OFFSET_LEN_3:
					this._msgLen += buf[index]
					break

				case states.OFFSET_OFFSETS_0:
					this._requests[0].offset = buf[index] << 56
					break

				case states.OFFSET_OFFSETS_1:
					this._requests[0].offset += buf[index] << 48
					break

				case states.OFFSET_OFFSETS_2:
					this._requests[0].offset += buf[index] << 40
					break

				case states.OFFSET_OFFSETS_3:
					this._requests[0].offset += buf[index] << 32
					break

				case states.OFFSET_OFFSETS_4:
					this._requests[0].offset += buf[index] << 24
					break

				case states.OFFSET_OFFSETS_5:
					this._requests[0].offset += buf[index] << 16
					break

				case states.OFFSET_OFFSETS_6:
					this._requests[0].offset += buf[index] << 8
					break

				case states.OFFSET_OFFSETS_7:
					this._requests[0].offset += buf[index]
					next = states.OFFSET_OFFSETS_0
					this.emit('offset', this._requests[0].name, this._requests[0].offset)
			}
			index += bytes
			this._toRead -= bytes
			this._state = next
			if (this._toRead == 0) this._last()
		}
	}

	this._last = function() {
		var last = this._requests.shift()
		this.emit(last.last, last.name, last.offset)
		this._state = states.HEADER_LEN_0

	}
})<|endoftext|>


<commit_before>import { Widget } from 'phosphor/lib/ui/widget';
import { ABCWidgetFactory } from 'jupyterlab/lib/docregistry';

/**
 * The class name added to a DocWidget.
 */
const CLASS_NAME = 'jp-DocWidget{{cookiecutter.mime_short_name}}';

/**
 * A widget for rendering {{cookiecutter.extension_name}} files.
 */
export class DocWidget extends Widget {
  constructor(context) {
    super();
    this._context = context;
    this.addClass(CLASS_NAME);
    context.model.contentChanged.connect(() => {
      this.update();
    });
    context.pathChanged.connect(() => {
      this.update();
    });
  }

  /**
   * Dispose of the resources used by the widget.
   */
  dispose() {
    if (!this.isDisposed) {
      this._context = null;
      super.dispose();
    }
  }

  /**
   * A message handler invoked on an `'update-request'` message.
   */
  onUpdateRequest(msg) {
    this.title.label = this._context.path.split('/').pop();
    if (this.isAttached) {
      let content = this._context.model.toString();
      let json = content ? JSON.parse(content) : {};
      let text = document.createTextNode(JSON.stringify(json));
      this.node.appendChild(text);
    }
  }

  /**
   * A message handler invoked on an `'after-attach'` message.
   */
  onAfterAttach(msg) {
    this.update();
  }
}

/**
 * A widget factory for DocWidget.
 */
export class DocWidgetFactory extends ABCWidgetFactory {
  constructor(options) {
    super(options);
  }

  /**
   * Create a new widget given a context.
   */
  createNewWidget(context, kernel) {
    let widget = new DocWidget(context);
    this.widgetCreated.emit(widget);
    return widget;
  }
}
<commit_msg>Use ActivityMonitor to throttle users typing to update model<commit_after>import { Widget } from 'phosphor/lib/ui/widget';
import { ABCWidgetFactory } from 'jupyterlab/lib/docregistry';

/**
 * The class name added to a DocWidget.
 */
const CLASS_NAME = 'jp-DocWidget{{cookiecutter.mime_short_name}}';

/**
 * The timeout to wait for change activity to have ceased before rendering.
 */
const RENDER_TIMEOUT = 1000;

/**
 * A widget for rendering {{cookiecutter.extension_name}} files.
 */
export class DocWidget extends Widget {
  constructor(context) {
    super();
    this._context = context;
    this.addClass(CLASS_NAME);
    context.model.contentChanged.connect(() => {
      this.update();
    });
    context.pathChanged.connect(() => {
      this.update();
    });
    this._monitor = new ActivityMonitor({
      signal: context.model.contentChanged,
      timeout: RENDER_TIMEOUT
    });
    this._monitor.activityStopped.connect(this.update, this);
  }

  /**
   * Dispose of the resources used by the widget.
   */
  dispose() {
    if (!this.isDisposed) {
      this._context = null;
      this._monitor.dispose();
      super.dispose();
    }
  }

  /**
   * A message handler invoked on an `'update-request'` message.
   */
  onUpdateRequest(msg) {
    this.title.label = this._context.path.split('/').pop();
    if (this.isAttached) {
      let content = this._context.model.toString();
      let json = content ? JSON.parse(content) : {};
      let text = document.createTextNode(JSON.stringify(json));
      this.node.appendChild(text);
    }
  }

  /**
   * A message handler invoked on an `'after-attach'` message.
   */
  onAfterAttach(msg) {
    this.update();
  }
}

/**
 * A widget factory for DocWidget.
 */
export class DocWidgetFactory extends ABCWidgetFactory {
  constructor(options) {
    super(options);
  }

  /**
   * Create a new widget given a context.
   */
  createNewWidget(context, kernel) {
    let widget = new DocWidget(context);
    this.widgetCreated.emit(widget);
    return widget;
  }
}
<|endoftext|>


<commit_before>
/**
  CoreJS

  Configures the corejs, and is in charge of assembling all the applications together.
  Provides the master server that handles and routes all of the virtual host requests.

  Available globally as corejs.
 */

require('./extensions.js');

var _ = require('underscore'),
    events = require('events'),
    net = require('net'),
    inflect = require('./support/inflect.js'),
    child_process = require('child_process'),
    cluster = require('cluster'),
    os = require('os'),
    http = require('http'),
    util = require('util'),
    pathModule = require('path'),
    EventEmitter = events.EventEmitter;

function CoreJS(noserver) {

  var self = this;

  // Initialize `corejs` global
  global.corejs = this;

  // Inherit from constructor
  _.extend(this, this.constructor);

  // Cluster configuration
  this.clusterConfig = {
    listenPort: null,
    multiProcess: 0,
    masterProcess: 'node [master]',
    singleProcess: 'node [single process]',
    workerProcess: 'node worker'
  };

  this.extend = _.extend;

  // Internals
  this.drivers = {};
  this.engines = {};
  this.storages = {};
  this.lib = {};

  // Regular expressions
  this.regex = require('./regex');

  // Instance properties
  this.apps = {};
  this.vhosts = {};
  this.path = pathModule.resolve(__dirname, '../');
  this.className = this.constructor.name;
  this.environment = this.config.environment;

  // Server options, provided by environment
  this.serverOptions = null;

  // Preload Utility
  var Utility = require('./utility'),
      skipFromLibDir = ['request.js', 'response.js', 'corejs.js', 'command.js', 'client'];

  this.util = new Utility();

  // Lib
  this.util.getFiles(this.path + '/lib', function(file) {
    var key = file.replace(self.regex.jsFile, '');
    if (skipFromLibDir.indexOf(file) >= 0) return;
    self.lib[key] = require(self.path + '/lib/' + file);
  });

  // Storage
  this.util.getFiles(this.path + '/storages/' , function(file) {
    var key = file.replace(self.regex.jsFile, '');
    self.storages[key] = require(self.path + '/storages/' + file);
  });

  // Database drivers
  this.util.getFiles(this.path + '/drivers', function(file) {
    var key = file.replace(self.regex.jsFile, '');
    self.drivers[key] = require(self.path + '/drivers/' + file);
  });

  // Template engine prototype
  this.engineProto = new this.lib.engine();

  // Template Engines
  this.util.getFiles(this.path + '/engines', function(file) {
    var key = file.replace(self.regex.jsFile, '');
    self.engines[key] = require(self.path + '/engines/' + file);
  });

  // Enhance request/response
  require('./response');
  require('./request');

  // Allow using corejs standalone
  if (noserver) return;

  // Start the debugger if on DEBUG environment
  if (this.config.environment == 'debug') this.checkInspectorStatus();

  // Launch application server
  this.launchApplication();

  // Only set important properties enumerable
  this.util.onlySetEnumerable(this, ['version', 'className', 'environment', 'path', 'config', 'vhosts', 'apps',
    'drivers', 'engines', 'storages']);

  // console.exit(this);
}

// Version
CoreJS.version = require('../package.json').version;

// Stores the configuration settings for the corejs
CoreJS.config = {
  autoCurl: true
};

// Save the Framework's MasterPath, for future reference
CoreJS.path = pathModule.resolve(__dirname, '../');

// Inherit from EventEmitter
CoreJS.__proto__ = new EventEmitter();

/**
  Developers Note: the static properties of the CoreJS constructor are passed
  to the corejs instance on construction. This means, the methods and properties
  available in the CoreJS constructor will also be available in the instance.
 */

/**
  Bootstraps an application

  @param {string} dir
  @param {object} config
  @static
 */

CoreJS.bootstrap = function(dir, config) {

  if (process.env.FAUX === '1') {
    console.log(JSON.stringify(config));
    process.exit();
  }

  if (typeof config == 'undefined') {
    throw new Error('Configuration parameter missing');
  }

  ['server', 'environments', 'events'].forEach(function(section) {
    if (!config[section]) config[section] = {};
  });

  var appEnv, envFunc, vhosts = {};

  // Get environment
  appEnv = process.env.NODE_ENV || config.environments.default || 'development';

  // Start node debugger, if on `debug` environment
  if (appEnv == 'debug') {
    console.log('');
    require('child_process').spawn('kill', ['-s', 'SIGUSR1', process.pid]);
    CoreJS.configure('inspector_port', config.server.inspectorPort || 3000);
  }

  // Configure vhosts
  CoreJS.configure('bootstrap', config);

  // Ability to alter the bootstrap
  CoreJS.emit('bootstrap_config', config);

  CoreJS.configure('environment', appEnv);
  CoreJS.configure('hostname', config.server.host || 'localhost');
  CoreJS.configure('appPath', dir);

  // Stay up setting
  if (typeof config.server.stayUp == 'undefined') {
    var stayUp = false;
  } else {
    switch (config.server.stayUp.constructor.name || false) {
      case 'Boolean':
        stayUp = config.server.stayUp;
        break;
      case 'String':
        stayUp = (appEnv === config.server.stayUp);
        break;
      case 'Array':
        stayUp = (config.server.stayUp.indexOf(appEnv) >= 0)
        break;
      default: break;
    }
  }

  // console.log(stayUp);

  // Configure server
  CoreJS.configure('server', {
    listenPort: process.env.PORT_OVERRIDE || config.server.port || 8080,
    multiProcess: config.server.multiProcess || false,
    stayUp: stayUp
  });

  var events = config.events || {};

  CoreJS.once('pre_init', function(app) {

    // Setup 'environment getter'
    app.__defineGetter__('environment', function() {
      return corejs.environment;
    });

    // Run environment function from bootstrap
    var bootEnvFunc = config.environments[appEnv];
    if (bootEnvFunc instanceof Function) bootEnvFunc(app);

    // Run environment script
    var envFunc, envPath = 'config/env/' + appEnv;
    if (pathModule.existsSync(envPath)) {
      envFunc = app.require(envPath);
      if (envFunc instanceof Function) envFunc(app);
    }

    // Run bootstrap pre_init event (already on pre_init)
    if (events.pre_init instanceof Function) {
      events.pre_init.call(null, app);
      delete events.pre_init;
    }

    // Run bootstrap events
    for (var evt in events) {
      app.on(evt, events[evt]);
    }

  });

  // Framework singleton
  return new CoreJS();

}

/**
  Configures the corejs.

  @param {string} context
  @param {string|object} value
  @returns {self} for chaining
  @static
 */

CoreJS.configure = function(context, value) {
  this.config[context] = value;
  return this;
}

/**
  Requires a module relative to the corejs's path

  @param {string} module
  @param {boolean} reload
  @returns {object}
  @public
 */

CoreJS.prototype.require = function(module, reload) {
  var Module, oldCache, outModule,
      modulePath = '../' + module;

  if (reload) {
    // Get node's Module
    Module = require('module').Module;

    // Backup original cache
    oldCache = Module._cache;

    // Temporarily empty cache
    Module._cache = {};

    // Get the reloaded module
    try { outModule = require(modulePath); }
    catch(e) { outModule = require(module); }

    // Restore the module cache
    Module._cache = oldCache;

    return outModule;
  } else {
    try { return require(modulePath); }
    catch(e) { return require(module); }
  }
}

/**
  Notifies the application that an asynchronous event has been triggered
 */

CoreJS.prototype.async = function(app) {
  app.asyncQueue.push(1);
}

/**
  Notifies the application that an asynchronous event has finalized

 */

CoreJS.prototype.done = function(app) {
  app.asyncQueue.pop();
  if (app.asyncQueue.length === 0) {
    // Application is initialized on the next tick of event loop,
    // To prevent access errors on objects
    process.nextTick(function() {
      app.initialize();
    });
  }
}

/**
  Deep extend, up to one level

  @param {object} source
  @param {object} destination
  @return {object}
 */

CoreJS.prototype.configExtend = function(base, source) {
  // Extend the base, 1 level deep
  for (var key in base) {
    if (key in source) {
      if (source[key] instanceof Array) {
        base[key] = source[key];
      } else if (source[key] instanceof Object) {
        corejs.extend(base[key], source[key]);
      } else {
        base[key] = source[key];
      }
    }
  }
  return base;
}

/**
  Shortcut for util.inherits

  @param {function} base
  @param {function} parent
  @public
 */

CoreJS.prototype.inherits = function(base, parent) {
  util.inherits(base, this.lib[parent]);
}

/**
  Initializes applications, and configures virtual hosts

  @param {object} servers
  @private
 */

CoreJS.prototype.launchApplication = function(servers) {
  var enumerable = ['className', 'domain', 'path', 'debugLog', 'viewCaching',
      'storage', 'lib','models', 'helpers', 'controllers', 'engines', 'initialized'];

  var host = this.config.hostname,
      path = pathModule.resolve(this.path, this.config.appPath);

  // Enable inheritance within Application
  var Application = corejs.lib.application;

  // Extend the application's prototype
  var appExtend = path + '/app.js';
  if (pathModule.existsSync(appExtend)) require(appExtend);

  // Initialize app routes
  this.lib.controller.prototype.queuedRoutes[host] = [];

  // Provide new app prototype
  var app = new Application(host, path);

  // Only set important properties enumerable
  this.util.onlySetEnumerable(app, enumerable);

  // Start the server
  this.startServer();
}

/**
  Starts the application server

  @private
 */

CoreJS.prototype.startServer = function() {

  /*jshint loopfunc:true */

  var app = this.app,
      interProcess = this,
      options = this.config.server,
      allCPUS = os.cpus().length,
      bootstrap = corejs.config.bootstrap;

  // Merge config with this.clusterConfig
  options = this.serverOptions = _.extend(this.clusterConfig, options);

  if (typeof options.multiProcess == 'number') {
    allCPUS = (options.multiProcess || 1);
    options.multiProcess = true;
    options.allCPUS = allCPUS;
  } else if (typeof options.multiProcess == 'boolean') {
    options.allCPUS = allCPUS;
  } else {
    throw new Error("The multiProcess option accepts {int|boolean}. Check your boot.js file");
  }

  // Convenience function, to avoid repetition
  function commonStartupOperations() {
    if (options.stayUp) {
      process.on('uncaughtException', app.log); // prints stack trace
    }

    // console.log(process.pid);

    startupMessage.call(this, options);
  }

  if (options.multiProcess && cluster.isMaster) {

    // Master

    process.title = options.masterProcess;

    for (var worker, i=0; i < allCPUS; i++) {
      worker = cluster.fork();
      worker.on('message', function(data) {
        if (data.cmd != null) interProcess.emit('worker_message', data);
        if (data.response != null) worker.send({response: data.response});
      });
    }

    cluster.on('death', function(worker) {
      app.log('Worker process ' + worker.pid + ' died. Restarting...');
      cluster.fork();
    });

    commonStartupOperations.call(this);
    app.log('Master running...');

  } else {

    // app.server already available on `pre_init` event

    // Worker
    app.server.listen(options.listenPort, app.domain, function() {
      // Server init event
      app.emit('server_init', app.server);
    });

    if (options.multiProcess) {
      process.title = options.workerProcess;
      app.log('Worker running...');
    } else {
      process.title = options.singleProcess;
      commonStartupOperations.call(this);
      autoCurlRequest();
    }

  }
}

/**
  Checks the status of the node inspector

  @private
 */

CoreJS.prototype.checkInspectorStatus = function() {
  var port = this.config.inspector_port || 3000;

  this.util.checkPort(port, function(err) {
    if (err) {
      console.log('Node Inspector is not running.\n\nStart it with `./tools/run-inspector`\n');
      process.exit();
    } else {
      console.log('Node Inspector running on http://0.0.0.0:' + port);
    }
  });

}

/**
  Prints the startup message

  @param {object} options
  @private
 */

function startupMessage(options) {
  var app = this.app;
  if ((process.argv.length >= 3 && !options.multiProcess) || process.env.NODE_ENV == 'silent') {
    return; // Disable startup message on curl requests
  }
  app.log(util.format('%s Server running on %s', inflect.capitalize(corejs.environment), app.baseUrl));
  if (options.multiProcess) app.log(util.format('Running a cluster of %d workers', options.allCPUS));
  app.emit('startup_message');
}

/**
  Handles automatic curl requests on environments, by passing its command line options for a new request.

  If a relative path is used, the default application's (the first you have defined on the environment) url
  will be used, and the path attached to it.

  An URL can also be used.

  @private
 */

function autoCurlRequest() {
  if (process.argv.length >= 3 && corejs.config.autoCurl) {
    var app = corejs.app,
        config = corejs.config,
        args = process.argv.slice(2),
        url = args[args.length - 1],
        exec = require('child_process').exec,
        portStr = config.server.listenPort !== 80 ? ":" + config.server.listenPort : '';

    if (corejs.regex.startsWithSlash.test(url)) {
      url = "http://" + app.domain + portStr + url;
    }

    var switches = args.slice(0, (args.length - 1)).join(' ');
    var cmd = switches + ' ' + url;

    var cb = function() {
      app.curl(cmd, function(err, buf) {
        console.log(err || buf);
        process.exit(0);
      });
    }

    // Run request when needed
    if (app.initialized) cb();
    else app.on('init', cb);

  }
}

module.exports = CoreJS;
<commit_msg>Fixed environments refactor<commit_after>
/**
  CoreJS

  Configures the corejs, and is in charge of assembling all the applications together.
  Provides the master server that handles and routes all of the virtual host requests.

  Available globally as corejs.
 */

require('./extensions.js');

var _ = require('underscore'),
    events = require('events'),
    net = require('net'),
    inflect = require('./support/inflect.js'),
    child_process = require('child_process'),
    cluster = require('cluster'),
    os = require('os'),
    http = require('http'),
    util = require('util'),
    pathModule = require('path'),
    EventEmitter = events.EventEmitter;

function CoreJS(noserver) {

  var self = this;

  // Initialize `corejs` global
  global.corejs = this;

  // Inherit from constructor
  _.extend(this, this.constructor);

  // Cluster configuration
  this.clusterConfig = {
    listenPort: null,
    multiProcess: 0,
    masterProcess: 'node [master]',
    singleProcess: 'node [single process]',
    workerProcess: 'node worker'
  };

  this.extend = _.extend;

  // Internals
  this.drivers = {};
  this.engines = {};
  this.storages = {};
  this.lib = {};

  // Regular expressions
  this.regex = require('./regex');

  // Instance properties
  this.apps = {};
  this.vhosts = {};
  this.path = pathModule.resolve(__dirname, '../');
  this.className = this.constructor.name;
  this.environment = this.config.environment;

  // Server options, provided by environment
  this.serverOptions = null;

  // Preload Utility
  var Utility = require('./utility'),
      skipFromLibDir = ['request.js', 'response.js', 'corejs.js', 'command.js', 'client'];

  this.util = new Utility();

  // Lib
  this.util.getFiles(this.path + '/lib', function(file) {
    var key = file.replace(self.regex.jsFile, '');
    if (skipFromLibDir.indexOf(file) >= 0) return;
    self.lib[key] = require(self.path + '/lib/' + file);
  });

  // Storage
  this.util.getFiles(this.path + '/storages/' , function(file) {
    var key = file.replace(self.regex.jsFile, '');
    self.storages[key] = require(self.path + '/storages/' + file);
  });

  // Database drivers
  this.util.getFiles(this.path + '/drivers', function(file) {
    var key = file.replace(self.regex.jsFile, '');
    self.drivers[key] = require(self.path + '/drivers/' + file);
  });

  // Template engine prototype
  this.engineProto = new this.lib.engine();

  // Template Engines
  this.util.getFiles(this.path + '/engines', function(file) {
    var key = file.replace(self.regex.jsFile, '');
    self.engines[key] = require(self.path + '/engines/' + file);
  });

  // Enhance request/response
  require('./response');
  require('./request');

  // Allow using corejs standalone
  if (noserver) return;

  // Start the debugger if on DEBUG environment
  if (this.config.environment == 'debug') this.checkInspectorStatus();

  // Launch application server
  this.launchApplication();

  // Only set important properties enumerable
  this.util.onlySetEnumerable(this, ['version', 'className', 'environment', 'path', 'config', 'vhosts', 'apps',
    'drivers', 'engines', 'storages']);

  // console.exit(this);
}

// Version
CoreJS.version = require('../package.json').version;

// Stores the configuration settings for the corejs
CoreJS.config = {
  autoCurl: true
};

// Save the Framework's MasterPath, for future reference
CoreJS.path = pathModule.resolve(__dirname, '../');

// Inherit from EventEmitter
CoreJS.__proto__ = new EventEmitter();

/**
  Developers Note: the static properties of the CoreJS constructor are passed
  to the corejs instance on construction. This means, the methods and properties
  available in the CoreJS constructor will also be available in the instance.
 */

/**
  Bootstraps an application

  @param {string} dir
  @param {object} config
  @static
 */

CoreJS.bootstrap = function(dir, config) {

  if (process.env.FAUX === '1') {
    console.log(JSON.stringify(config));
    process.exit();
  }

  if (typeof config == 'undefined') {
    throw new Error('Configuration parameter missing');
  }

  ['server', 'environments', 'events'].forEach(function(section) {
    if (!config[section]) config[section] = {};
  });

  var appEnv, envFunc, vhosts = {};

  // Get environment
  appEnv = process.env.NODE_ENV || config.environments.default || 'development';

  // Start node debugger, if on `debug` environment
  if (appEnv == 'debug') {
    console.log('');
    require('child_process').spawn('kill', ['-s', 'SIGUSR1', process.pid]);
    CoreJS.configure('inspector_port', config.server.inspectorPort || 3000);
  }

  // Configure vhosts
  CoreJS.configure('bootstrap', config);

  // Ability to alter the bootstrap
  CoreJS.emit('bootstrap_config', config);

  CoreJS.configure('environment', appEnv);
  CoreJS.configure('hostname', config.server.host || 'localhost');
  CoreJS.configure('appPath', dir);

  // Stay up setting
  if (typeof config.server.stayUp == 'undefined') {
    var stayUp = false;
  } else {
    switch (config.server.stayUp.constructor.name || false) {
      case 'Boolean':
        stayUp = config.server.stayUp;
        break;
      case 'String':
        stayUp = (appEnv === config.server.stayUp);
        break;
      case 'Array':
        stayUp = (config.server.stayUp.indexOf(appEnv) >= 0)
        break;
      default: break;
    }
  }

  // console.log(stayUp);

  // Configure server
  CoreJS.configure('server', {
    listenPort: process.env.PORT_OVERRIDE || config.server.port || 8080,
    multiProcess: config.server.multiProcess || false,
    stayUp: stayUp
  });

  var events = config.events || {};

  CoreJS.once('pre_init', function(app) {

    // Setup 'environment getter'
    app.__defineGetter__('environment', function() {
      return corejs.environment;
    });

    // Run environment script
    var envFunc, envPath = 'config/env/' + appEnv + '.js';

    if (pathModule.existsSync(app.fullPath(envPath))) {
      envFunc = app.require(envPath);
      if (envFunc instanceof Function) envFunc(app);
    }

    // Run environment function from bootstrap
    var bootEnvFunc = config.environments[appEnv];
    if (bootEnvFunc instanceof Function) bootEnvFunc(app);

    // Run bootstrap pre_init event (already on pre_init)
    if (events.pre_init instanceof Function) {
      events.pre_init.call(null, app);
      delete events.pre_init;
    }

    // Run bootstrap events
    for (var evt in events) {
      app.on(evt, events[evt]);
    }

  });

  // Framework singleton
  return new CoreJS();

}

/**
  Configures the corejs.

  @param {string} context
  @param {string|object} value
  @returns {self} for chaining
  @static
 */

CoreJS.configure = function(context, value) {
  this.config[context] = value;
  return this;
}

/**
  Requires a module relative to the corejs's path

  @param {string} module
  @param {boolean} reload
  @returns {object}
  @public
 */

CoreJS.prototype.require = function(module, reload) {
  var Module, oldCache, outModule,
      modulePath = '../' + module;

  if (reload) {
    // Get node's Module
    Module = require('module').Module;

    // Backup original cache
    oldCache = Module._cache;

    // Temporarily empty cache
    Module._cache = {};

    // Get the reloaded module
    try { outModule = require(modulePath); }
    catch(e) { outModule = require(module); }

    // Restore the module cache
    Module._cache = oldCache;

    return outModule;
  } else {
    try { return require(modulePath); }
    catch(e) { return require(module); }
  }
}

/**
  Notifies the application that an asynchronous event has been triggered
 */

CoreJS.prototype.async = function(app) {
  app.asyncQueue.push(1);
}

/**
  Notifies the application that an asynchronous event has finalized

 */

CoreJS.prototype.done = function(app) {
  app.asyncQueue.pop();
  if (app.asyncQueue.length === 0) {
    // Application is initialized on the next tick of event loop,
    // To prevent access errors on objects
    process.nextTick(function() {
      app.initialize();
    });
  }
}

/**
  Deep extend, up to one level

  @param {object} source
  @param {object} destination
  @return {object}
 */

CoreJS.prototype.configExtend = function(base, source) {
  // Extend the base, 1 level deep
  for (var key in base) {
    if (key in source) {
      if (source[key] instanceof Array) {
        base[key] = source[key];
      } else if (source[key] instanceof Object) {
        corejs.extend(base[key], source[key]);
      } else {
        base[key] = source[key];
      }
    }
  }
  return base;
}

/**
  Shortcut for util.inherits

  @param {function} base
  @param {function} parent
  @public
 */

CoreJS.prototype.inherits = function(base, parent) {
  util.inherits(base, this.lib[parent]);
}

/**
  Initializes applications, and configures virtual hosts

  @param {object} servers
  @private
 */

CoreJS.prototype.launchApplication = function(servers) {
  var enumerable = ['className', 'domain', 'path', 'debugLog', 'viewCaching',
      'storage', 'lib','models', 'helpers', 'controllers', 'engines', 'initialized'];

  var host = this.config.hostname,
      path = pathModule.resolve(this.path, this.config.appPath);

  // Enable inheritance within Application
  var Application = corejs.lib.application;

  // Extend the application's prototype
  var appExtend = path + '/app.js';
  if (pathModule.existsSync(appExtend)) require(appExtend);

  // Initialize app routes
  this.lib.controller.prototype.queuedRoutes[host] = [];

  // Provide new app prototype
  var app = new Application(host, path);

  // Only set important properties enumerable
  this.util.onlySetEnumerable(app, enumerable);

  // Start the server
  this.startServer();
}

/**
  Starts the application server

  @private
 */

CoreJS.prototype.startServer = function() {

  /*jshint loopfunc:true */

  var app = this.app,
      interProcess = this,
      options = this.config.server,
      allCPUS = os.cpus().length,
      bootstrap = corejs.config.bootstrap;

  // Merge config with this.clusterConfig
  options = this.serverOptions = _.extend(this.clusterConfig, options);

  if (typeof options.multiProcess == 'number') {
    allCPUS = (options.multiProcess || 1);
    options.multiProcess = true;
    options.allCPUS = allCPUS;
  } else if (typeof options.multiProcess == 'boolean') {
    options.allCPUS = allCPUS;
  } else {
    throw new Error("The multiProcess option accepts {int|boolean}. Check your boot.js file");
  }

  // Convenience function, to avoid repetition
  function commonStartupOperations() {
    if (options.stayUp) {
      process.on('uncaughtException', app.log); // prints stack trace
    }

    // console.log(process.pid);

    startupMessage.call(this, options);
  }

  if (options.multiProcess && cluster.isMaster) {

    // Master

    process.title = options.masterProcess;

    for (var worker, i=0; i < allCPUS; i++) {
      worker = cluster.fork();
      worker.on('message', function(data) {
        if (data.cmd != null) interProcess.emit('worker_message', data);
        if (data.response != null) worker.send({response: data.response});
      });
    }

    cluster.on('death', function(worker) {
      app.log('Worker process ' + worker.pid + ' died. Restarting...');
      cluster.fork();
    });

    commonStartupOperations.call(this);
    app.log('Master running...');

  } else {

    // app.server already available on `pre_init` event

    // Worker
    app.server.listen(options.listenPort, app.domain, function() {
      // Server init event
      app.emit('server_init', app.server);
    });

    if (options.multiProcess) {
      process.title = options.workerProcess;
      app.log('Worker running...');
    } else {
      process.title = options.singleProcess;
      commonStartupOperations.call(this);
      autoCurlRequest();
    }

  }
}

/**
  Checks the status of the node inspector

  @private
 */

CoreJS.prototype.checkInspectorStatus = function() {
  var port = this.config.inspector_port || 3000;

  this.util.checkPort(port, function(err) {
    if (err) {
      console.log('Node Inspector is not running.\n\nStart it with `./tools/run-inspector`\n');
      process.exit();
    } else {
      console.log('Node Inspector running on http://0.0.0.0:' + port);
    }
  });

}

/**
  Prints the startup message

  @param {object} options
  @private
 */

function startupMessage(options) {
  var app = this.app;
  if ((process.argv.length >= 3 && !options.multiProcess) || process.env.NODE_ENV == 'silent') {
    return; // Disable startup message on curl requests
  }
  app.log(util.format('%s Server running on %s', inflect.capitalize(corejs.environment), app.baseUrl));
  if (options.multiProcess) app.log(util.format('Running a cluster of %d workers', options.allCPUS));
  app.emit('startup_message');
}

/**
  Handles automatic curl requests on environments, by passing its command line options for a new request.

  If a relative path is used, the default application's (the first you have defined on the environment) url
  will be used, and the path attached to it.

  An URL can also be used.

  @private
 */

function autoCurlRequest() {
  if (process.argv.length >= 3 && corejs.config.autoCurl) {
    var app = corejs.app,
        config = corejs.config,
        args = process.argv.slice(2),
        url = args[args.length - 1],
        exec = require('child_process').exec,
        portStr = config.server.listenPort !== 80 ? ":" + config.server.listenPort : '';

    if (corejs.regex.startsWithSlash.test(url)) {
      url = "http://" + app.domain + portStr + url;
    }

    var switches = args.slice(0, (args.length - 1)).join(' ');
    var cmd = switches + ' ' + url;

    var cb = function() {
      app.curl(cmd, function(err, buf) {
        console.log(err || buf);
        process.exit(0);
      });
    }

    // Run request when needed
    if (app.initialized) cb();
    else app.on('init', cb);

  }
}

module.exports = CoreJS;
<|endoftext|>


<commit_before>app.directive('palette', function() {
    return {
        restrict: 'E',
        scope: true,
        templateUrl: 'app/toolbox/directives/painting/palette/palette.tpl.html',
        controller: 'PaletteCtrl'
    };
});

app.controller('PaletteCtrl', function($scope) {
	$scope.toolname = 'palette'
	$scope.active = $scope.config.tools.activeTool == $scope.toolname;

	$scope.color = {
            H: 100,
            S: 70,
            V: 80,
            hex: "#000000",
        }

        var palmousedown = false;
		var huemousedown = false;

        var palette = document.getElementById("palette");
        var hue = document.getElementById("hue");

        var palContext = palette.getContext('2d');
        var hueContext = hue.getContext('2d');

        var palBox = palette.getBoundingClientRect();
        var hueBox = hue.getBoundingClientRect();

        var palImg = new Image();
        palImg.src = "assets/img/bgGradient.png";

        var hueImg = new Image();
        hueImg.src = "assets/img/hueBar.png";

        hueImg.onload = function() {
            $scope.$watch('color', function(newVal, oldVal) {
                rgb = HSVtoRGB(newVal.H, newVal.S, newVal.V);
                $scope.config.tools.colors.primary.r = rgb.R;
                $scope.config.tools.colors.primary.g = rgb.G;
                $scope.config.tools.colors.primary.b = rgb.B;
                $scope.color.hex = RGBtoHEX(rgb.R, rgb.G, rgb.B);

                drawMarker(palette, palBox, palContext, palImg);
                drawBar(hue, hueBox, hueContext, hueImg);
            }, true);
        };

	/* init */
	$scope.init = function() {
		$scope.setCursor('default');
	};

	$scope.mouseDown = function() {

	};

	/* onMouseUp */
	$scope.mouseUp = function() {

	};

	/* onMouseMove */
	$scope.mouseMove = function() {

	};

    $scope.palMouseDown = function(event) {
        updateSV(event);
        palmousedown = true;
    }

    $scope.palMouseMove = function(event) {
        if (palmousedown) {
            updateSV(event);
        }
    }

    $scope.palMouseUp = function() {
        palmousedown = false;
    }

    $scope.hueMouseDown = function(event) {
        updateH(event);
        huemousedown = true;
    };

    $scope.hueMouseMove = function(event) {
        if (huemousedown) {
            updateH(event);
        }
    }

    $scope.hueMouseUp = function() {
        huemousedown = false;
    }

	/*
	 * This will watch for this tools' "active" variable changes.
	 * When "active" changes to "true", this tools functions need to
	 * be registered to the global config.
	 * This functions NEEDS to be in each tools controller for
	 * the tool to function. Please assign the correct toolfunctions
	 * to the "activeToolFunctions" object.
	 * Always call "init" first;
	 */
	$scope.$watch('active', function(nval, oval) {
		if (nval) {
			$scope.init();

			$scope.config.tools.activeToolFunctions = {
				mouseDown: $scope.mouseDown,
				mouseUp: $scope.mouseUp,
				mouseMove: $scope.mouseMove
			};
		}
	}, true);

	function updateSV(event) {
        $scope.color.S = Math.floor((event.offsetX*100)/(palBox.right - palBox.left));
        $scope.color.V = Math.floor(100-(event.offsetY*100)/(palBox.bottom - palBox.top));
    }

    function updateH(event) {
        $scope.color.H = Math.floor(360-(event.offsetY*360)/(hueBox.bottom - hueBox.top));
    }

    function drawMarker(palette, palBox, palContext, palImg) {
        palContext.clearRect(0, 0, palette.width, palette.height);
        palContext.drawImage(palImg, 0, 0);
        palContext.beginPath();
        locX = $scope.color.S * (palBox.right - palBox.left)/100;
        locY = (100 - $scope.color.V) * (palBox.bottom - palBox.top)/100;
        palContext.arc(locX,locY,5,0,2*Math.PI, false);
        palContext.fillStyle = "rgb("  + $scope.config.tools.colors.primary.r + ","
                                    + $scope.config.tools.colors.primary.g + ","
                                    + $scope.config.tools.colors.primary.b + ")";
        palContext.fill();
        palContext.lineWidth = 2;
        palContext.strokeStyle = "black";
        palContext.stroke();
        palContext.lineWidth = 1;
        palContext.strokeStyle = "white";
        palContext.stroke();
    }

    function drawBar(hue, hueBox, hueContext, hueImg) {
        hueContext.clearRect(0, 0, hue.width, hue.height);
        hueContext.drawImage(hueImg, 0, 0, hue.width, hue.height);
        hueContext.beginPath();
        loc = (360 - $scope.color.H) * (hueBox.bottom - hueBox.top)/360;
        hueContext.rect(0, loc - 3, hueBox.right-hueBox.left, 6);
        hueContext.fillStyle = "hsl(" + $scope.color.H + ", 100%, 50%)";
        hueContext.fill();
        hueContext.lineWidth = 2;
        hueContext.strokeStyle = "black";
        hueContext.stroke();
    }
});<commit_msg>fixed indentation<commit_after>app.directive('palette', function() {
    return {
        restrict: 'E',
        scope: true,
        templateUrl: 'app/toolbox/directives/painting/palette/palette.tpl.html',
        controller: 'PaletteCtrl'
    };
});

app.controller('PaletteCtrl', function($scope) {
	$scope.toolname = 'palette'
	$scope.active = $scope.config.tools.activeTool == $scope.toolname;

	$scope.color = {
        H: 100,
        S: 70,
        V: 80,
        hex: "#000000",
    }

    var palmousedown = false;
	var huemousedown = false;

    var palette = document.getElementById("palette");
    var hue = document.getElementById("hue");

    var palContext = palette.getContext('2d');
    var hueContext = hue.getContext('2d');

    var palBox = palette.getBoundingClientRect();
    var hueBox = hue.getBoundingClientRect();

    var palImg = new Image();
    palImg.src = "assets/img/bgGradient.png";

    var hueImg = new Image();
    hueImg.src = "assets/img/hueBar.png";

    hueImg.onload = function() {
        $scope.$watch('color', function(newVal, oldVal) {
            rgb = HSVtoRGB(newVal.H, newVal.S, newVal.V);
            $scope.config.tools.colors.primary.r = rgb.R;
            $scope.config.tools.colors.primary.g = rgb.G;
            $scope.config.tools.colors.primary.b = rgb.B;
            $scope.color.hex = RGBtoHEX(rgb.R, rgb.G, rgb.B);

            drawMarker(palette, palBox, palContext, palImg);
            drawBar(hue, hueBox, hueContext, hueImg);
        }, true);
    };

	/* init */
	$scope.init = function() {
		$scope.setCursor('default');
	};

	$scope.mouseDown = function() {

	};

	/* onMouseUp */
	$scope.mouseUp = function() {

	};

	/* onMouseMove */
	$scope.mouseMove = function() {

	};

    $scope.palMouseDown = function(event) {
        updateSV(event);
        palmousedown = true;
    }

    $scope.palMouseMove = function(event) {
        if (palmousedown) {
            updateSV(event);
        }
    }

    $scope.palMouseUp = function() {
        palmousedown = false;
    }

    $scope.hueMouseDown = function(event) {
        updateH(event);
        huemousedown = true;
    };

    $scope.hueMouseMove = function(event) {
        if (huemousedown) {
            updateH(event);
        }
    }

    $scope.hueMouseUp = function() {
        huemousedown = false;
    }

	/*
	 * This will watch for this tools' "active" variable changes.
	 * When "active" changes to "true", this tools functions need to
	 * be registered to the global config.
	 * This functions NEEDS to be in each tools controller for
	 * the tool to function. Please assign the correct toolfunctions
	 * to the "activeToolFunctions" object.
	 * Always call "init" first;
	 */
	$scope.$watch('active', function(nval, oval) {
		if (nval) {
			$scope.init();

			$scope.config.tools.activeToolFunctions = {
				mouseDown: $scope.mouseDown,
				mouseUp: $scope.mouseUp,
				mouseMove: $scope.mouseMove
			};
		}
	}, true);

	function updateSV(event) {
        $scope.color.S = Math.floor((event.offsetX*100)/(palBox.right - palBox.left));
        $scope.color.V = Math.floor(100-(event.offsetY*100)/(palBox.bottom - palBox.top));
    }

    function updateH(event) {
        $scope.color.H = Math.floor(360-(event.offsetY*360)/(hueBox.bottom - hueBox.top));
    }

    function drawMarker(palette, palBox, palContext, palImg) {
        palContext.clearRect(0, 0, palette.width, palette.height);
        palContext.drawImage(palImg, 0, 0);
        palContext.beginPath();
        locX = $scope.color.S * (palBox.right - palBox.left)/100;
        locY = (100 - $scope.color.V) * (palBox.bottom - palBox.top)/100;
        palContext.arc(locX,locY,5,0,2*Math.PI, false);
        palContext.fillStyle = "rgb("  + $scope.config.tools.colors.primary.r + ","
                                    + $scope.config.tools.colors.primary.g + ","
                                    + $scope.config.tools.colors.primary.b + ")";
        palContext.fill();
        palContext.lineWidth = 2;
        palContext.strokeStyle = "black";
        palContext.stroke();
        palContext.lineWidth = 1;
        palContext.strokeStyle = "white";
        palContext.stroke();
    }

    function drawBar(hue, hueBox, hueContext, hueImg) {
        hueContext.clearRect(0, 0, hue.width, hue.height);
        hueContext.drawImage(hueImg, 0, 0, hue.width, hue.height);
        hueContext.beginPath();
        loc = (360 - $scope.color.H) * (hueBox.bottom - hueBox.top)/360;
        hueContext.rect(0, loc - 3, hueBox.right-hueBox.left, 6);
        hueContext.fillStyle = "hsl(" + $scope.color.H + ", 100%, 50%)";
        hueContext.fill();
        hueContext.lineWidth = 2;
        hueContext.strokeStyle = "black";
        hueContext.stroke();
    }
});<|endoftext|>


<commit_before>var protocol = require('transduce-protocol');

function load(){
  var libs = ['transducers-js', 'transducers.js'], impl;
  if(typeof process !== 'undefined' && process.env && process.env.TRANSDUCE_IMPL){
    libs = [process.env.TRANSDUCE_IMPL];
  }
  var i = 0; len = libs.length;
  for(; i < len; i++){
    try {
      impl = loader[libs[i]]();
      if(impl !== undef){
        return impl;
      }
    } catch(e){}
  }
  throw new Error('Must install one of: '+libs.join());
}

var undef, loader = {
  'transducers-js': function(){
    var impl;
    if(typeof window !== 'undefined' && window.transducers && window.transducers.Wrap){
      impl = window.transducers;
    } else {
      impl = require('transducers-js');
    }
    return impl;
  },
  'transducers.js': function(){
    //adapt methods to match transducers-js API
    var impl;
    if(typeof window !== 'undefined' && window.transducers){
      impl = window.transducers;
    } else {
      impl = require('transducers.js');
    }
    return {
      into: impl.into,
      transduce: function(xf, f, init, coll){
        f = protocol.transformer(f);
        return impl.transduce(coll, xf, f, init);
      },
      reduce: function(f, init, coll){
        f = protocol.transformer(f);
        return impl.reduce(coll, f, init);
      },
      map: nullFirst(impl, 'map'),
      filter: nullFirst(impl, 'filter'),
      remove: nullFirst(impl, 'remove'),
      take: nullFirst(impl, 'take'),
      takeWhile: nullFirst(impl, 'takeWhile'),
      drop: nullFirst(impl, 'drop'),
      dropWhile: nullFirst(impl, 'dropWhile'),
    }
    return impl;
  }
}

function nullFirst(impl, method){
  return function(f){
    return impl[method](f);
  }
}

var impl = load();

module.exports = {
  into: impl.into,
  transduce: impl.transduce,
  reduce: impl.reduce,
  map: impl.map,
  filter: impl.filter,
  remove: impl.remove,
  take: impl.take,
  takeWhile: impl.takeWhile,
  drop: impl.drop,
  dropWhile: impl.dropWhile,
  protocols: protocol.protocols,
  isIterator: protocol.isIterator,
  iterator: protocol.iterator,
  isTransformer: protocol.isTransformer,
  transformer: protocol.transformer,
  isReduced: protocol.isReduced,
  reduced: protocol.reduced,
  unreduced: protocol.unreduced,
  compose: protocol.compose
};
<commit_msg>Detect and load transducers.js or transducers-js from browser<commit_after>var protocol = require('transduce-protocol');

function load(){
  var libs = ['transducers-js', 'transducers.js'], impl;
  if(typeof process !== 'undefined' && process.env && process.env.TRANSDUCE_IMPL){
    libs = [process.env.TRANSDUCE_IMPL];
  }
  var i = 0; len = libs.length;
  for(; i < len; i++){
    try {
      impl = loader[libs[i]]();
      if(impl && impl.map){
        return impl;
      }
    } catch(e){}
  }
  throw new Error('Must install one of: '+libs.join());
}

var undef, loader = {
  'transducers-js': function(){
    var impl = loadFromBrowser();
    if(impl){
      if(!impl.Wrap){
        // if no Wrap exported, probably transducers.js
        impl = undef;
      }
    } else {
      impl = require('transducers-js');
    }
    return impl;
  },
  'transducers.js': function(){
    //adapt methods to match transducers-js API
    var impl = loadFromBrowser();
    if(!impl){
      impl = require('transducers.js');
    }
    return {
      into: impl.into,
      transduce: function(xf, f, init, coll){
        f = protocol.transformer(f);
        return impl.transduce(coll, xf, f, init);
      },
      reduce: function(f, init, coll){
        f = protocol.transformer(f);
        return impl.reduce(coll, f, init);
      },
      map: nullFirst(impl, 'map'),
      filter: nullFirst(impl, 'filter'),
      remove: nullFirst(impl, 'remove'),
      take: nullFirst(impl, 'take'),
      takeWhile: nullFirst(impl, 'takeWhile'),
      drop: nullFirst(impl, 'drop'),
      dropWhile: nullFirst(impl, 'dropWhile'),
    }
    return impl;
  }
}

function nullFirst(impl, method){
  return function(f){
    return impl[method](f);
  }
}

function loadFromBrowser(){
  if(typeof window !== 'undefined'){
    return window.transducers;
  }
}

var impl = load();

module.exports = {
  into: impl.into,
  transduce: impl.transduce,
  reduce: impl.reduce,
  map: impl.map,
  filter: impl.filter,
  remove: impl.remove,
  take: impl.take,
  takeWhile: impl.takeWhile,
  drop: impl.drop,
  dropWhile: impl.dropWhile,
  protocols: protocol.protocols,
  isIterator: protocol.isIterator,
  iterator: protocol.iterator,
  isTransformer: protocol.isTransformer,
  transformer: protocol.transformer,
  isReduced: protocol.isReduced,
  reduced: protocol.reduced,
  unreduced: protocol.unreduced,
  compose: protocol.compose
};
<|endoftext|>


<commit_before>// @flow

import React from 'react';
import type { Node } from 'react';
import classNames from 'classnames';
import { inject, observer } from 'mobx-react';

const defaultProps = {
    className: 'accordion__body',
    hideBodyClassName: 'accordion__body--hidden',
};

type AccordionItemBodyProps = {
    children: Node,
    className: string,
    hideBodyClassName: string,
    accordionStore: {
        items: Array<Object>,
        accordion: boolean,
        onChange: Function,
    },
    itemkey: string | number,
};

const AccordionItemBody = (props: AccordionItemBodyProps) => {
    const { itemkey, children, className, hideBodyClassName } = props;
    const { items, accordion } = props.accordionStore;
    const foundItem = items.find(item => item.itemkey === itemkey);
    if (!foundItem) return null;

    const { itemUuid, expanded } = foundItem;
    const id = `accordion__body-${itemUuid}`;
    const role = accordion ? 'tabpanel' : null;

    const bodyClass = classNames(className, {
        [hideBodyClassName]: !expanded,
    });
    const ariaHidden = !expanded;
    return (
        <div
            id={id}
            className={bodyClass}
            aria-hidden={ariaHidden}
            aria-labelledby={id.replace(
                'accordion__body-',
                'accordion__title-',
            )}
            role={role}
        >
            {children}
        </div>
    );
};

AccordionItemBody.defaultProps = defaultProps;
// We need this to be able to assign correct params to element.
// Minifiers modify component name
AccordionItemBody.accordionElementName = 'AccordionItemBody';

export default inject('accordionStore')(observer(AccordionItemBody));
<commit_msg>Export un-wrapped AccordionItemBody as named export<commit_after>// @flow

import React from 'react';
import type { Node } from 'react';
import classNames from 'classnames';
import { inject, observer } from 'mobx-react';

const defaultProps = {
    className: 'accordion__body',
    hideBodyClassName: 'accordion__body--hidden',
};

type AccordionItemBodyProps = {
    children: Node,
    className: string,
    hideBodyClassName: string,
    accordionStore: {
        items: Array<Object>,
        accordion: boolean,
        onChange: Function,
    },
    itemkey: string | number,
};

export const AccordionItemBody = (props: AccordionItemBodyProps) => {
    const { itemkey, children, className, hideBodyClassName } = props;
    const { items, accordion } = props.accordionStore;
    const foundItem = items.find(item => item.itemkey === itemkey);
    if (!foundItem) return null;

    const { itemUuid, expanded } = foundItem;
    const id = `accordion__body-${itemUuid}`;
    const role = accordion ? 'tabpanel' : null;

    const bodyClass = classNames(className, {
        [hideBodyClassName]: !expanded,
    });
    const ariaHidden = !expanded;
    return (
        <div
            id={id}
            className={bodyClass}
            aria-hidden={ariaHidden}
            aria-labelledby={id.replace(
                'accordion__body-',
                'accordion__title-',
            )}
            role={role}
        >
            {children}
        </div>
    );
};

AccordionItemBody.defaultProps = defaultProps;
// We need this to be able to assign correct params to element.
// Minifiers modify component name
AccordionItemBody.accordionElementName = 'AccordionItemBody';

export default inject('accordionStore')(observer(AccordionItemBody));
<|endoftext|>


<commit_before>/**
 * @fileoverview Manual testing sequence.
 */

'use strict';

/**
 * Runs the test sequence.
 */
genotet.test = function() {
  // Implement test sequences here. This is intended for manual testing,
  // e.g. the following lines create a few views.

  genotet.viewManager.createView('expression', 'My Expression Matrix', {
    fileName: 'expressionMatrix',
    isGeneRegex: true,
    isConditionRegex: true,
    geneInput: 'sig.*',
    conditionInput: 'si.*'
  });
  /*
  genotet.viewManager.createView('binding', 'My Genome Browser', {
    fileName: 'b6.bw',
    bedName: 'bed_data.bed',
    chr: '1'
  });
  */
  genotet.viewManager.createView('network', 'My Network', {
    fileName: 'meishei.tsv',
    inputGenes: 'BATF|RORC|STAT3|IRF4|MAF',
    isRegex: true
  });
};
<commit_msg>uncomment binding dev view<commit_after>/**
 * @fileoverview Manual testing sequence.
 */

'use strict';

/**
 * Runs the test sequence.
 */
genotet.test = function() {
  // Implement test sequences here. This is intended for manual testing,
  // e.g. the following lines create a few views.

  genotet.viewManager.createView('expression', 'My Expression Matrix', {
    fileName: 'expressionMatrix',
    isGeneRegex: true,
    isConditionRegex: true,
    geneInput: 'sig.*',
    conditionInput: 'si.*'
  });
  genotet.viewManager.createView('binding', 'My Genome Browser', {
    fileName: 'b6.bw',
    bedName: 'bed_data.bed',
    chr: '1'
  });
  genotet.viewManager.createView('network', 'My Network', {
    fileName: 'meishei.tsv',
    inputGenes: 'BATF|RORC|STAT3|IRF4|MAF',
    isRegex: true
  });
};
<|endoftext|>


<commit_before>'use strict';

module.exports = function(leadAttributes) {
  return '<tns:paramsSyncLead>' +
    '<leadRecord>' +
    '<Email>' + leadAttributes.Email + '</Email>' +
    '<leadAttributeList>' +
    '<attribute>' +
    '<attrName>FirstName</attrName><attrValue>' + leadAttributes.FirstName + '</attrValue>' +
    '</attribute>' +
    '<attribute>' +
    '<attrName>LastName</attrName><attrValue>' + leadAttributes.LastName + '</attrValue>' +
    '</attribute>' +
    '</leadAttributeList>' +
    '</leadRecord>' +
    '<returnLead>true</returnLead>' +
    '</tns:paramsSyncLead>';
};

<commit_msg>Added Company and JobTitle to lead attributes<commit_after>'use strict';

module.exports = function(leadAttributes) {
  return '<tns:paramsSyncLead>' +
    '<leadRecord>' +
    '<Email>' + leadAttributes.Email + '</Email>' +
    '<leadAttributeList>' +
    '<attribute>' +
    '<attrName>FirstName</attrName><attrValue>' + leadAttributes.FirstName + '</attrValue>' +
    '</attribute>' +
    '<attribute>' +
    '<attrName>LastName</attrName><attrValue>' + leadAttributes.LastName + '</attrValue>' +
    '</attribute>' +
    '<attribute>' +
    '<attrName>JobTitle</attrName><attrValue>' + leadAttributes.JobTitle + '</attrValue>' +
    '</attribute>' +
    '<attribute>' +
    '<attrName>Company</attrName><attrValue>' + leadAttributes.Company + '</attrValue>' +
    '</attribute>'
    '</leadAttributeList>' +
    '</leadRecord>' +
    '<returnLead>true</returnLead>' +
    '</tns:paramsSyncLead>';
};

<|endoftext|>


<commit_before>import React from 'react';
import { Row, Col } from 'react-bootstrap';

import wedding from '../../../../../config/wedding.js';

import glob from 'styles/app';
import local from './_styles';
import Map from '../../_partials/map/map';

import PageHeader from '../../_partials/page-header';
import WeddingDate from '../../_partials/pretty-wedding-date';
import EucFour from '../../svg/euc-4';
import VenueAddress from '../../_partials/venue-address';

/**
  *
  * The details page
  *
  * @param  none
  *
  * @return {ReactComponent}
  */

export default () => {
  return (

      <PageHeader page="The Wedding" />

      <Row style={{marginBottom: '30px'}}>
        <Col xs={12}>
          <div className={`${local.eucSet}`}>
            <div className={`${local.eucDate} ${local.eucBorderLeft}`}>
              <EucFour color="$blackLight" />

            <div className={`${local.eucDate} ${local.eucBorderRight}`}>
              <EucFour color="$blackLight" />

          <h2 className={`${local.date}`}>
            <WeddingDate />

          <div className={`${local.eucSet} ${local.eucSetBtm}`}>
            <div className={`${local.eucDate} ${local.eucBorderLeft}`}>
              <EucFour color="$blackLight" />

            <div className={`${local.eucDate} ${local.eucBorderRight}`}>
              <EucFour color="$blackLight" />

        </Col>
      </Row>

      <Row style={{ marginBottom: '30px' }}>
        <Col xs={12} sm={6} md={4} mdOffset={2} className={local.location}>

Ceremony & Reception
to Follow at:

{wedding.venue.name}

<VenueAddress />

        </Col>
        <Col xs={8} xsOffset={2} sm={6} smOffset={0} md={4}>
          <Map type="venue" />
        </Col>
      </Row>

Timeline

        <Row>
          <Col xs={8} xsOffset={1} sm={6} smOffset={3} md={4} mdOffset={4}>
            <div className={`${glob.card} ${local.timeline}`}>
              {wedding.timeline.map((timelineEvent, index) => {
                const ref = `timeline_${index}`;

                return (
                  <Row className={local.event} key={ref}>
                    <Col xs={5}>

{timelineEvent.time.start}

                    </Col>
                    <Col xs={2}>

                        ·······

                    </Col>
                    <Col xs={5}>

{timelineEvent.eventName}

                    </Col>
                  </Row>
                );
              })}

          </Col>
        </Row>

  );
};
<commit_msg>Eucalyptus colors<commit_after>import React from 'react';
import { Row, Col } from 'react-bootstrap';

import wedding from '../../../../../config/wedding.js';

import glob from 'styles/app';
import local from './_styles';
import Map from '../../_partials/map/map';

import PageHeader from '../../_partials/page-header';
import WeddingDate from '../../_partials/pretty-wedding-date';
import EucFour from '../../svg/euc-4';
import VenueAddress from '../../_partials/venue-address';

/**
  *
  * The details page
  *
  * @param  none
  *
  * @return {ReactComponent}
  */

export default () => {
  return (

      <PageHeader page="The Wedding" />

      <Row style={{marginBottom: '30px'}}>
        <Col xs={12}>
          <div className={`${local.eucSet}`}>
            <div className={`${local.eucDate} ${local.eucBorderLeft}`}>
              <EucFour color="$black" />

            <div className={`${local.eucDate} ${local.eucBorderRight}`}>
              <EucFour color="$black" />

          <h2 className={`${local.date}`}>
            <WeddingDate />

          <div className={`${local.eucSet} ${local.eucSetBtm}`}>
            <div className={`${local.eucDate} ${local.eucBorderLeft}`}>
              <EucFour color="$blackLight" />

            <div className={`${local.eucDate} ${local.eucBorderRight}`}>
              <EucFour color="$blackLight" />

        </Col>
      </Row>

      <Row style={{ marginBottom: '30px' }}>
        <Col xs={12} sm={6} md={4} mdOffset={2} className={local.location}>

Ceremony & Reception
to Follow at:

{wedding.venue.name}

<VenueAddress />

        </Col>
        <Col xs={8} xsOffset={2} sm={6} smOffset={0} md={4}>
          <Map type="venue" />
        </Col>
      </Row>

Timeline

        <Row>
          <Col xs={8} xsOffset={1} sm={6} smOffset={3} md={4} mdOffset={4}>
            <div className={`${glob.card} ${local.timeline}`}>
              {wedding.timeline.map((timelineEvent, index) => {
                const ref = `timeline_${index}`;

                return (
                  <Row className={local.event} key={ref}>
                    <Col xs={5}>

{timelineEvent.time.start}

                    </Col>
                    <Col xs={2}>

                        ·······

                    </Col>
                    <Col xs={5}>

{timelineEvent.eventName}

                    </Col>
                  </Row>
                );
              })}

          </Col>
        </Row>

  );
};
<|endoftext|>


<commit_before>
/**
  CoreJS

  Configures the corejs, and is in charge of assembling all the applications together.
  Provides the master server that handles and routes all of the virtual host requests.

  Available globally as corejs.
 */

require('./extensions.js');

var _ = require('underscore'),
    events = require('events'),
    net = require('net'),
    child_process = require('child_process'),
    cluster = require('cluster'),
    os = require('os'),
    http = require('http'),
    util = require('util'),
    pathModule = require('path'),
    EventEmitter = events.EventEmitter;

function CoreJS(noserver) {

  var self = this;

  // Initialize `corejs` global
  global.corejs = this;

  // Inherit from constructor
  _.extend(this, this.constructor);

  // Cluster configuration
  this.clusterConfig = {
    listenPort: null,
    multiProcess: 0,
    masterProcess: 'node [master]',
    singleProcess: 'node [single process]',
    workerProcess: 'node worker'
  };

  this.extend = _.extend;

  // Internals
  this.drivers = {};
  this.engines = {};
  this.storages = {};
  this.lib = {};

  // Regular expressions
  this.regex = require('./regex');

  // Instance properties
  this.apps = {};
  this.vhosts = {};
  this.path = pathModule.resolve(__dirname, '../');
  this.className = this.constructor.name;
  this.environment = this.config.environment;

  // Server options, provided by environment
  this.serverOptions = null;

  // Preload Utility
  var Utility = require('./utility'),
      skipFromLibDir = ['request.js', 'response.js', 'corejs.js'];

  this.util = new Utility();

  // Lib
  this.util.getFiles(this.path + '/lib', function(file) {
    var key = file.replace(self.regex.jsFile, '');
    if (skipFromLibDir.indexOf(file) >= 0) return;
    self.lib[key] = require(self.path + '/lib/' + file);
  });

  // Storage
  this.util.getFiles(this.path + '/storages/' , function(file) {
    var key = file.replace(self.regex.jsFile, '');
    self.storages[key] = require(self.path + '/storages/' + file);
  });

  // Database drivers
  this.util.getFiles(this.path + '/drivers', function(file) {
    var key = file.replace(self.regex.jsFile, '');
    self.drivers[key] = require(self.path + '/drivers/' + file);
  });

  // Template engine prototype
  this.engineProto = new this.lib.engine();

  // Template Engines
  this.util.getFiles(this.path + '/engines', function(file) {
    var key = file.replace(self.regex.jsFile, '');
    self.engines[key] = require(self.path + '/engines/' + file);
  });

  // Enhance request/response
  require('./response');
  require('./request');

  // Allow using corejs standalone
  if (noserver) return;

  // Start the debugger if on DEBUG environment
  if (this.config.environment == 'debug') this.checkInspectorStatus();

  // Launch application server
  this.launchApplication();

  // Only set important properties enumerable
  this.util.onlySetEnumerable(this, ['version', 'className', 'environment', 'path', 'config', 'vhosts', 'apps',
    'drivers', 'engines', 'storages']);

  // console.exit(this);
}

// Version
CoreJS.version = require('../package.json').version;

// Stores the configuration settings for the corejs
CoreJS.config = {
  autoCurl: true
};

// Save the Framework's MasterPath, for future reference
CoreJS.path = pathModule.resolve(__dirname, '../');

// Inherit from EventEmitter
CoreJS.__proto__ = new EventEmitter();

/**
  Developers Note: the static properties of the CoreJS constructor are passed
  to the corejs instance on construction. This means, the methods and properties
  available in the CoreJS constructor will also be available in the instance.
 */

/**
  Bootstraps an application

  @param {string} dir
  @param {object} config
  @static
 */

CoreJS.bootstrap = function(dir, config) {

  if (typeof config == 'undefined') {
    throw new Error('Configuration parameter missing');
  }

  ['server', 'environments', 'events'].forEach(function(section) {
    if (!config[section]) config[section] = {};
  });

  var appEnv, envFunc, vhosts = {};

  // Get environment
  appEnv = process.env.NODE_ENV || config.environments.default || 'development';

  // Start node debugger, if on `debug` environment
  if (appEnv == 'debug') {
    console.log('');
    require('child_process').spawn('kill', ['-s', 'SIGUSR1', process.pid]);
    CoreJS.configure('inspector_port', config.server.inspectorPort || 3000);
  }

  // Configure vhosts
  CoreJS.configure('bootstrap', config);

  // Ability to alter the bootstrap
  CoreJS.emit('bootstrap_config', config);

  CoreJS.configure('environment', appEnv);
  CoreJS.configure('hostname', config.server.host || 'localhost');
  CoreJS.configure('appPath', dir);

  // Configure server
  CoreJS.configure('server', {
    listenPort: config.server.port || 8080,
    multiProcess: config.server.multiProcess || false,
    stayUp: config.server.stayUp || false,
  });

  var events = config.events || {};

  CoreJS.once('pre_init', function(app) {

    // Setup 'environment getter'
    app.__defineGetter__('environment', function() {
      return corejs.environment;
    });

    // Run environment script
    var envFunc = app.require('config/env/' + appEnv);
    envFunc(app);

    // Run environment function from bootstrap
    var bootEnvFunc = config.environments[appEnv];
    if (bootEnvFunc instanceof Function) bootEnvFunc(app);

    // Run bootstrap pre_init event (already on pre_init)
    if (events.pre_init instanceof Function) {
      events.pre_init.call(null, app);
      delete events.pre_init;
    }

    // Run bootstrap events
    for (var evt in events) {
      app.on(evt, events[evt]);
    }

  });

  // Framework singleton
  return new CoreJS();

}

/**
  Configures the corejs.

  @param {string} context
  @param {string|object} value
  @returns {self} for chaining
  @static
 */

CoreJS.configure = function(context, value) {
  this.config[context] = value;
  return this;
}

/**
  Requires a module relative to the corejs's path

  @param {string} module
  @param {boolean} reload
  @returns {object}
  @public
 */

CoreJS.prototype.require = function(module, reload) {
  var Module, oldCache, outModule,
      modulePath = '../' + module;

  if (reload) {
    // Get node's Module
    Module = require('module').Module;

    // Backup original cache
    oldCache = Module._cache;

    // Temporarily empty cache
    Module._cache = {};

    // Get the reloaded module
    try { outModule = require(modulePath); }
    catch(e) { outModule = require(module); }

    // Restore the module cache
    Module._cache = oldCache;

    return outModule;
  } else {
    try { return require(modulePath); }
    catch(e) { return require(module); }
  }
}

/**
  Notifies the application that an asynchronous event has been triggered
 */

CoreJS.prototype.async = function(app) {
  app.asyncQueue.push(1);
}

/**
  Notifies the application that an asynchronous event has finalized

 */

CoreJS.prototype.done = function(app) {
  app.asyncQueue.pop();
  if (app.asyncQueue.length === 0) {
    // Application is initialized on the next tick of event loop,
    // To prevent access errors on objects
    process.nextTick(function() {
      app.initialize();
    });
  }
}

/**
  Deep extend, up to one level

  @param {object} source
  @param {object} destination
  @return {object}
 */

CoreJS.prototype.configExtend = function(base, source) {
  // Extend the base, 1 level deep
  for (var key in base) {
    if (key in source) {
      if (source[key] instanceof Array) {
        base[key] = source[key];
      } else if (source[key] instanceof Object) {
        corejs.extend(base[key], source[key]);
      } else {
        base[key] = source[key];
      }
    }
  }
  return base;
}

/**
  Shortcut for util.inherits

  @param {function} base
  @param {function} parent
  @public
 */

CoreJS.prototype.inherits = function(base, parent) {
  util.inherits(base, this.lib[parent]);
}

/**
  Initializes applications, and configures virtual hosts

  @param {object} servers
  @private
 */

CoreJS.prototype.launchApplication = function(servers) {
  var enumerable = ['className', 'domain', 'path', 'debugLog', 'viewCaching',
      'storage', 'lib','models', 'helpers', 'controllers', 'engines', 'initialized'];

  var host = this.config.hostname,
      path = pathModule.resolve(this.path, this.config.appPath);

  // Enable inheritance within Application
  var Application = corejs.lib.application;

  // Extend the application's prototype
  require(path + '/app.js');

  // Initialize app routes
  this.lib.controller.prototype.queuedRoutes[host] = [];

  // Provide new app prototype
  var app = new Application(host, path);

  // Only set important properties enumerable
  this.util.onlySetEnumerable(app, enumerable);

  // Start the server
  this.startServer();
}

/**
  Starts the application server

  @private
 */

CoreJS.prototype.startServer = function() {

  /*jshint loopfunc:true */

  var app = this.app,
      interProcess = this,
      options = this.config.server,
      allCPUS = os.cpus(),
      bootstrap = corejs.config.bootstrap;

  // Merge config with this.clusterConfig
  options = this.serverOptions = _.extend(this.clusterConfig, options);

  if (typeof options.multiProcess == 'number') {
    allCPUS = (options.multiProcess || 1);
    options.multiProcess = true;
    options.allCPUS = allCPUS;
  } else allCPUS = os.cpus().length;

  // Convenience function, to avoid repetition
  function commonStartupOperations() {
    if (options.stayUp) {
      process.on('uncaughtException', app.log); // prints stack trace
    }
    startupMessage.call(this, options);
  }

  if (options.multiProcess && cluster.isMaster) {

    // Master

    process.title = options.masterProcess;

    for (var worker, i=0; i < allCPUS; i++) {
      worker = cluster.fork();
      worker.on('message', function(data) {
        if (data.cmd != null) interProcess.emit('worker_message', data);
        if (data.response != null) worker.send({response: data.response});
      });
    }

    cluster.on('death', function(worker) {
      app.log('Worker process ' + worker.pid + ' died. Restarting...');
      cluster.fork();
    });

    commonStartupOperations.call(this);
    app.log('Master running...');

  } else {

    // app.server already available on `pre_init` event

    // Worker
    app.server.listen(options.listenPort, app.domain, function() {
      // Server init event
      app.emit('server_init', app.server);
    });

    if (options.multiProcess) {
      process.title = options.workerProcess;
      app.log('Worker running...');
    } else {
      process.title = options.singleProcess;
      commonStartupOperations.call(this);
      autoCurlRequest();
    }

  }
}

/**
  Checks the status of the node inspector

  @private
 */

CoreJS.prototype.checkInspectorStatus = function() {
  var port = this.config.inspector_port || 3000;

  this.util.checkPort(port, function(err) {
    if (err) {
      console.log('Node Inspector is not running.\n\nStart it with `./tools/run-inspector`\n');
      process.exit();
    } else {
      console.log('Node Inspector running on http://0.0.0.0:' + port);
    }
  });

}

/**
  Prints the startup message

  @param {object} options
  @private
 */

function startupMessage(options) {
  var app = this.app;
  if (process.argv.length >= 3 && !options.multiProcess) {
    return; // Disable startup message on curl requests
  }
  app.log(util.format('[%s] Server running on %s', corejs.environment, app.baseUrl));
  if (options.multiProcess) app.log(util.format('Running a cluster of %d workers', options.allCPUS));
  app.emit('startup_message');
}

/**
  Handles automatic curl requests on environments, by passing its command line options for a new request.

  If a relative path is used, the default application's (the first you have defined on the environment) url
  will be used, and the path attached to it.

  An URL can also be used.

  @private
 */

function autoCurlRequest() {
  if (process.argv.length >= 3 && corejs.config.autoCurl) {
    var app = corejs.app,
        config = corejs.config,
        args = process.argv.slice(2),
        url = args[args.length - 1],
        exec = require('child_process').exec,
        portStr = config.server.listenPort !== 80 ? ":" + config.server.listenPort : '';

    if (corejs.regex.startsWithSlash.test(url)) {
      url = "http://" + app.domain + portStr + url;
    }

    var switches = args.slice(0, (args.length - 1)).join(' ');
    var cmd = switches + ' ' + url;

    var cb = function() {
      app.curl(cmd, function(err, buf) {
        console.log(err || buf);
        process.exit(0);
      });
    }

    // Run request when needed
    if (app.initialized) cb();
    else app.on('init', cb);

  }
}

module.exports = CoreJS;
<commit_msg>Fixed reporting of multiple cpus when in cluster mode<commit_after>
/**
  CoreJS

  Configures the corejs, and is in charge of assembling all the applications together.
  Provides the master server that handles and routes all of the virtual host requests.

  Available globally as corejs.
 */

require('./extensions.js');

var _ = require('underscore'),
    events = require('events'),
    net = require('net'),
    child_process = require('child_process'),
    cluster = require('cluster'),
    os = require('os'),
    http = require('http'),
    util = require('util'),
    pathModule = require('path'),
    EventEmitter = events.EventEmitter;

function CoreJS(noserver) {

  var self = this;

  // Initialize `corejs` global
  global.corejs = this;

  // Inherit from constructor
  _.extend(this, this.constructor);

  // Cluster configuration
  this.clusterConfig = {
    listenPort: null,
    multiProcess: 0,
    masterProcess: 'node [master]',
    singleProcess: 'node [single process]',
    workerProcess: 'node worker'
  };

  this.extend = _.extend;

  // Internals
  this.drivers = {};
  this.engines = {};
  this.storages = {};
  this.lib = {};

  // Regular expressions
  this.regex = require('./regex');

  // Instance properties
  this.apps = {};
  this.vhosts = {};
  this.path = pathModule.resolve(__dirname, '../');
  this.className = this.constructor.name;
  this.environment = this.config.environment;

  // Server options, provided by environment
  this.serverOptions = null;

  // Preload Utility
  var Utility = require('./utility'),
      skipFromLibDir = ['request.js', 'response.js', 'corejs.js'];

  this.util = new Utility();

  // Lib
  this.util.getFiles(this.path + '/lib', function(file) {
    var key = file.replace(self.regex.jsFile, '');
    if (skipFromLibDir.indexOf(file) >= 0) return;
    self.lib[key] = require(self.path + '/lib/' + file);
  });

  // Storage
  this.util.getFiles(this.path + '/storages/' , function(file) {
    var key = file.replace(self.regex.jsFile, '');
    self.storages[key] = require(self.path + '/storages/' + file);
  });

  // Database drivers
  this.util.getFiles(this.path + '/drivers', function(file) {
    var key = file.replace(self.regex.jsFile, '');
    self.drivers[key] = require(self.path + '/drivers/' + file);
  });

  // Template engine prototype
  this.engineProto = new this.lib.engine();

  // Template Engines
  this.util.getFiles(this.path + '/engines', function(file) {
    var key = file.replace(self.regex.jsFile, '');
    self.engines[key] = require(self.path + '/engines/' + file);
  });

  // Enhance request/response
  require('./response');
  require('./request');

  // Allow using corejs standalone
  if (noserver) return;

  // Start the debugger if on DEBUG environment
  if (this.config.environment == 'debug') this.checkInspectorStatus();

  // Launch application server
  this.launchApplication();

  // Only set important properties enumerable
  this.util.onlySetEnumerable(this, ['version', 'className', 'environment', 'path', 'config', 'vhosts', 'apps',
    'drivers', 'engines', 'storages']);

  // console.exit(this);
}

// Version
CoreJS.version = require('../package.json').version;

// Stores the configuration settings for the corejs
CoreJS.config = {
  autoCurl: true
};

// Save the Framework's MasterPath, for future reference
CoreJS.path = pathModule.resolve(__dirname, '../');

// Inherit from EventEmitter
CoreJS.__proto__ = new EventEmitter();

/**
  Developers Note: the static properties of the CoreJS constructor are passed
  to the corejs instance on construction. This means, the methods and properties
  available in the CoreJS constructor will also be available in the instance.
 */

/**
  Bootstraps an application

  @param {string} dir
  @param {object} config
  @static
 */

CoreJS.bootstrap = function(dir, config) {

  if (typeof config == 'undefined') {
    throw new Error('Configuration parameter missing');
  }

  ['server', 'environments', 'events'].forEach(function(section) {
    if (!config[section]) config[section] = {};
  });

  var appEnv, envFunc, vhosts = {};

  // Get environment
  appEnv = process.env.NODE_ENV || config.environments.default || 'development';

  // Start node debugger, if on `debug` environment
  if (appEnv == 'debug') {
    console.log('');
    require('child_process').spawn('kill', ['-s', 'SIGUSR1', process.pid]);
    CoreJS.configure('inspector_port', config.server.inspectorPort || 3000);
  }

  // Configure vhosts
  CoreJS.configure('bootstrap', config);

  // Ability to alter the bootstrap
  CoreJS.emit('bootstrap_config', config);

  CoreJS.configure('environment', appEnv);
  CoreJS.configure('hostname', config.server.host || 'localhost');
  CoreJS.configure('appPath', dir);

  // Configure server
  CoreJS.configure('server', {
    listenPort: config.server.port || 8080,
    multiProcess: config.server.multiProcess || false,
    stayUp: config.server.stayUp || false,
  });

  var events = config.events || {};

  CoreJS.once('pre_init', function(app) {

    // Setup 'environment getter'
    app.__defineGetter__('environment', function() {
      return corejs.environment;
    });

    // Run environment script
    var envFunc = app.require('config/env/' + appEnv);
    envFunc(app);

    // Run environment function from bootstrap
    var bootEnvFunc = config.environments[appEnv];
    if (bootEnvFunc instanceof Function) bootEnvFunc(app);

    // Run bootstrap pre_init event (already on pre_init)
    if (events.pre_init instanceof Function) {
      events.pre_init.call(null, app);
      delete events.pre_init;
    }

    // Run bootstrap events
    for (var evt in events) {
      app.on(evt, events[evt]);
    }

  });

  // Framework singleton
  return new CoreJS();

}

/**
  Configures the corejs.

  @param {string} context
  @param {string|object} value
  @returns {self} for chaining
  @static
 */

CoreJS.configure = function(context, value) {
  this.config[context] = value;
  return this;
}

/**
  Requires a module relative to the corejs's path

  @param {string} module
  @param {boolean} reload
  @returns {object}
  @public
 */

CoreJS.prototype.require = function(module, reload) {
  var Module, oldCache, outModule,
      modulePath = '../' + module;

  if (reload) {
    // Get node's Module
    Module = require('module').Module;

    // Backup original cache
    oldCache = Module._cache;

    // Temporarily empty cache
    Module._cache = {};

    // Get the reloaded module
    try { outModule = require(modulePath); }
    catch(e) { outModule = require(module); }

    // Restore the module cache
    Module._cache = oldCache;

    return outModule;
  } else {
    try { return require(modulePath); }
    catch(e) { return require(module); }
  }
}

/**
  Notifies the application that an asynchronous event has been triggered
 */

CoreJS.prototype.async = function(app) {
  app.asyncQueue.push(1);
}

/**
  Notifies the application that an asynchronous event has finalized

 */

CoreJS.prototype.done = function(app) {
  app.asyncQueue.pop();
  if (app.asyncQueue.length === 0) {
    // Application is initialized on the next tick of event loop,
    // To prevent access errors on objects
    process.nextTick(function() {
      app.initialize();
    });
  }
}

/**
  Deep extend, up to one level

  @param {object} source
  @param {object} destination
  @return {object}
 */

CoreJS.prototype.configExtend = function(base, source) {
  // Extend the base, 1 level deep
  for (var key in base) {
    if (key in source) {
      if (source[key] instanceof Array) {
        base[key] = source[key];
      } else if (source[key] instanceof Object) {
        corejs.extend(base[key], source[key]);
      } else {
        base[key] = source[key];
      }
    }
  }
  return base;
}

/**
  Shortcut for util.inherits

  @param {function} base
  @param {function} parent
  @public
 */

CoreJS.prototype.inherits = function(base, parent) {
  util.inherits(base, this.lib[parent]);
}

/**
  Initializes applications, and configures virtual hosts

  @param {object} servers
  @private
 */

CoreJS.prototype.launchApplication = function(servers) {
  var enumerable = ['className', 'domain', 'path', 'debugLog', 'viewCaching',
      'storage', 'lib','models', 'helpers', 'controllers', 'engines', 'initialized'];

  var host = this.config.hostname,
      path = pathModule.resolve(this.path, this.config.appPath);

  // Enable inheritance within Application
  var Application = corejs.lib.application;

  // Extend the application's prototype
  require(path + '/app.js');

  // Initialize app routes
  this.lib.controller.prototype.queuedRoutes[host] = [];

  // Provide new app prototype
  var app = new Application(host, path);

  // Only set important properties enumerable
  this.util.onlySetEnumerable(app, enumerable);

  // Start the server
  this.startServer();
}

/**
  Starts the application server

  @private
 */

CoreJS.prototype.startServer = function() {

  /*jshint loopfunc:true */

  var app = this.app,
      interProcess = this,
      options = this.config.server,
      allCPUS = os.cpus().length,
      bootstrap = corejs.config.bootstrap;

  // Merge config with this.clusterConfig
  options = this.serverOptions = _.extend(this.clusterConfig, options);

  if (typeof options.multiProcess == 'number') {
    allCPUS = (options.multiProcess || 1);
    options.multiProcess = true;
    options.allCPUS = allCPUS;
  } else if (typeof options.multiProcess == 'boolean') {
    options.allCPUS = allCPUS;
  }

  // Convenience function, to avoid repetition
  function commonStartupOperations() {
    if (options.stayUp) {
      process.on('uncaughtException', app.log); // prints stack trace
    }
    startupMessage.call(this, options);
  }

  if (options.multiProcess && cluster.isMaster) {

    // Master

    process.title = options.masterProcess;

    for (var worker, i=0; i < allCPUS; i++) {
      worker = cluster.fork();
      worker.on('message', function(data) {
        if (data.cmd != null) interProcess.emit('worker_message', data);
        if (data.response != null) worker.send({response: data.response});
      });
    }

    cluster.on('death', function(worker) {
      app.log('Worker process ' + worker.pid + ' died. Restarting...');
      cluster.fork();
    });

    commonStartupOperations.call(this);
    app.log('Master running...');

  } else {

    // app.server already available on `pre_init` event

    // Worker
    app.server.listen(options.listenPort, app.domain, function() {
      // Server init event
      app.emit('server_init', app.server);
    });

    if (options.multiProcess) {
      process.title = options.workerProcess;
      app.log('Worker running...');
    } else {
      process.title = options.singleProcess;
      commonStartupOperations.call(this);
      autoCurlRequest();
    }

  }
}

/**
  Checks the status of the node inspector

  @private
 */

CoreJS.prototype.checkInspectorStatus = function() {
  var port = this.config.inspector_port || 3000;

  this.util.checkPort(port, function(err) {
    if (err) {
      console.log('Node Inspector is not running.\n\nStart it with `./tools/run-inspector`\n');
      process.exit();
    } else {
      console.log('Node Inspector running on http://0.0.0.0:' + port);
    }
  });

}

/**
  Prints the startup message

  @param {object} options
  @private
 */

function startupMessage(options) {
  var app = this.app;
  if (process.argv.length >= 3 && !options.multiProcess) {
    return; // Disable startup message on curl requests
  }
  app.log(util.format('[%s] Server running on %s', corejs.environment, app.baseUrl));
  if (options.multiProcess) app.log(util.format('Running a cluster of %d workers', options.allCPUS));
  app.emit('startup_message');
}

/**
  Handles automatic curl requests on environments, by passing its command line options for a new request.

  If a relative path is used, the default application's (the first you have defined on the environment) url
  will be used, and the path attached to it.

  An URL can also be used.

  @private
 */

function autoCurlRequest() {
  if (process.argv.length >= 3 && corejs.config.autoCurl) {
    var app = corejs.app,
        config = corejs.config,
        args = process.argv.slice(2),
        url = args[args.length - 1],
        exec = require('child_process').exec,
        portStr = config.server.listenPort !== 80 ? ":" + config.server.listenPort : '';

    if (corejs.regex.startsWithSlash.test(url)) {
      url = "http://" + app.domain + portStr + url;
    }

    var switches = args.slice(0, (args.length - 1)).join(' ');
    var cmd = switches + ' ' + url;

    var cb = function() {
      app.curl(cmd, function(err, buf) {
        console.log(err || buf);
        process.exit(0);
      });
    }

    // Run request when needed
    if (app.initialized) cb();
    else app.on('init', cb);

  }
}

module.exports = CoreJS;
<|endoftext|>