text:
"use strict";

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

/*jshint -W083 */
(function ($) {
	"use strict";

	$.extendext = function () {
		var options,
		    name,
		    src,
		    copy,
		    copyIsArray,
		    clone,
		    target = arguments[0] || {},
		    i = 1,
		    length = arguments.length,
		    deep = false,
		    arrayMode = 'default';

		// Handle a deep copy situation
		if (typeof target === "boolean") {
			deep = target;

			// Skip the boolean and the target
			target = arguments[i++] || {};
		}

		// Handle array mode parameter
		if (typeof target === "string") {
			arrayMode = target.toLowerCase();
			if (arrayMode !== 'concat' && arrayMode !== 'replace' && arrayMode !== 'extend') {
				arrayMode = 'default';
			}

			// Skip the string param
			target = arguments[i++] || {};
		}

		// Handle case when target is a string or something (possible in deep copy)
		if ((typeof target === "undefined" ? "undefined" : _typeof(target)) !== "object" && !$.isFunction(target)) {
			target = {};
		}

		// Extend jQuery itself if only one argument is passed
		if (i === length) {
			target = this;
			i--;
		}

		for (; i < length; i++) {
			// Only deal with non-null/undefined values
			if ((options = arguments[i]) !== null) {
				// Special operations for arrays
				if ($.isArray(options) && arrayMode !== 'default') {
					clone = target && $.isArray(target) ? target : [];

					switch (arrayMode) {
						case 'concat':
							target = clone.concat($.extend(deep, [], options));
							break;

						case 'replace':
							target = $.extend(deep, [], options);
							break;

						case 'extend':
							options.forEach(function (e, i) {
								if ((typeof e === "undefined" ? "undefined" : _typeof(e)) === 'object') {
									var type = $.isArray(e) ? [] : {};
									clone[i] = $.extendext(deep, arrayMode, clone[i] || type, e);
								} else if (clone.indexOf(e) === -1) {
									clone.push(e);
								}
							});

							target = clone;
							break;
					}
				} else {
					// Extend the base object
					for (name in options) {
						src = target[name];
						copy = options[name];

						// Prevent never-ending loop
						if (target === copy) {
							continue;
						}

						// Recurse if we're merging plain objects or arrays
						if (deep && copy && ($.isPlainObject(copy) || (copyIsArray = $.isArray(copy)))) {

							if (copyIsArray) {
								copyIsArray = false;
								clone = src && $.isArray(src) ? src : [];
							} else {
								clone = src && $.isPlainObject(src) ? src : {};
							}

							// Never move original objects, clone them
							target[name] = $.extendext(deep, arrayMode, clone, copy);

							// Don't bring in undefined values
						} else if (copy !== undefined) {
							target[name] = copy;
						}
					}
				}
			}
		}

		// Return the modified object
		return target;
	};
})(jQuery);
/*!
 * util
 * https://github.com/Voliware/Util
 * Licensed under the MIT license.
 */

/**
 * General utility functions
 */

var Util = function () {
	function Util() {
		_classCallCheck(this, Util);
	}

	_createClass(Util, null, [{
		key: "each",

		/**
   * Wraps a for in loop.
   * For each object it will pass the
   * property name and value to a callback.
   * @param {object} data - data to loop through
   * @param {function} cb - callback
   */
		value: function each(data, cb) {
			for (var i in data) {
				var e = data[i];
				cb(i, e);
			}
		}
	}]);

	return Util;
}();

// helpers

if (typeof isDefined === 'undefined') {
	window.isDefined = function (x) {
		return typeof x !== 'undefined';
	};
}
if (typeof isNull === 'undefined') {
	window.isNull = function (x) {
		return x === null;
	};
}
if (typeof isNullOrUndefined === 'undefined') {
	window.isNullOrUndefined = function (x) {
		return x === null || x === 'undefined';
	};
}
if (typeof isFunction === 'undefined') {
	window.isFunction = function (x) {
		return typeof x === 'function';
	};
}
if (typeof isString === 'undefined') {
	window.isString = function (x) {
		return typeof x === 'string';
	};
}
if (typeof isNumber === 'undefined') {
	window.isNumber = function (x) {
		return typeof x === 'number';
	};
}
if (typeof isObject === 'undefined') {
	window.isObject = function (x) {
		return x !== null && !isArray(x) && (typeof x === "undefined" ? "undefined" : _typeof(x)) === 'object';
	};
}
if (typeof isArray === 'undefined') {
	window.isArray = function (x) {
		return x !== null && Array.isArray(x);
	};
}
if (typeof getType === 'undefined') {
	//http://stackoverflow.com/questions/332422/how-do-i-get-the-name-of-an-objects-type-in-javascript
	window.getType = function (x) {
		if (x === null) return "[object Null]";
		return Object.prototype.toString.call(x);
	};
}
if (typeof createGuid === 'undefined') {
	window.createGuid = function createGuid() {
		function s4() {
			return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);
		}
		return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4();
	};
}

// array
if (typeof Array.diff === 'undefined') {
	Array.diff = function (a, b) {
		return a.filter(function (i) {
			return b.indexOf(i) < 0;
		});
	};
}
if (typeof Array.min === 'undefined') {
	Array.min = function (array) {
		return Math.min.apply(Math, array);
	};
}
if (typeof Array.max === 'undefined') {
	Array.max = function (array) {
		return Math.max.apply(Math, array);
	};
}
if (typeof Object.set === 'undefined') {
	Object.set = function (obj, data) {
		for (var key in data) {
			if (obj.hasOwnProperty(key)) {
				obj[key] = data[key];
			}
		}
	};
}

//https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
if (typeof Object.assign != 'function') {
	Object.assign = function (target) {
		'use strict';

		if (target == null) {
			throw new TypeError('Cannot convert undefined or null to object');
		}

		target = Object(target);
		for (var index = 1; index < arguments.length; index++) {
			var source = arguments[index];
			if (source != null) {
				for (var key in source) {
					if (Object.prototype.hasOwnProperty.call(source, key)) {
						target[key] = source[key];
					}
				}
			}
		}
		return target;
	};
}
/**
 * Deep copy an object (make copies of all its object properties, sub-properties, etc.)
 * An improved version of http://keithdevens.com/weblog/archive/2007/Jun/07/javascript.clone
 * that doesn't break if the constructor has required parameters
 *
 * It also borrows some code from http://stackoverflow.com/a/11621004/560114
 */
function deepCopy(src, /* INTERNAL */_visited, _copiesVisited) {
	if (src === null || (typeof src === "undefined" ? "undefined" : _typeof(src)) !== 'object') {
		return src;
	}

	//Honor native/custom clone methods
	if (typeof src.clone == 'function') {
		return src.clone(true);
	}

	//Special cases:
	//Date
	if (src instanceof Date) {
		return new Date(src.getTime());
	}
	//RegExp
	if (src instanceof RegExp) {
		return new RegExp(src);
	}
	//DOM Element
	if (src.nodeType && typeof src.cloneNode == 'function') {
		return src.cloneNode(true);
	}

	// Initialize the visited objects arrays if needed.
	// This is used to detect cyclic references.
	if (_visited === undefined) {
		_visited = [];
		_copiesVisited = [];
	}

	// Check if this object has already been visited
	var i,
	    len = _visited.length;
	for (i = 0; i < len; i++) {
		// If so, get the copy we already made
		if (src === _visited[i]) {
			return _copiesVisited[i];
		}
	}

	//Array
	if (Object.prototype.toString.call(src) == '[object Array]') {
		//[].slice() by itself would soft clone
		var ret = src.slice();

		//add it to the visited array
		_visited.push(src);
		_copiesVisited.push(ret);

		i = ret.length;
		while (i--) {
			ret[i] = deepCopy(ret[i], _visited, _copiesVisited);
		}
		return ret;
	}

	//If we've reached here, we have a regular object

	//make sure the returned object has the same prototype as the original
	var proto = Object.getPrototypeOf ? Object.getPrototypeOf(src) : src.__proto__;
	if (!proto) {
		proto = src.constructor.prototype; //this line would probably only be reached by very old browsers
	}
	var dest = object_create(proto);

	//add this object to the visited array
	_visited.push(src);
	_copiesVisited.push(dest);

	for (var key in src) {
		//Note: this does NOT preserve ES5 property attributes like 'writable', 'enumerable', etc.
		//For an example of how this could be modified to do so, see the singleMixin() function
		dest[key] = deepCopy(src[key], _visited, _copiesVisited);
	}
	return dest;
}

//If Object.create isn't already defined, we just do the simple shim,
//without the second argument, since that's all we need here
var object_create = Object.create;
if (typeof object_create !== 'function') {
	object_create = function object_create(o) {
		function F() {}
		F.prototype = o;
		return new F();
	};
}
/*!
 * util-jquery
 * https://github.com/Voliware/Util
 * Licensed under the MIT license.
 */

if (!isDefined($)) throw new ReferenceError("util-jquery requires jquery 2.2.2 or greater");

// helpers
if (typeof isJquery === 'undefined') {
	window.isJquery = function (x) {
		return x instanceof $;
	};
}

(function ($) {

	/**
  * Checks if an element has an attribute
  * @param {string} attr - attribute name
  * @returns {boolean} - true if it does, false otherwise
  */
	$.fn.hasAttr = function (attr) {
		return $(this).is('[' + attr + ']');
	};

	/**
  * Populate a DOM object in the appropriate way.
  * Extend with $Util.populate object
  * @param {string|number|jQuery} data
  * @param {boolean} [trigger=true] - whether to call change and input events
  */
	$.fn.populate = function (data) {
		var trigger = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;

		var $this = $(this);

		// don't popualte if data-populate=false
		if ($this.data('populate') === false) return this;

		var tag = $this.prop("tagName").toLowerCase();
		var type = $this.attr('type');

		// populate using extensions or defaults
		var extension = getExtension(tag);
		if (extension) extension.call(this, data);else defaultPopulate(tag, type, data);

		// prevent further populates if update is set to false
		if ($this.data('update') === false) this.attr('data-populate', false);

		// trigger input and change events
		if (trigger) $this.trigger('change').trigger('input');

		return this;

		/**
   * Default populate switch
   * @param {string} tag - element tag
   * @param {string} type - element type
   * @param {*} data - data to populate with
   */
		function defaultPopulate(tag, type, data) {
			switch (tag) {
				case 'input':
					_populateInput(type, data);
					break;
				case 'select':
				case 'textarea':
					$this.val(data);
					break;
				case 'img':
					$this.attr('src', data);
					break;
				case "button":
					$this.prop('disabled', data === 0);
					break;
				default:
					$this.html(data);
					break;
			}
		}

		/**
   * Get the extension for this tag,
   * or for a data-tag attribute
   * @param {string} tag - element tag
   * @returns {function|null}
   */
		function getExtension(tag) {
			if ($Util.populate[tag]) return $Util.populate[tag];
			if ($this.hasAttr('data-tag')) return $Util.populate[$this.attr('data-tag')];
			return null;
		}

		/**
   * Populate an input according to type
   */
		function _populateInput(type, data) {
			switch (type) {
				case "checkbox":
					var checkedValue = $this.data('checked');
					if (data.toString() === checkedValue || data.toString() === "1" || data === true) $this.prop('checked', true);
					break;
				case "radio":
					var dataStr = data.toString();
					$this.filter('[value="' + dataStr + '"]').prop('checked', true);
					break;
				default:
					$this.val(data);
					break;
			}
		}
	};

	/**
  * Populates the children of an object such as a form
  * by matching data keys with DOM elements that have the
  * attribute [data-name="key"] or [name="key"]. Uses
  * $.populate(data) to appropriately fill in the found element.
  * @param {object} data
  * @param {boolean} [trigger=true] - whether to call change and input events
  * @returns {jQuery}
  */
	$.fn.populateChildren = function (data) {
		var trigger = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;

		var $this = $(this);
		$.each(data, function (i, e) {
			var $elInput = $this.find('[name="' + i + '"]');
			var $el = $this.find('[data-name="' + i + '"]');
			if ($elInput.length > 0 && $elInput.data('populate') !== false) $elInput.populate(e, trigger);
			if ($el.length > 0 && $el.data('populate') !== false) $el.populate(e, trigger);
		});
		return this;
	};

	/**
  * Populate an elements attributes by matching
  * data keys with attributes of the same name.
  * @param {object} data
  * @returns {jQuery}
  */
	$.fn.populateAttr = function (data) {
		var $this = $(this);
		$.each(data, function (i, e) {
			$this.attr('i', e);
		});
		return this;
	};

	/**
  * Slide toggle who's first arg is a toggle state
  * @param {boolean} state - true to slide down
  * @param {string} [options=""]
  * @param {function} [cb=null]
  */
	$.fn.slideToggleState = function (state) {
		var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
		var cb = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;

		if (state) $(this).slideDown(options, cb);else $(this).slideUp(options, cb);
		return this;
	};

	/**
  * Append option(s) to a select
  * @param {*} arguments - Either an object of key/value pairs, where the key is the
  * option value and the value is the string within the tags, and a third key is
  * an optional disabled state,
  * or a key and value as two parameters to add one option, with an optional bool
  * for option state
  * @example addToSelect(0, 'Male', true)
  * @example addToSelect(1, 'Female')
  * @example addToSelect({0 : 'Male'}, {1 : 'Female'})
  * @example addToSelect({value : 0, text : 'Male', disabled : true})
  * @example addToSelect({value : 0, text : 'Male', disabled : true}, {value : 1, text : 'Female'})
  * @example addToSelect([{value : 0, text : 'Male'}])
  * @example addToSelect({ female : {value : 1, text : 'Female'}})
  * @returns {jQuery}
  */
	$.fn.addToSelect = function () {
		var $this = $(this);
		if (!$this.is('select')) {
			return this;
		}

		// options always end up in an array
		var options = [];

		// case: multiple arguments
		if (arguments.length > 1) {

			// case: arguments of strings/numbers, single option
			if (isString(arguments[0]) || isNumber(arguments[0])) {
				var disabled = isDefined(arguments[2]) ? arguments[2] : false;
				var option = {
					value: arguments[0],
					text: arguments[1],
					disabled: disabled
				};
				options = [option];
			}
			// case: arguments of multiple objects (comma seperated)
			else {
					if (isObject(arguments[0])) {
						options = arguments;
					}
				}
		}
		// case: single object argument
		else if (isObject(arguments[0])) {
				// case: well formed single object
				if (arguments[0].hasOwnProperty('value')) {
					options = [arguments[0]];
				}
				// case: object of objects
				else if (Object.keys(arguments[0]).length > 1) {
						$.each(arguments[0], function (i, e) {
							// case: objects are named
							if (isObject(e)) {
								options.push(e);
							}
							// case: objects are simple key/values
							else {
									options.push({
										value: i,
										text: e
									});
								}
						});
					}
					// case: single object
					else {
							options = [arguments[0]];
						}
			}
			// case: array of objects
			else if (Array.isArray(arguments[0])) {
					options = arguments[0];
				}

		// add options
		for (var i = 0; i < options.length; i++) {
			var _option = processOption(options[i]);
			var $opt = '<option value="' + _option.value + '"';
			if (_option.disabled) {
				$opt += ' disabled';
			}
			$opt += '>' + _option.text + '</option>';
			$this.append($opt);
		}

		return this;

		/**
   * Process an option ensuring it is formatted correctly
   * @param {object} option
   * @returns {object}
   */
		function processOption(option) {
			if (option.hasOwnProperty('value') === false) {
				var value = Object.keys(option)[0];
				var text = option[value];
				return {
					value: value,
					text: text
				};
			} else {
				return option;
			}
		}
	};

	/**
  * Disable/enable an option/set of options based on value attribute
  * @param {*} [arguments] - Pass a boolean to toggle all options,
  * pass an array and boolean to toggle some options,
  * pass a string and boolean to toggle one option
  * @returns {jQuery}
  */
	$.fn.toggleOption = function () {
		var $this = $(this);
		if (!$this.is('select')) return this;

		var state;
		var value;

		// toggle specific options
		if (arguments.length > 1) {
			value = arguments[0];
			if (!$.isArray(value)) value = [value];

			state = arguments[1];

			for (var i = 0; i < value.length; i++) {
				$this.find('option[value="' + value[i] + '"]').prop('disabled', !state);
			}
		}
		// toggle all <option>s
		else {
				state = arguments[0];
				$this.find('option').prop('disabled', !state);
			}

		return this;
	};
})(jQuery);

/**
 * jQuery utility functions
 */

var $Util = function () {
	function $Util() {
		_classCallCheck(this, $Util);
	}

	_createClass($Util, null, [{
		key: "jQuerify",

		/**
   * Attaches all jQuery functions to a
   * $wrapper property of an object, but
   * always returns the base object
   * @param {*} obj - some object that has a $wrapper property
   * @param {boolean} [override=false] - whether to override any already-named properties
   * @param {jQuery} obj.$wrapper
   */
		value: function jQuerify(obj) {
			var override = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;

			if (!obj.$wrapper) throw new ReferenceError('$Util.jQuerify: $wrapper must be a property of the first argument');

			Util.each($Util.jqueryPrototype, function (i, e) {
				// continue if override is false
				if (isDefined(obj[e]) && !override) return true;

				obj[e] = function () {
					var _obj$$wrapper;

					(_obj$$wrapper = obj.$wrapper)[e].apply(_obj$$wrapper, arguments);
					return obj;
				};
			});
		}

		/**
   * Convenient wrapper for merging defaults
   * and options object with jquery deep $.extend
   * @param {object} defaults - the default settings
   * @param {object} options - set options
   * @param {string} [arrayMode] - optional array mode
      */

	}, {
		key: "opts",
		value: function opts(defaults, options, arrayMode) {
			if (isDefined(arrayMode)) {
				return $.extendext(true, arrayMode, defaults, options);
			} else {
				return $.extend(true, defaults, options);
			}
		}
	}]);

	return $Util;
}();

$Util.jqueryPrototype = Object.getOwnPropertyNames($.prototype);

// extensions for $.fn.populate
// specificy tag name as object name
// and a prop called populate that is a
// function that takes some data argument
$Util.populate = {};
/*!
 * eventSystem
 * https://github.com/Voliware/Util
 * Licensed under the MIT license.
 */

/**
 * Basic event system.
 * Uses the on/off/trigger or emit methods.
 */

var EventSystem = function () {

	/**
  * Constructor
  * @returns {EventSystem}
  */
	function EventSystem() {
		_classCallCheck(this, EventSystem);

		this.events = {};
		return this;
	}

	/**
  * Create an event an object
  * with an array of callbacks
  * @param {string} name - name of the event
  * @returns {{callbacks: Array}}
  * @private
  */

	_createClass(EventSystem, [{
		key: "_createEvent",
		value: function _createEvent(name) {
			return this.events[name] = { callbacks: [] };
		}

		/**
   * Destroy an event
   * @param {string} name - name of the event
   * @returns {EventSystem}
   * @private
   */

	}, {
		key: "_destroy",
		value: function _destroy(name) {
			if (isDefined(this.event[name])) delete this.event[name];
			return this;
		}

		/**
   * Attaches a callback to an event
   * @param {string} name - name of the event
   * @param {function} callback - the callback function
   * @returns {EventSystem}
   */

	}, {
		key: "on",
		value: function on(name, callback) {
			var event = this.events[name];

			if (!isDefined(event)) event = this._createEvent(name);

			event.callbacks.push(callback);
			return this;
		}

		/**
   * Detach a callback from an event.
   * This will only work if the callback is not anonymous
   * @param {string} name - name of the event
   * @param {function} callback - the callback function
   * @returns {EventSystem}
   */

	}, {
		key: "off",
		value: function off(name, callback) {
			var event = this.events[name];

			if (isDefined(event)) {
				var i = event.callbacks.indexOf(callback);
				if (i > -1) event.callbacks.splice(i, 1);
			}
			return this;
		}

		/**
   * Remove all callbacks for an event
   * @param {string} name - name of the event
   * @returns {EventSystem}
   */

	}, {
		key: "offAll",
		value: function offAll(name) {
			var event = this.events[name];

			if (isDefined(event)) event[name].callbacks = [];

			return this;
		}

		/**
   * Run all callbacks attached to an event
   * @returns {EventSystem}
   */

	}, {
		key: "trigger",
		value: function trigger() {
			// grab the name of the event and remove it from arguments
			var shift = [].shift;
			var name = shift.apply(arguments);
			var event = this.events[name];

			// there's no need to trigger if no one is listening
			if (!isDefined(event)) return this;

			for (var i = 0; i < event.callbacks.length; i++) {
				var _event$callbacks;

				(_event$callbacks = event.callbacks)[i].apply(_event$callbacks, arguments);
			}
			return this;
		}

		/**
   * Alias to trigger method
   * @returns {EventSystem}
   */

	}, {
		key: "emit",
		value: function emit() {
			return this.trigger();
		}
	}]);

	return EventSystem;
}();
/*!
 * manager
 * https://github.com/Voliware/Util
 * Licensed under the MIT license.
 */

if (!isDefined(EventSystem)) throw new ReferenceError("Manager requires EventSystem");

/**
 * Generic object manager.
 * Adds/updates/deletes objects in a collection.
 * Can accept an array or object of
 * data and determine which objects
 * are new, old, or no longer exist
 * @extends EventSystem
 */

var Manager = function (_EventSystem) {
	_inherits(Manager, _EventSystem);

	/**
  * Constructor
  * @param {object} [options]
  * @param {string} [options.identifier='id'] - the property name that identifies
  * each object, which is a property of each object, managed by this manager
  * @param {boolean} [options.useObjectNames=false] - whether to use the names
  * of objects passed to manage() as their object identifiers
  * @returns {Manager}
  */
	function Manager(options) {
		var _ret;

		_classCallCheck(this, Manager);

		var _this = _possibleConstructorReturn(this, (Manager.__proto__ || Object.getPrototypeOf(Manager)).call(this));

		var defaults = {
			// to manage objects, they must have
			// a unique id before they get to Manager.
			// this is their id property name
			identifier: 'id',
			// OR instead of using an identifier,
			// use the name of the object.
			// this only works when passing
			// objects of objects to manage()
			useObjectNames: false,
			// max number of objs to manage
			max: 0
		};
		_this.settings = Object.assign(defaults, options);

		// all child classes will use
		// a more friendly name for objects
		// so any mutations must be done
		// to the object itself, not this ref
		_this.objects = {};
		_this.count = 0;

		// cached and processed data passed to manage()
		_this._cachedData = {};
		_this._processedData = {};
		// last serialized collection
		_this.serializedObjects = [];
		// a flag that is set to true when the add/edit/delete
		// functions are called, to indicate that the
		// previously serialized data is now old
		_this.requiresNewSerialize = false;

		return _ret = _this, _possibleConstructorReturn(_this, _ret);
	}

	/**
  * Check if an object exists in the collection
  * @param {...(number|object|string)} arguments - the object or the id of the object
  * @returns {boolean}
  * @private
  */

	_createClass(Manager, [{
		key: "_exists",
		value: function _exists() {
			var arg = arguments[0];
			if (isString(arg) || isNumber(arg)) return isDefined(this.objects[arg]);else return isDefined(this.objects[arg[this.settings.identifier]]);
		}

		/**
   * Get an object in the managed collection
   * by id (string/number) or by an object's
   * property as set in this.settings.identifier
   * @param {...(number|object|string)} arguments - the object or the id of the object
   * @returns {*|null}
   * @private
   */

	}, {
		key: "_get",
		value: function _get() {
			var arg = arguments[0];
			var obj = null;
			var identifier = this.settings.identifier;

			// an object id was passed
			if (isString(arg) || isNumber(arg)) {
				String(arg);
				if (this.objects[arg]) obj = this.objects[arg];
			}
			// an object was passed
			else if (this.objects[arg[identifier]]) {
					obj = this.objects[arg[identifier]];
				}

			return obj;
		}

		/**
   * Adds an object to the collection.
   * Replaces any existing object with the same identifier.
   * @param {object} obj - the object to add
   * @param {string} [id] - the id of the object
   * @returns {*}
   * @private
   */

	}, {
		key: "_add",
		value: function _add(obj, id) {
			var self = this;
			var identifier = this.settings.identifier;

			// if an id is passed, add it to
			// the object as the identifier property
			if (isDefined(id)) {
				String(id);
				obj[identifier] = id;
				this.objects[id] = obj;
				postAdd();
			}
			// if no id is passed, check that it has
			// an identifier property already
			else if (!isNullOrUndefined(obj[identifier])) {
					this.objects[obj[identifier]] = obj;
					postAdd();
				}
				// otherwise, it cannot be managed
				else {
						console.warn('Manager._add: cannot add an object with no identifier');
					}

			return obj;

			/**
    * After a successful add, trigger
    * the event and increase the counter
    */
			function postAdd() {
				self.requiresNewSerialize = true;
				self.trigger('add', obj);
				self.count++;
				obj._count = self.count;
			}
		}

		/**
   * Replaces or adds an object
   * @param {object} obj - the object to update
   * @param {string} [id] - the id of the object
   * @returns {*}
   * @private
   */

	}, {
		key: "_update",
		value: function _update(obj, id) {
			var self = this;
			var identifier = this.settings.identifier;

			if (isDefined(id)) {
				String(id);
				this.objects[id] = obj;
				postUpdate();
			} else if (!isNullOrUndefined(obj[identifier])) {
				this.objects[obj[identifier]] = obj;
				postUpdate();
			} else {
				console.warn('Manager._update: cannot update an object with no identifier');
			}

			return obj;

			/**
    * After a successful update, trigger
    * the event and reset the serialize flag
    */
			function postUpdate() {
				self.requiresNewSerialize = true;
				self.trigger('update', obj);
				self.count++;
				obj._count = self.count;
			}
		}

		/**
   * Deletes an object from the collection
   * @param {...(number|object|string)} arguments - the object or the id of the object
   * @returns {Manager}
   * @private
   */

	}, {
		key: "_delete",
		value: function _delete() {
			var arg = arguments[0];
			var obj = null;
			var identifier = this.settings.identifier;

			obj = this._get.apply(this, arguments);

			if (obj) {
				var id = obj[identifier];
				this.trigger('delete', id);
				delete this.objects[id];
				this.requiresNewSerialize = true;
				if (this.count > 0) this.count--;
			} else {
				console.error('Manager._delete: cannot delete an object with no identifier');
			}

			return this;
		}

		/**
   * Deletes all objects from the collection
   * @returns {Manager}
   * @private
   */

	}, {
		key: "_empty",
		value: function _empty() {
			// ..in likely case there are references
			for (var i in this.objects) {
				delete this.objects[i];
			}
			return this;
		}

		/**
   * Cache data
   * @param {*} data
   * @returns {Manager}
   * @private
   */

	}, {
		key: "_cacheData",
		value: function _cacheData(data) {
			this._cachedData = deepCopy(data);
			return this;
		}

		/**
   * Process all incoming data to manage
   * @param {object} data
   * @returns {Manager}
   * @private
   */

	}, {
		key: "_processData",
		value: function _processData(data) {
			this._processedData = deepCopy(data);
			return this;
		}

		/**
   * Get the ids of all objects
   * @returns {string[]}
   */

	}, {
		key: "getIds",
		value: function getIds() {
			var ids = [];
			for (var i in this.objects) {
				var id = this.getId(this.objects[i]);
				ids.push(id);
			}
			return ids;
		}

		/**
   * Get the id of an object
   * @param {object} obj
   * @returns {string|undefined}
   */

	}, {
		key: "getId",
		value: function getId(obj) {
			return obj[this.settings.identifier].toString();
		}

		/**
   * Given a collection of objects in an array,
   * or in an object, add and update them
   * in the manager's own collection.
   * Then delete any objects still in the manager's
   * collection that are not in the data
   * @param {object|object[]} data
   * @returns {Manager}
   */

	}, {
		key: "manage",
		value: function manage(data) {
			this._cacheData(data);
			this._processData(data);

			if (!isObject(this._processedData) && this.settings.useObjectNames) throw new Error("Manager.manage: to use option useObjectNames, object passed to manage() must be an object.");

			var self = this;
			var id = this.settings.identifier;
			// maintain an array of ids found in data
			// then xreference this to see which objects
			// no longer exist (data is the master here)
			var dataIds = [];

			// add or update objects
			for (var i in this._processedData) {
				var e = this._processedData[i];

				if (this.settings.useObjectNames) e[id] = i;

				// ids must be defined within objects
				// there is no other way to know if an
				// object is new or old
				if (!isDefined(e[id])) return console.error("Manager.manage: cannot manage objects with no ids");

				// objectIds will always be strings
				var objId = e[id].toString();
				var obj = self.objects[objId];
				if (isDefined(obj)) self._update(e);else self._add(e);
				dataIds.push(objId);
			}

			// diff the array of object ids
			// with the array of data ids
			var objectIds = this.getIds();
			var diff = Array.diff(objectIds, dataIds);

			// delete any objects that are
			// no longer found in data
			for (i = 0; i < diff.length; i++) {
				this._delete(diff[i]);
			}

			return this;
		}

		/**
   * Public method to see if an object exists
   * @returns {boolean}
   */

	}, {
		key: "exists",
		value: function exists() {
			return this._exists.apply(this, arguments);
		}

		/**
   * Add many objects to the collection
   * @param {...object} arguments - one or more objects
   * @returns {Manager}
   */

	}, {
		key: "addObjects",
		value: function addObjects() {
			var data = arguments.length > 1 ? [].slice.call(arguments).sort() : arguments[0];
			for (var i in data) {
				var e = data[i];
				this.addObject(e);
			}
			return this;
		}

		/**
   * Public method to add an object
   * @returns {*}
   */

	}, {
		key: "addObject",
		value: function addObject() {
			return this._add.apply(this, arguments);
		}

		/**
   * Public method to get an object
   * @returns {*}
   */

	}, {
		key: "getObject",
		value: function getObject() {
			return this._get.apply(this, arguments);
		}

		/**
   * Public method to update an object
   * @returns {*}
   */

	}, {
		key: "updateObject",
		value: function updateObject() {
			return this._update.apply(this, arguments);
		}

		/**
   * Public method to delete an object
   * @returns {*}
   */

	}, {
		key: "deleteObject",
		value: function deleteObject() {
			return this._delete.apply(this, arguments);
		}

		/**
   * Public method to delete all objects
   * @returns {*}
   */

	}, {
		key: "deleteObjects",
		value: function deleteObjects() {
			return this._empty();
		}

		/**
   * Serialize all objects that have a serializer method
   * @param {number} [index=0] - index to start at
   * @param {number} [max=0] - max amount to return
   * @returns {object[]}
   */

	}, {
		key: "serializer",
		value: function serializer() {
			var index = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
			var max = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;

			if (this.requiresNewSerialize) {
				var self = this;
				this.serializedObjects = [];
				$.each(this.objects, function (i, e) {
					if (e.serializer) self.serializedObjects.push(e.serializer());
				});
				this.requiresNewSerialize = false;
			}

			max = max > 0 ? max : this.serializedObjects.length;
			return this.serializedObjects.slice(index, max);
		}
	}]);

	return Manager;
}(EventSystem);

/*!
 * pool
 * https://github.com/Voliware/Util
 * Licensed under the MIT license.
 */

/**
 * Generic object pool for
 * limiting memory usage
 */

var Pool = function () {

	/**
  * Constructor
  * @param {*} object - object to alloc in the pool
  * @returns {Pool}
  */
	function Pool(object) {
		_classCallCheck(this, Pool);

		this.object = object;

		this.totalAlloc = 0;
		this.totalFree = 0;
		this.pool = [];
		return this;
	}

	/**
  * Clear pool totalAlloc and totalFree
  * @returns {Pool}
  * @private
  */

	_createClass(Pool, [{
		key: "_clearStats",
		value: function _clearStats() {
			var inUse = this.totalAlloc - this.totalFree;
			this.totalAlloc = inUse || 0;
			this.totalFree = 0;
			return this;
		}

		/**
   * Allocate space in the pool
   * @returns {*}
   */

	}, {
		key: "alloc",
		value: function alloc() {
			var obj;
			if (this.pool.length === 0) {
				obj = new this.object();
				this.totalAlloc++;
			} else {
				obj = this.pool.pop();
				this.totalFree--;
			}
			return obj;
		}

		/**
   * Free space in the pool by
   * returning an object to it
   * @param {*} obj
   * @returns {Pool}
   */

	}, {
		key: "free",
		value: function free(obj) {
			this.pool.push(obj);
			this.totalFree++;
			return this;
		}

		/**
   * Collect all objects in the pool
   * and clear current stats
   * @returns {Pool}
   */

	}, {
		key: "collect",
		value: function collect() {
			this.pool = [];
			this._clearStats();
			return this;
		}
	}]);

	return Pool;
}();


text:
import moment from 'moment';

import computeFn from '../utils/helper-compute';
import BaseHelper from './-base';

export default BaseHelper.extend({
  globalAllowEmpty: false,

  compute: computeFn(function(params, { hidePrefix, locale, timeZone }) {
    this._super(...arguments);

    return this.morphMoment(moment(...params), { locale, timeZone }).toNow(hidePrefix);
  })
});

redpajama_set_name: RedPajamaGithub


text:
namespace net {
class URLRequestContextGetter;
}

class GoogleServiceAuthError;
class SigninClient;

// ProfileOAuth2TokenService is a KeyedService that retrieves
// OAuth2 access tokens for a given set of scopes using the OAuth2 login
// refresh tokens.
//
// See |OAuth2TokenService| for usage details.
//
// Note: after StartRequest returns, in-flight requests will continue
// even if the TokenService refresh token that was used to initiate
// the request changes or is cleared.  When the request completes,
// Consumer::OnGetTokenSuccess will be invoked, but the access token
// won't be cached.
//
// Note: requests should be started from the UI thread. To start a
// request from other thread, please use OAuth2TokenServiceRequest.
class ProfileOAuth2TokenService : public OAuth2TokenService,
                                  public KeyedService {
 public:
  virtual ~ProfileOAuth2TokenService();

  // Initializes this token service with the SigninClient.
  virtual void Initialize(SigninClient* client);

  // KeyedService implementation.
  virtual void Shutdown() OVERRIDE;

  // Lists account IDs of all accounts with a refresh token.
  virtual std::vector<std::string> GetAccounts() OVERRIDE;

  // Loads credentials from a backing persistent store to make them available
  // after service is used between profile restarts.
  //
  // Only call this method if there is at least one account connected to the
  // profile, otherwise startup will cause unneeded work on the IO thread.  The
  // primary account is specified with the |primary_account_id| argument and
  // should not be empty.  For a regular profile, the primary account id comes
  // from SigninManager.  For a managed account, the id comes from
  // ManagedUserService.
  virtual void LoadCredentials(const std::string& primary_account_id);

  // Updates a |refresh_token| for an |account_id|. Credentials are persisted,
  // and available through |LoadCredentials| after service is restarted.
  virtual void UpdateCredentials(const std::string& account_id,
                                 const std::string& refresh_token);

  // Revokes all credentials handled by the object.
  virtual void RevokeAllCredentials();

  SigninErrorController* signin_error_controller() {
    return signin_error_controller_.get();
  }

  const SigninErrorController* signin_error_controller() const {
    return signin_error_controller_.get();
  }

  SigninClient* client() const { return client_; }

 protected:
  ProfileOAuth2TokenService();

  // OAuth2TokenService overrides.
  // Note: These methods are overriden so that ProfileOAuth2TokenService is a
  // concrete class.

  // Simply returns NULL and should be overriden by subsclasses.
  virtual net::URLRequestContextGetter* GetRequestContext() OVERRIDE;

  // Updates the internal cache of the result from the most-recently-completed
  // auth request (used for reporting errors to the user).
  virtual void UpdateAuthError(
      const std::string& account_id,
      const GoogleServiceAuthError& error) OVERRIDE;

 private:
  // The client with which this instance was initialized, or NULL.
  SigninClient* client_;

  // Used to expose auth errors to the UI.
  scoped_ptr<SigninErrorController> signin_error_controller_;

  DISALLOW_COPY_AND_ASSIGN(ProfileOAuth2TokenService);
};

#endif  // COMPONENTS_SIGNIN_CORE_BROWSER_PROFILE_OAUTH2_TOKEN_SERVICE_H_


text:
package com.milaboratory.core.io.sequence.fastq;

import com.milaboratory.core.io.CompressionType;
import com.milaboratory.core.io.sequence.SingleRead;
import com.milaboratory.core.io.sequence.SingleSequenceWriter;
import com.milaboratory.core.sequence.NucleotideAlphabet;
import com.milaboratory.core.sequence.NucleotideSequence;
import com.milaboratory.core.sequence.SequenceQuality;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

public final class SingleFastqWriter implements SingleSequenceWriter {
    public static final int DEFAULT_BUFFER_SIZE = 131072;
    final OutputStream outputStream;
    final QualityFormat qualityFormat;
    final byte[] buffer;
    int pointer;

    public SingleFastqWriter(String fileName) throws IOException {
        this(new FileOutputStream(fileName), QualityFormat.Phred33, CompressionType.detectCompressionType(fileName), DEFAULT_BUFFER_SIZE);
    }

    public SingleFastqWriter(File file) throws IOException {
        this(new FileOutputStream(file), QualityFormat.Phred33, CompressionType.detectCompressionType(file), DEFAULT_BUFFER_SIZE);
    }

    public SingleFastqWriter(OutputStream outputStream) throws IOException {
        this(outputStream, QualityFormat.Phred33, CompressionType.None, DEFAULT_BUFFER_SIZE);
    }

    public SingleFastqWriter(File file, QualityFormat qualityFormat, CompressionType ct) throws IOException {
        this(new FileOutputStream(file), qualityFormat, ct, DEFAULT_BUFFER_SIZE);
    }

    public SingleFastqWriter(String fileName, QualityFormat qualityFormat, CompressionType ct) throws IOException {
        this(new FileOutputStream(fileName), qualityFormat, ct, DEFAULT_BUFFER_SIZE);
    }

    public SingleFastqWriter(OutputStream outputStream, QualityFormat qualityFormat, CompressionType ct) throws IOException {
        this(outputStream, qualityFormat, ct, DEFAULT_BUFFER_SIZE);
    }

    public SingleFastqWriter(OutputStream outputStream, QualityFormat qualityFormat, CompressionType ct, int bufferSize) throws IOException {
        this.outputStream = ct.createOutputStream(outputStream, bufferSize / 2);
        this.qualityFormat = qualityFormat;
        this.buffer = new byte[bufferSize];
    }

    @Override
    public synchronized void write(SingleRead read) {
        String description = read.getDescription();
        int len = description.length();
        flushIfNeededToWrite(len + 1);
        buffer[pointer++] = '@';
        for (int i = 0; i < len; ++i)
            buffer[pointer++] = (byte) description.charAt(i);

        NucleotideSequence sequence = read.getData().getSequence();
        SequenceQuality quality = read.getData().getQuality();

        len = sequence.size();

        flushIfNeededToWrite(len + 2);

        buffer[pointer++] = '\n';

        for (int i = 0; i < len; ++i)
            buffer[pointer++] = NucleotideAlphabet.symbolByteFromCode(sequence.codeAt(i));

        buffer[pointer++] = '\n';

        flushIfNeededToWrite(len + 3);

        buffer[pointer++] = '+';
        buffer[pointer++] = '\n';

        quality.encodeTo(qualityFormat, buffer, pointer);
        pointer += len;

        buffer[pointer++] = '\n';
    }

    private void flushIfNeededToWrite(int sizeToWrite) {
        if (buffer.length - pointer < sizeToWrite)
            flush();
    }

    @Override
    public void flush() {
        try {
            outputStream.write(buffer, 0, pointer);
            pointer = 0;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void close() {
        try {
            flush();
            outputStream.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}


text:
package mbus_test

import (
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"

	"github.com/cloudfoundry/yagnats"
	"github.com/cloudfoundry/yagnats/fakeyagnats"

	boshhandler "github.com/cloudfoundry/bosh-agent/handler"
	boshlog "github.com/cloudfoundry/bosh-agent/logger"
	. "github.com/cloudfoundry/bosh-agent/mbus"
	boshsettings "github.com/cloudfoundry/bosh-agent/settings"
	fakesettings "github.com/cloudfoundry/bosh-agent/settings/fakes"
)

func init() {
	Describe("natsHandler", func() {
		var (
			settingsService *fakesettings.FakeSettingsService
			client          *fakeyagnats.FakeYagnats
			logger          boshlog.Logger
			handler         boshhandler.Handler
		)

		BeforeEach(func() {
			settingsService = &fakesettings.FakeSettingsService{
				Settings: boshsettings.Settings{
					AgentID: "my-agent-id",
					Mbus:    "nats://fake-username:fake-password@127.0.0.1:1234",
				},
			}
			logger = boshlog.NewLogger(boshlog.LevelNone)
			client = fakeyagnats.New()
			handler = NewNatsHandler(settingsService, client, logger)
		})

		Describe("Start", func() {
			It("starts", func() {
				var receivedRequest boshhandler.Request

				handler.Start(func(req boshhandler.Request) (resp boshhandler.Response) {
					receivedRequest = req
					return boshhandler.NewValueResponse("expected value")
				})
				defer handler.Stop()

				Expect(client.ConnectedConnectionProvider()).ToNot(BeNil())

				Expect(client.SubscriptionCount()).To(Equal(1))
				subscriptions := client.Subscriptions("agent.my-agent-id")
				Expect(len(subscriptions)).To(Equal(1))

				expectedPayload := []byte(`{"method":"ping","arguments":["foo","bar"], "reply_to": "reply to me!"}`)
				subscription := subscriptions[0]
				subscription.Callback(&yagnats.Message{
					Subject: "agent.my-agent-id",
					Payload: expectedPayload,
				})

				Expect(receivedRequest).To(Equal(boshhandler.Request{
					ReplyTo: "reply to me!",
					Method:  "ping",
					Payload: expectedPayload,
				}))

				Expect(client.PublishedMessageCount()).To(Equal(1))
				messages := client.PublishedMessages("reply to me!")
				Expect(len(messages)).To(Equal(1))
				Expect(messages[0].Payload).To(Equal([]byte(`{"value":"expected value"}`)))
			})

			It("does not respond if the response is nil", func() {
				err := handler.Start(func(req boshhandler.Request) (resp boshhandler.Response) {
					return nil
				})
				Expect(err).ToNot(HaveOccurred())
				defer handler.Stop()

				subscription := client.Subscriptions("agent.my-agent-id")[0]
				subscription.Callback(&yagnats.Message{
					Subject: "agent.my-agent-id",
					Payload: []byte(`{"method":"ping","arguments":["foo","bar"], "reply_to": "reply to me!"}`),
				})

				Expect(client.PublishedMessageCount()).To(Equal(0))
			})

			It("responds with an error if the response is bigger than 1MB", func() {
				err := handler.Start(func(req boshhandler.Request) (resp boshhandler.Response) {
					// gets inflated by json.Marshal when enveloping
					size := 0

					switch req.Method {
					case "small":
						size = 1024*1024 - 12
					case "big":
						size = 1024 * 1024
					default:
						panic("unknown request size")
					}

					chars := make([]byte, size)
					for i := range chars {
						chars[i] = 'A'
					}
					return boshhandler.NewValueResponse(string(chars))
				})
				Expect(err).ToNot(HaveOccurred())
				defer handler.Stop()

				subscription := client.Subscriptions("agent.my-agent-id")[0]
				subscription.Callback(&yagnats.Message{
					Subject: "agent.my-agent-id",
					Payload: []byte(`{"method":"small","arguments":[], "reply_to": "fake-reply-to"}`),
				})

				subscription.Callback(&yagnats.Message{
					Subject: "agent.my-agent-id",
					Payload: []byte(`{"method":"big","arguments":[], "reply_to": "fake-reply-to"}`),
				})

				Expect(client.PublishedMessageCount()).To(Equal(1))
				messages := client.PublishedMessages("fake-reply-to")
				Expect(len(messages)).To(Equal(2))
				Expect(messages[0].Payload).To(MatchRegexp("value"))
				Expect(messages[1].Payload).To(Equal([]byte(
					`{"exception":{"message":"Response exceeded maximum allowed length"}}`)))
			})

			It("can add additional handler funcs to receive requests", func() {
				var firstHandlerReq, secondHandlerRequest boshhandler.Request

				handler.Start(func(req boshhandler.Request) (resp boshhandler.Response) {
					firstHandlerReq = req
					return boshhandler.NewValueResponse("first-handler-resp")
				})
				defer handler.Stop()

				handler.RegisterAdditionalFunc(func(req boshhandler.Request) (resp boshhandler.Response) {
					secondHandlerRequest = req
					return boshhandler.NewValueResponse("second-handler-resp")
				})

				expectedPayload := []byte(`{"method":"ping","arguments":["foo","bar"], "reply_to": "fake-reply-to"}`)

				subscription := client.Subscriptions("agent.my-agent-id")[0]
				subscription.Callback(&yagnats.Message{
					Subject: "agent.my-agent-id",
					Payload: expectedPayload,
				})

				// Expected requests received by both handlers
				Expect(firstHandlerReq).To(Equal(boshhandler.Request{
					ReplyTo: "fake-reply-to",
					Method:  "ping",
					Payload: expectedPayload,
				}))

				Expect(secondHandlerRequest).To(Equal(boshhandler.Request{
					ReplyTo: "fake-reply-to",
					Method:  "ping",
					Payload: expectedPayload,
				}))

				// Bosh handler responses were sent
				Expect(client.PublishedMessageCount()).To(Equal(1))
				messages := client.PublishedMessages("fake-reply-to")
				Expect(len(messages)).To(Equal(2))
				Expect(messages[0].Payload).To(Equal([]byte(`{"value":"first-handler-resp"}`)))
				Expect(messages[1].Payload).To(Equal([]byte(`{"value":"second-handler-resp"}`)))
			})

			It("has the correct connection info", func() {
				err := handler.Start(func(req boshhandler.Request) (res boshhandler.Response) { return })
				Expect(err).ToNot(HaveOccurred())
				defer handler.Stop()

				Expect(client.ConnectedConnectionProvider()).To(Equal(&yagnats.ConnectionInfo{
					Addr:     "127.0.0.1:1234",
					Username: "fake-username",
					Password: "fake-password",
				}))
			})

			It("does not err when no username and password", func() {
				settingsService.Settings.Mbus = "nats://127.0.0.1:1234"
				handler = NewNatsHandler(settingsService, client, logger)

				err := handler.Start(func(req boshhandler.Request) (res boshhandler.Response) { return })
				Expect(err).ToNot(HaveOccurred())
				defer handler.Stop()
			})

			It("errs when has username without password", func() {
				settingsService.Settings.Mbus = "nats://foo@127.0.0.1:1234"
				handler = NewNatsHandler(settingsService, client, logger)

				err := handler.Start(func(req boshhandler.Request) (res boshhandler.Response) { return })
				Expect(err).To(HaveOccurred())
				defer handler.Stop()
			})
		})

		Describe("Send", func() {
			It("sends the message over nats to a subject that includes the target and topic", func() {
				errCh := make(chan error, 1)

				payload := map[string]string{"key1": "value1", "keyA": "valueA"}

				go func() {
					errCh <- handler.Send(boshhandler.HealthMonitor, boshhandler.Heartbeat, payload)
				}()

				var err error
				select {
				case err = <-errCh:
				}
				Expect(err).ToNot(HaveOccurred())

				Expect(client.PublishedMessageCount()).To(Equal(1))
				messages := client.PublishedMessages("hm.agent.heartbeat.my-agent-id")
				Expect(messages).To(HaveLen(1))
				Expect(messages[0].Payload).To(Equal(
					[]byte("{\"key1\":\"value1\",\"keyA\":\"valueA\"}"),
				))
			})
		})
	})
}


text:
class GameRow extends React.Component { // eslint-disable-line no-unused-vars
    constructor(props) {
        super(props);
    }

    render() {
        // look up more about how this works!
        const rowItems = this.props.rowArray.map((item, index) =>
            // Correct! Key should be specified inside the array.
            <GameRowItem key={index.toString()} value={item} setSelectedSpace={this.props.setSelectedSpace}/>
        );

        return (
            <tr>
                {rowItems}
            </tr>
        );
    }
}


text:
using Microsoft.Extensions.Logging;

namespace Orchard.ContentManagement.Handlers
{
    public class ContentItemMetadataContext
    {
        public ContentItem ContentItem { get; set; }
        public ContentItemMetadata Metadata { get; set; }
    }
}


text:
@extends('layouts.siggy')

@section('content')
@include('siggy.activities.search')
@include('siggy.activities.thera')
@include('siggy.activities.scanned_systems')
@include('siggy.activities.notifications')
@include('siggy.activities.astrolabe')
@include('siggy.activities.chainmap')
@include('siggy.activities.notes')
@include('siggy.activities.dscan')
@include('siggy.activities.timerboard')

	@if(count($reconnectRequired) > 0)

Please reconnect your characters

			One or more of your connected characters has to be reconnected. This is due to switching to ESI for ship info and location.
			If you had previously connected your character and it gave the ESI scopes, you must reconnect for siggy to now gain the new "online" status scope.

			Affected characters:

			@foreach($reconnectRequired as $ssoChar)

{{$ssoChar->character->name}}

			@endforeach

			If you fail to reconnect your characters, they will eventually stop appearing on the map.

			Please go to the Connected Characters page and click the "Reconnect characters" button on each character for siggy new permissions for each character.

			Go to Connected Characters

	@endif

No chain-maps configured

			Your group administrators have not configured chain-maps for your corporation or character. Please contact them to fix this.

	@include('siggy.chainmap')

                <?php echo !empty($systemName) ? $systemName : 'System'; ?>

Extra

Scan

Intel

<?php echo __('Options'); ?>

				@include('siggy/displaygroups/poses')
				@include('siggy/displaygroups/dscan')
				@include('siggy/displaygroups/structures')

	                    Planets/Moons/Belts

	                    Radius

	                    True Sec

	                    {{ __('Constellation') }}

Carebearing

	                        C1 |
	                        C2 |
	                        C3 |
	                        C4 |
	                        C5 |
	                        C6

Cosmic Anomaly

	                            Perimeter Ambush Point

	                            Perimeter Camp

	                            Phase Catalyst Node

	                            The Line

Magnetometric

	                            Forgotten Perimeter Coronation Platform

	                            Forgotten Perimeter Power Array

Radar

	                            Unsecured Perimeter Amplifier

	                            Unsecured Perimeter Information Center

Cosmic Anomaly

	                            Perimeter Checkpoint

	                            Perimeter Hangar

	                            The Ruins of Enclave Cohort 27

	                            Sleeper Data Sanctuary

Magnetometric

	                            Forgotten Perimeter Gateway

	                            Forgotten Perimeter Habitation Coils

Radar

	                            Unsecured Perimeter Comms Relay

	                            Unsecured Perimeter Transponder Farm

Cosmic Anomaly

	                            Fortification Frontier Stronghold

	                            Outpost Frontier Stronghold

	                            Solar Cell

	                            The Oruze Construct

Magnetometric

	                            Forgotten Frontier Quarantine Outpost

	                            Forgotten Frontier Recursive Depot

Radar

	                            Unsecured Frontier Database

	                            Unsecured Frontier Receiver

Cosmic Anomaly

	                            Frontier Barracks

	                            Frontier Command Post

	                            Integrated Terminus

	                            Sleeper Information Sanctum

Magnetometric

	                            Forgotten Frontier Conversion Module

	                            Forgotten Frontier Evacuation Center

Radar

	                            Unsecured Frontier Digital Nexus

	                            Unsecured Frontier Trinary Hub

Cosmic Anomaly

	                            Core Garrison

	                            Core Stronghold

	                            Oruze Osobnyk

	                            Quarantine Area

Magnetometric

	                            Forgotten Core Data Field

	                            Forgotten Core Information Pen

Radar

	                            Unsecured Frontier Enclave Relay

	                            Unsecured Frontier Server Bank

Cosmic Anomaly

	                            Core Citadel

	                            Core Bastion

	                            Strange Energy Readings

	                            The Mirror

Magnetometric

	                            Forgotten Core Assembly Hall

	                            Forgotten Core Circuitry Disassembler

Radar

	                            Unsecured Core Backup Array

	                            Unsecured Core Emergence

* All links open a new tab to eve-survival

	                    System label/display name
This is completely optional and displays a custom name in the system list for easy identification of chained systems

	                    <input type="text" name="label"  class="siggy-input" />

	                    Activity Level

	                    <select name='activity' class="siggy-input">
	                        <option value='0'>Don't Know</option>
	                        <option value='1'>Empty</option>
	                        <option value='2'>Occupied</option>
	                        <option value='3'>Active</option>
	                        <option value='4'>Friendly</option>
	                    </select>

	                        <button id="system-options-reset" type="reset" class="btn btn-default">Reset</button>
	                        <button id="system-options-save" class="btn btn-primary">Save</button>

	                    Region / {{ __('Constellation') }}

	                    System Effect

	                    Hub Jumps

	                    Statics

	                    POS Summary (Intel)

	                    Structure Summary (Intel)

Statistics

							<canvas id="stats-canvas"></canvas>

						<form id='mass_sigs_quick_form'>
							Signature Adder
							<textarea name='blob' placeholder=" Paste scan results here + Press Enter " type='text' class="siggy-input"></textarea>
							<input name='delete_nonexistent_sigs' id='delete_nonexistent_sigs' type='checkbox' value='1' />
							Delete nonexistent sigs
						</form>

	                    <form>

	                                Sig ID
	                                <input type="text" class="siggy-input" name="sig" maxlength="3" placeholder="ABC" />

	                            @if( $group->show_sig_size_col )

	                                Sig Size
	                                <select name="size" class="siggy-input">
	                                    <option value="" selected="selected"> -- </option>
	                                    <option value="1.25">1.25</option>
	                                    <option value="2.2">2.2</option>
	                                    <option value="2.5">2.5</option>
	                                    <option value="4">4</option>
	                                    <option value="5">5</option>
	                                    <option value="6.67">6.67</option>
	                                    <option value="10">10</option>
	                                </select>

	                        	@endif

	                                Type
	                                <select name="type" class="siggy-input">
	                                    <option value="none" selected="selected"> -- </option>
	                                    <option value="wh"><?php echo __('WH');?></option>
	                                    <option value="gas"><?php echo __('Gas');?></option>
	                                    <option value="ore"><?php echo __('Ore');?></option>
	                                    <option value="data"><?php echo __('Data');?></option>
	                                    <option value="relic"><?php echo __('Relic');?></option>
	                                    <option value="anomaly"><?php echo __('Combat');?></option>
	                                </select>

	                                Site
	                                <select name="site" class="siggy-input">
	                                </select>

	                        	<button name='add' class="btn btn-default" style="margin-top: 15px;line-height: 171%;" type="submit">  Add</button>

	                                Description
	                                <input type="text" name="desc" class="siggy-input" />

	                    </form>

						0 /
							0 <?php echo __('signature(s) shown'); ?>

							<button type="button" class="btn btn-xs dropdown-toggle btn-info" data-toggle="dropdown"> Filter </button>

<input type="checkbox"/> <?php echo __('Wormhole');?>

<input type="checkbox"/> <?php echo __('Ore');?>

<input type="checkbox"/> <?php echo __('Gas');?>

<input type="checkbox"/> <?php echo __('Data');?>

<input type="checkbox"/> <?php echo __('Relic');?>

<input type="checkbox"/> <?php echo __('Combat');?>

<input type="checkbox"/> <?php echo __('None');?>

	                        Sig
	                        @if( $group->show_sig_size_col)
	                        Size
	                        Type
	                        Name/Description
	                        @else
	                        Type
	                        Name/Description
	                        @endif

	                        Age

	@include('siggy/boxes/confirm')
	@include('siggy/boxes/hotkey_helper')
	@include('siggy/boxes/group_notes')
	@include('siggy/boxes/character_settings')
	@include('siggy/boxes/dialog_import_thera')
	@include('siggy/boxes/dialog_exit_finder')
	@include('siggy/boxes/dialog_pos')
	@include('siggy/boxes/dialog_dscan')
	@include('siggy/boxes/dialog_notice')
	@include('siggy/boxes/dialog_notifier')
	@include('siggy/boxes/dialog_mass_sig')
	@include('siggy/boxes/dialog_structure')
	@include('siggy/boxes/dialog_structure_vulnerability')
	@include('siggy/handlebars/sig_table_row')
	@include('siggy/handlebars/effect_tooltip')
	@include('siggy/handlebars/statics_tooltip')
	@include('siggy/handlebars/site_tooltip')
	@include('siggy/handlebars/thera_table_row')
	@include('siggy/handlebars/search_result_pos')
	@include('siggy/handlebars/search_result_legacy_pos')
	@include('siggy/handlebars/scanned_system_table_row')
	@include('siggy/handlebars/notification_history_table_row')
	@include('siggy/handlebars/notification_setting_table_row')
	@include('siggy/handlebars/notifier_form_mapped_system')
	@include('siggy/handlebars/notifier_form_resident_found')
	@include('siggy/handlebars/notifier_form_site_found')
	@include('siggy/handlebars/chainmap_table_row')
	@include('siggy/handlebars/sig_create_new_wormhole_form')
	@include('siggy/handlebars/jump_log_entry')
	@include('siggy/handlebars/dialog_base')
	@include('siggy/handlebars/structure_table_row')
	@include('siggy/handlebars/pos_table_row')
	@include('siggy/handlebars/dscan_table_row')

@endsection


text:
<?php
require "header.php";
session_start();
if (isset($_SESSION['username']))
    $username = $_SESSION['username'];
if (isset($_SESSION['password']))
    $password = $_SESSION['password'];
if (!(empty($username) OR empty($password))) {
    include 'config.php';
    include 'CrudMissoes.php';
    include 'CrudTime.php';
    //include 'aultoload.php';

    $idFase = $_REQUEST['idFase'];
    $_SESSION['idFase'] = $idFase;
    //echo 'id fase = '. $idFase;
    ?>

                         Missões

                            <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Criar Missao

                                <form class="form-horizontal" role="form" action="RecebeDadosMissao.php" method="POST">

                                        Nome:

                                            <input type="text" class="form-control" name="nome" id="nomeMissao" required="required">

                                        Descrição:

                                            <textarea class="form-control" rows="3" name="descricao" id="descricaoMissao"></textarea>

                                    <input type="hidden" name="idFase" value="<?php echo $idFase; ?>" />

                            <button type="button" class="btn btn-default" data-dismiss="modal">Cancelar</button>
                            <button type="submit" class="btn btn-success" id="salvarFase">Salvar</button>

                        </form>

             Tarefas

                A Fazer
                Desenvolvendo
                Verificando
                Pronto

                <?php //listaMissoes($idFase); ?>

                <?php
                $query = "SELECT id_missao, nome FROM missoes WHERE fk_id_fase = '$idFase'";

                // Executa consulta
                $result = mysql_query($query, $link);

                $numlinha = mysql_num_rows($result);

                if ($numlinha > 0) {
                    while ($row = mysql_fetch_assoc($result)) {
                        $nome = $row['nome'];
                        $idMissao = $row['id_missao'];
                        ?>

                    <?php echo $nome; ?>
                        <?php $idMissao; ?>

                            <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Criar Tarefa

                                <form class="form-horizontal" role="form" action="RecebeDadosTarefa.php" method="POST" id="formCriatarefa">

                                        Nome:

                                            <input type="text" class="form-control" name="nome" id="nomeTarefa" required="required">

                                        Descrição:

                                            <textarea class="form-control" rows="3" name="descricao" id="descricaoTarefa"></textarea>

                                        Responsável

<?php listaUserSelect("responsavel","formCriatarefa"); ?>

                                        Início

                                            <input type="date" class="form-control" name="inicio" placeholder="dd/mm/yyyy" id="diniTarefa" required="required">

                                        Fim

                                            <input type="date" class="form-control" name="fim" placeholder="dd/mm/yyyy" id="dfimTarefa" required="required" >

                                    <input type="hidden" name="idMissao" value="<?php echo $idMissao; ?>" />

                            <button type="button" class="btn btn-default" data-dismiss="modal">Cancelar</button>
                            <button type="submit" class="btn btn-success" id="salvarTarefa">Salvar</button>

                        </form>

                        </form>
                        <form id="formEditarMissao" class="form-horizontal" role="form" action="editarMissao.php" method="post">

                        </form>
                        <form id="formDeletarMissao" class="form-horizontal" role="form" action="excluirMissao.php" method="post">

                        </form>

            <?php
        }
    } else {
        echo '';
    }
    //}
    $libera = mysql_free_result($result);
    ?>

    <?php
    //include_once "footer.php";
} else {
    echo "usuario não cadastrado, faça seu cadastro";
    echo " Voltar ";
}
?>


text:
#ifndef CAFFE_DATA_LAYERS_HPP_
#define CAFFE_DATA_LAYERS_HPP_

#include <string>
#include <utility>
#include <vector>

#include "boost/scoped_ptr.hpp"
#include "hdf5/hdf5.h"
#include "leveldb/db.h"
#include "lmdb/lmdb.h"

#include "caffe/blob.hpp"
#include "caffe/common.hpp"
#include "caffe/data_transformer.hpp"
#include "caffe/filler.hpp"
#include "caffe/internal_thread.hpp"
#include "caffe/layer.hpp"
#include "caffe/proto/caffe.pb.h"

namespace caffe {

#define HDF5_DATA_DATASET_NAME "data"
#define HDF5_DATA_LABEL_NAME "label"

/**
 * @brief Provides base for data layers that feed blobs to the Net.
 *
 * TODO(dox): thorough documentation for Forward and proto params.
 */
template <typename Dtype>
class BaseDataLayer : public Layer<Dtype> {
 public:
  explicit BaseDataLayer(const LayerParameter& param);
  virtual ~BaseDataLayer() {}
  // LayerSetUp: implements common data layer setup functionality, and calls
  // DataLayerSetUp to do special data layer setup for individual layer types.
  // This method may not be overridden except by the BasePrefetchingDataLayer.
  virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom,
      vector<Blob<Dtype>*>* top);
  virtual void DataLayerSetUp(const vector<Blob<Dtype>*>& bottom,
      vector<Blob<Dtype>*>* top) {}

  virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,
      const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom) {}
  virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,
      const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom) {}

  int datum_channels() const { return datum_channels_; }
  int datum_height() const { return datum_height_; }
  int datum_width() const { return datum_width_; }
  int datum_size() const { return datum_size_; }

 protected:
  TransformationParameter transform_param_;
  DataTransformer<Dtype> data_transformer_;
  int datum_channels_;
  int datum_height_;
  int datum_width_;
  int datum_size_;
  Blob<Dtype> data_mean_;
  const Dtype* mean_;
  Caffe::Phase phase_;
  bool output_labels_;
};

template <typename Dtype>
class BasePrefetchingDataLayer :
    public BaseDataLayer<Dtype>, public InternalThread {
 public:
  explicit BasePrefetchingDataLayer(const LayerParameter& param)
      : BaseDataLayer<Dtype>(param) {}
  virtual ~BasePrefetchingDataLayer() {}
  // LayerSetUp: implements common data layer setup functionality, and calls
  // DataLayerSetUp to do special data layer setup for individual layer types.
  // This method may not be overridden.
  void LayerSetUp(const vector<Blob<Dtype>*>& bottom,
      vector<Blob<Dtype>*>* top);

  virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom,
      vector<Blob<Dtype>*>* top);
  virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom,
      vector<Blob<Dtype>*>* top);

  virtual void CreatePrefetchThread();
  virtual void JoinPrefetchThread();
  // The thread's function
  virtual void InternalThreadEntry() {}

 protected:
  Blob<Dtype> prefetch_data_;
  Blob<Dtype> prefetch_label_;
};

template <typename Dtype>
class DataLayer : public BasePrefetchingDataLayer<Dtype> {
 public:
  explicit DataLayer(const LayerParameter& param)
      : BasePrefetchingDataLayer<Dtype>(param) {}
  virtual ~DataLayer();
  virtual void DataLayerSetUp(const vector<Blob<Dtype>*>& bottom,
      vector<Blob<Dtype>*>* top);

  virtual inline LayerParameter_LayerType type() const {
    return LayerParameter_LayerType_DATA;
  }
  virtual inline int ExactNumBottomBlobs() const { return 0; }
  virtual inline int MinTopBlobs() const { return 1; }
  virtual inline int MaxTopBlobs() const { return 2; }

 protected:
  virtual void InternalThreadEntry();

  // LEVELDB
  shared_ptr<leveldb::DB> db_;
  shared_ptr<leveldb::Iterator> iter_;
  // LMDB
  MDB_env* mdb_env_;
  MDB_dbi mdb_dbi_;
  MDB_txn* mdb_txn_;
  MDB_cursor* mdb_cursor_;
  MDB_val mdb_key_, mdb_value_;
};

/**
 * @brief Provides data to the Net generated by a Filler.
 *
 * TODO(dox): thorough documentation for Forward and proto params.
 */
template <typename Dtype>
class DummyDataLayer : public Layer<Dtype> {
 public:
  explicit DummyDataLayer(const LayerParameter& param)
      : Layer<Dtype>(param) {}
  virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom,
      vector<Blob<Dtype>*>* top);

  virtual inline LayerParameter_LayerType type() const {
    return LayerParameter_LayerType_DUMMY_DATA;
  }
  virtual inline int ExactNumBottomBlobs() const { return 0; }
  virtual inline int MinTopBlobs() const { return 1; }

 protected:
  virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom,
      vector<Blob<Dtype>*>* top);
  virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,
      const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom) {}
  virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,
      const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom) {}

  vector<shared_ptr<Filler<Dtype> > > fillers_;
  vector<bool> refill_;
};

/**
 * @brief Provides data to the Net from HDF5 files.
 *
 * TODO(dox): thorough documentation for Forward and proto params.
 */
template <typename Dtype>
class HDF5DataLayer : public Layer<Dtype> {
 public:
  explicit HDF5DataLayer(const LayerParameter& param)
      : Layer<Dtype>(param) {}
  virtual ~HDF5DataLayer();
  virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom,
      vector<Blob<Dtype>*>* top);

  virtual inline LayerParameter_LayerType type() const {
    return LayerParameter_LayerType_HDF5_DATA;
  }
  virtual inline int ExactNumBottomBlobs() const { return 0; }
  virtual inline int ExactNumTopBlobs() const { return 2; }

 protected:
  virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom,
      vector<Blob<Dtype>*>* top);
  virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom,
      vector<Blob<Dtype>*>* top);
  virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,
      const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom) {}
  virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,
      const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom) {}
  virtual void LoadHDF5FileData(const char* filename);

  std::vector<std::string> hdf_filenames_;
  unsigned int num_files_;
  unsigned int current_file_;
  hsize_t current_row_;
  Blob<Dtype> data_blob_;
  Blob<Dtype> label_blob_;
};

/**
 * @brief Write blobs to disk as HDF5 files.
 *
 * TODO(dox): thorough documentation for Forward and proto params.
 */
template <typename Dtype>
class HDF5OutputLayer : public Layer<Dtype> {
 public:
  explicit HDF5OutputLayer(const LayerParameter& param);
  virtual ~HDF5OutputLayer();
  virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom,
      vector<Blob<Dtype>*>* top) {}

  virtual inline LayerParameter_LayerType type() const {
    return LayerParameter_LayerType_HDF5_OUTPUT;
  }
  // TODO: no limit on the number of blobs
  virtual inline int ExactNumBottomBlobs() const { return 2; }
  virtual inline int ExactNumTopBlobs() const { return 0; }

  inline std::string file_name() const { return file_name_; }

 protected:
  virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom,
      vector<Blob<Dtype>*>* top);
  virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom,
      vector<Blob<Dtype>*>* top);
  virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,
      const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom);
  virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,
      const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom);
  virtual void SaveBlobs();

  std::string file_name_;
  hid_t file_id_;
  Blob<Dtype> data_blob_;
  Blob<Dtype> label_blob_;
};

/**
 * @brief Provides data to the Net from image files.
 *
 * TODO(dox): thorough documentation for Forward and proto params.
 */
template <typename Dtype>
class ImageDataLayer : public BasePrefetchingDataLayer<Dtype> {
 public:
  explicit ImageDataLayer(const LayerParameter& param)
      : BasePrefetchingDataLayer<Dtype>(param) {}
  virtual ~ImageDataLayer();
  virtual void DataLayerSetUp(const vector<Blob<Dtype>*>& bottom,
      vector<Blob<Dtype>*>* top);

  virtual inline LayerParameter_LayerType type() const {
    return LayerParameter_LayerType_IMAGE_DATA;
  }
  virtual inline int ExactNumBottomBlobs() const { return 0; }
  virtual inline int ExactNumTopBlobs() const { return 2; }

 protected:
  shared_ptr<Caffe::RNG> prefetch_rng_;
  virtual void ShuffleImages();
  virtual void InternalThreadEntry();

  vector<std::pair<std::string, int> > lines_;
  int lines_id_;
};

/**
 * @brief Provides data to the Net from memory.
 *
 * TODO(dox): thorough documentation for Forward and proto params.
 */
template <typename Dtype>
class MemoryDataLayer : public BaseDataLayer<Dtype> {
 public:
  explicit MemoryDataLayer(const LayerParameter& param)
      : BaseDataLayer<Dtype>(param), has_new_data_(false) {}
  virtual void DataLayerSetUp(const vector<Blob<Dtype>*>& bottom,
      vector<Blob<Dtype>*>* top);

  virtual inline LayerParameter_LayerType type() const {
    return LayerParameter_LayerType_MEMORY_DATA;
  }
  virtual inline int ExactNumBottomBlobs() const { return 0; }
  virtual inline int ExactNumTopBlobs() const { return 2; }

  virtual void AddDatumVector(const vector<Datum>& datum_vector);

  // Reset should accept const pointers, but can't, because the memory
  //  will be given to Blob, which is mutable
  void Reset(Dtype* data, Dtype* label, int n);

  int batch_size() { return batch_size_; }

 protected:
  virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom,
      vector<Blob<Dtype>*>* top);

  int batch_size_;
  Dtype* data_;
  Dtype* labels_;
  int n_;
  int pos_;
  Blob<Dtype> added_data_;
  Blob<Dtype> added_label_;
  bool has_new_data_;
};

/**
 * @brief Provides data to the Net from windows of images files, specified
 *        by a window data file.
 *
 * TODO(dox): thorough documentation for Forward and proto params.
 */
template <typename Dtype>
class WindowDataLayer : public BasePrefetchingDataLayer<Dtype> {
 public:
  explicit WindowDataLayer(const LayerParameter& param)
      : BasePrefetchingDataLayer<Dtype>(param) {}
  virtual ~WindowDataLayer();
  virtual void DataLayerSetUp(const vector<Blob<Dtype>*>& bottom,
      vector<Blob<Dtype>*>* top);

  virtual inline LayerParameter_LayerType type() const {
    return LayerParameter_LayerType_WINDOW_DATA;
  }
  virtual inline int ExactNumBottomBlobs() const { return 0; }
  virtual inline int ExactNumTopBlobs() const { return 2; }

 protected:
  virtual unsigned int PrefetchRand();
  virtual void InternalThreadEntry();

  shared_ptr<Caffe::RNG> prefetch_rng_;
  vector<std::pair<std::string, vector<int> > > image_database_;
  enum WindowField { IMAGE_INDEX, LABEL, OVERLAP, X1, Y1, X2, Y2, NUM };
  vector<vector<float> > fg_windows_;
  vector<vector<float> > bg_windows_;
};

}  // namespace caffe

#endif  // CAFFE_DATA_LAYERS_HPP_


text:
/************************************************************************/
/*                                                                      */
/* INCLUDE                                                              */
/*                                                                      */
/************************************************************************/
#include "callstack.h"

#define WIN32_LEAN_AND_MEAN
#include <Windows.h>

#pragma warning( disable : 4091 ) //  warning C4091: 'typedef ': ignored on left of '' when no variable is declared
#include <DbgHelp.h>

/************************************************************************/
/*                                                                      */
/* DEFINES AND CONSTANTS                                                */
/*                                                                      */
/************************************************************************/

/************************************************************************/
/*                                                                      */
/* MACROS                                                               */
/*                                                                      */
/************************************************************************/
#define MAX_SYMBOL_NAME_LENGTH 128
#define MAX_FILENAME_LENGTH 1024
#define MAX_DEPTH 128

/************************************************************************/
/*                                                                      */
/* TYPES                                                                */
/*                                                                      */
/************************************************************************/

// SymInitialize()
typedef BOOL (__stdcall *sym_initialize_t)( IN HANDLE hProcess, IN PSTR UserSearchPath, IN BOOL fInvadeProcess );
typedef BOOL (__stdcall *sym_cleanup_t)( IN HANDLE hProcess );
typedef BOOL (__stdcall *sym_from_addr_t)( IN HANDLE hProcess, IN DWORD64 Address, OUT PDWORD64 Displacement, OUT PSYMBOL_INFO Symbol );

typedef BOOL (__stdcall *sym_get_line_t)( IN HANDLE hProcess, IN DWORD64 dwAddr, OUT PDWORD pdwDisplacement, OUT PIMAGEHLP_LINE64 Symbol );

/************************************************************************/
/*                                                                      */
/* STRUCTS                                                              */
/*                                                                      */
/************************************************************************/

/************************************************************************/
/*                                                                      */
/* CLASSES                                                              */
/*                                                                      */
/************************************************************************/

/************************************************************************/
/*                                                                      */
/* LOCAL VARIABLES                                                      */
/*                                                                      */
/************************************************************************/
static HMODULE gDebugHelp;
static HANDLE gProcess;
static SYMBOL_INFO  *gSymbol;

static sym_initialize_t LSymInitialize;
static sym_cleanup_t LSymCleanup;
static sym_from_addr_t LSymFromAddr;
static sym_get_line_t LSymGetLineFromAddr64;

static int gCallstackCount = 0;

/************************************************************************/
/*                                                                      */
/* GLOBAL VARIABLES                                                     */
/*                                                                      */
/************************************************************************/

/************************************************************************/
/*                                                                      */
/* LOCAL FUNCTIONS                                                      */
/*                                                                      */
/************************************************************************/

/************************************************************************/
/*                                                                      */
/* EXTERNAL FUNCTIONS                                                   */
/*                                                                      */
/************************************************************************/

//------------------------------------------------------------------------
Callstack::Callstack()
   : hash(0)
   , frame_count(0) {}

//------------------------------------------------------------------------
bool CallstackSystemInit()
{
   // Load the dll, similar to OpenGL function fecthing.
   // This is where these functions will come from.
   gDebugHelp = LoadLibraryA( "dbghelp.dll" );
   if ( gDebugHelp == nullptr ) {
      return false;
   }

   // Get pointers to the functions we want from the loded library.
   LSymInitialize = (sym_initialize_t)GetProcAddress( gDebugHelp, "SymInitialize" );
   LSymCleanup = (sym_cleanup_t)GetProcAddress( gDebugHelp, "SymCleanup" );
   LSymFromAddr = (sym_from_addr_t)GetProcAddress( gDebugHelp, "SymFromAddr" );
   LSymGetLineFromAddr64 = (sym_get_line_t)GetProcAddress( gDebugHelp, "SymGetLineFromAddr64" );

   // Initialize the system using the current process [see MSDN for details]
   gProcess = ::GetCurrentProcess();
   LSymInitialize( gProcess, NULL, TRUE );

   // Preallocate some memory for loading symbol information.
   gSymbol = (SYMBOL_INFO *) ::malloc( sizeof( SYMBOL_INFO ) + (MAX_FILENAME_LENGTH * sizeof(char)) );
   gSymbol->MaxNameLen   = MAX_FILENAME_LENGTH;
   gSymbol->SizeOfStruct = sizeof( SYMBOL_INFO );

   return true;
}

//------------------------------------------------------------------------
void CallstackSystemDeinit()
{
   // cleanup after ourselves
   free( gSymbol );
   gSymbol = nullptr;

   LSymCleanup( gProcess );

   FreeLibrary(gDebugHelp);
   gDebugHelp = NULL;
}

//------------------------------------------------------------------------
// Can not be static - called when
// the callstack is freed.
void DestroyCallstack( Callstack *ptr )
{
   ::free( ptr );
}

//------------------------------------------------------------------------
Callstack* CreateCallstack( uint skip_frames )
{
   // Cappture the callstack frames - uses a windows call
   void *stack[MAX_DEPTH];
   DWORD hash;

   // skip_frames:  number of frames to skip [starting at the top - so don't return the frames for "CreateCallstack" (+1), plus "skip_frame_" layers.
   // max_frames to return
   // memory to put this information into.
   // out pointer to back trace hash.
   uint32_t frames = CaptureStackBackTrace( 1 + skip_frames, MAX_DEPTH, stack, &hash );

   // create the callstack using an untracked allocation
   Callstack *cs = (Callstack*) ::malloc( sizeof(Callstack) );

   // force call the constructor (new in-place0
   cs = new (cs) Callstack();

   // copy the frames to our callstack object
   uint frame_count = min( MAX_FRAMES_PER_CALLSTACK, frames );
   cs->frame_count = frame_count;
   memcpy( cs->frames, stack, sizeof(void*) * frame_count );

   cs->hash = hash;

   return cs;
}

//------------------------------------------------------------------------
// Fills lines with human readable data for the given callstack
// Fills from top to bottom (top being most recently called, with each next one being the calling function of the previous)
//
// Additional features you can add;
// [ ] If a file exists in yoru src directory, clip the filename
// [ ] Be able to specify a list of function names which will cause this trace to stop.
uint CallstackGetLines( callstack_line_t *line_buffer, uint const max_lines, Callstack *cs )
{
   IMAGEHLP_LINE64 line_info;
   DWORD line_offset = 0; // Displacement from the beginning of the line
   line_info.SizeOfStruct = sizeof(IMAGEHLP_LINE64);

   uint count = min( max_lines, cs->frame_count );
   uint idx = 0;

   for (uint i = 0; i < count; ++i) {
      callstack_line_t *line = &(line_buffer[idx]);
      DWORD64 ptr = (DWORD64)(cs->frames[i]);
      if (FALSE == LSymFromAddr( gProcess, ptr, 0, gSymbol )) {
         continue;
      }

      strcpy_s( line->function_name, 128, gSymbol->Name );

      BOOL bRet = LSymGetLineFromAddr64(
         GetCurrentProcess(), // Process handle of the current process
         ptr, // Address
         &line_offset, // Displacement will be stored here by the function
         &line_info );         // File name / line information will be stored here

      if (bRet) {
         line->line = line_info.LineNumber;

         strcpy_s( line->filename, 128, line_info.FileName );
         line->offset = line_offset;

      } else {
         // no information
         line->line = 0;
         line->offset = 0;
         strcpy_s( line->filename, 128, "N/A" );
      }

      ++idx;
   }

   return idx;
}

//------------------------------------------------------------------------
void CallstackDemo()
{
   // do one at system startup
   CallstackSystemInit();

   // Creating a callstack - created at allocation time
   Callstack *cs = CreateCallstack(0);

   // Printing a callstack, happens when making report
   char line_buffer[512];
   callstack_line_t lines[128];
   uint line_count = CallstackGetLines( lines, 128, cs );
   for (uint i = 0; i < line_count; ++i) {
      // this specific format will make it double clickable in an output window
      // taking you to the offending line.
      sprintf_s( line_buffer, 512, "%s(%u): %s\n",
         lines[i].filename, lines[i].line, lines[i].function_name );

      // print to output and console
      OutputDebugStringA( line_buffer );
      printf( line_buffer );
   }

   // clean up - happens on free
   DestroyCallstack(cs);

   // do at system shutdown.
   CallstackSystemDeinit();
}


text:
from zmq import *

# A way to access original zmq
import zmq as _zmq

import gevent.event
import gevent.core
import sys
import errno
from logging import getLogger

logger = getLogger(__name__)

class Context(_zmq.Context):

    def socket(self, socket_type):
        if self.closed:
            raise _zmq.ZMQError(_zmq.ENOTSUP)
        return Socket(self, socket_type)

class Socket(_zmq.Socket):

    def __init__(self, context, socket_type):
        super(Socket, self).__init__(context, socket_type)
        on_state_changed_fd = self.getsockopt(_zmq.FD)
        # NOTE: pyzmq 13.0.0 messed up with setattr (they turned it into a
        # non-op) and you can't assign attributes normally anymore, hence the
        # tricks with self.__dict__ here
        self.__dict__["_readable"] = gevent.event.Event()
        self.__dict__["_writable"] = gevent.event.Event()
        try:
            # gevent>=1.0
            self.__dict__["_state_event"] = gevent.hub.get_hub().loop.io(
                    on_state_changed_fd, gevent.core.READ)
            self._state_event.start(self._on_state_changed)
        except AttributeError:
            # gevent<1.0
            self.__dict__["_state_event"] = \
                    gevent.core.read_event(on_state_changed_fd,
                            self._on_state_changed, persist=True)

    def _on_state_changed(self, event=None, _evtype=None):
        if self.closed:
            self._writable.set()
            self._readable.set()
            return

        while True:
            try:
                events = self.getsockopt(_zmq.EVENTS)
                break
            except ZMQError as e:
                if e.errno not in (_zmq.EAGAIN, errno.EINTR):
                    raise

        if events & _zmq.POLLOUT:
            self._writable.set()
        if events & _zmq.POLLIN:
            self._readable.set()

    def close(self):
        if not self.closed and getattr(self, '_state_event', None):
            try:
                # gevent>=1.0
                self._state_event.stop()
            except AttributeError:
                # gevent<1.0
                self._state_event.cancel()
        super(Socket, self).close()

    def connect(self, *args, **kwargs):
        while True:
            try:
                return super(Socket, self).connect(*args, **kwargs)
            except _zmq.ZMQError, e:
                if e.errno not in (_zmq.EAGAIN, errno.EINTR):
                    raise

    def send(self, data, flags=0, copy=True, track=False):
        if flags & _zmq.NOBLOCK:
            return super(Socket, self).send(data, flags, copy, track)
        flags |= _zmq.NOBLOCK
        while True:
            try:
                msg = super(Socket, self).send(data, flags, copy, track)
                # The following call, force polling the state of the zmq socket
                # (POLLIN and/or POLLOUT). It seems that a POLLIN event is often
                # missed when the socket is used to send at the same time,
                # forcing to poll at this exact moment seems to reduce the
                # latencies when a POLLIN event is missed. The drawback is a
                # reduced throughput (roughly 8.3%) in exchange of a normal
                # concurrency. In other hand, without the following line, you
                # loose 90% of the performances as soon as there is simultaneous
                # send and recv on the socket.
                self._on_state_changed()
                return msg
            except _zmq.ZMQError, e:
                if e.errno not in (_zmq.EAGAIN, errno.EINTR):
                    raise
            self._writable.clear()
            # The following sleep(0) force gevent to switch out to another
            # coroutine and seems to refresh the notion of time that gevent may
            # have. This definitively eliminate the gevent bug that can trigger
            # a timeout too soon under heavy load. In theory it will incur more
            # CPU usage, but in practice it balance even with the extra CPU used
            # when the timeout triggers too soon in the following loop. So for
            # the same CPU load, you get a better throughput (roughly 18.75%).
            gevent.sleep(0)
            while not self._writable.wait(timeout=1):
                try:
                    if self.getsockopt(_zmq.EVENTS) & _zmq.POLLOUT:
                        logger.error("/!\\ gevent_zeromq BUG /!\\ " + \
                                "catching up after missing event (SEND) /!\\")
                        break
                except ZMQError as e:
                    if e.errno not in (_zmq.EAGAIN, errno.EINTR):
                        raise

    def recv(self, flags=0, copy=True, track=False):
        if flags & _zmq.NOBLOCK:
            return super(Socket, self).recv(flags, copy, track)
        flags |= _zmq.NOBLOCK
        while True:
            try:
                msg = super(Socket, self).recv(flags, copy, track)
                # The following call, force polling the state of the zmq socket
                # (POLLIN and/or POLLOUT). It seems that a POLLOUT event is
                # often missed when the socket is used to receive at the same
                # time, forcing to poll at this exact moment seems to reduce the
                # latencies when a POLLOUT event is missed. The drawback is a
                # reduced throughput (roughly 8.3%) in exchange of a normal
                # concurrency. In other hand, without the following line, you
                # loose 90% of the performances as soon as there is simultaneous
                # send and recv on the socket.
                self._on_state_changed()
                return msg
            except _zmq.ZMQError, e:
                if e.errno not in (_zmq.EAGAIN, errno.EINTR):
                    raise
            self._readable.clear()
            # The following sleep(0) force gevent to switch out to another
            # coroutine and seems to refresh the notion of time that gevent may
            # have. This definitively eliminate the gevent bug that can trigger
            # a timeout too soon under heavy load. In theory it will incur more
            # CPU usage, but in practice it balance even with the extra CPU used
            # when the timeout triggers too soon in the following loop. So for
            # the same CPU load, you get a better throughput (roughly 18.75%).
            gevent.sleep(0)
            while not self._readable.wait(timeout=1):
                try:
                    if self.getsockopt(_zmq.EVENTS) & _zmq.POLLIN:
                        logger.error("/!\\ gevent_zeromq BUG /!\\ " + \
                                "catching up after missing event (RECV) /!\\")
                        break
                except ZMQError as e:
                    if e.errno not in (_zmq.EAGAIN, errno.EINTR):
                        raise


text:
package nxt.util;

public abstract interface Listener<T>
{
  public abstract void notify(T paramT);
}


text:
* lib_R61523

R61523 LCD library. Depends on lib_delay.
Tested with LCD from Sony Ericsson Vivaz U5 mobile phone.
LCD size is 640x360. Connected through 16bit FSMC peripheral.
Supports 16bit,18bit and 24bit color, landscape and portrait orientation.

### How do I get set up? ###

  See code example below

### Usage example ###
```C
  ...
  R61523_Init();
  R61523_ColorMode(COLOR_24BIT);
  R61523_OrientationMode(ORIENTATION_PORTRAIT);
  R61523_ClearScreen(BLACK);
  ...
```