text:
(function (root) {
	'use strict';

	var modules = {},
		slice = Array.prototype.slice,
		waiting = {},
		path = require('path');

	function once(func) {
		var called = false,
			result;
		return function () {
			if (!called) {
				result = func.apply(null, slice.call(arguments));
				called = true;
			}
			return result;
		};
	}

	root.define = GLOBAL.define = function () {
		var dependencies, factory, module;
		for (var i = 0; i < arguments.length; i++) {
			var arg = arguments[i],
				type = typeof arg;
			if (type === 'function') {
				factory = once(arg);
			} else if (type === 'string') {
				module = arg;
			} else if (type === 'object' && arg.length) {
				dependencies = arg;
			}
		}
		if (module) {
			console.log('resolving: ' + module);
		}
		resolveDependencies(factory, dependencies, module);
	};

	function resolveDependencies(factory, dependencies, module) {
		var resolved = [];
		if (dependencies) {
			for (var i = 0; i < dependencies.length; i++) {
				var dependency = dependencies[i] = path.normalize(dependencies[i]);
				if (modules[dependency]) {
					resolved.push(modules[dependency].factory.apply(root, modules[dependency].resolved));
				} else {
					addToWaiting(factory, dependency, {
						factory: factory,
						dependencies: dependencies,
						module: module
					});
				}
			}
		}
		if (!dependencies || resolved.length === dependencies.length) {
			handleResolved(factory, resolved, module);
		}
	}

	function addToWaiting(factory, dependency, args) {
		if (!factory.unresolved) {
			factory.unresolved = [];
		}
		var waitList = waiting[dependency];
		if (!waitList) {
			waitList = waiting[dependency] = [];
		}
		waitList.push(args);
		factory.unresolved.push(dependency);
		if (waitList.length === 1) {
			fetch(dependency);
		}
	}

	function handleResolved(factory, resolved, module) {
		if (factory.unresolved) {
			delete factory.unresolved;
		}
		factory.apply(root, resolved);
		if (module) {
			modules[module] = {
				factory: factory,
				resolved: resolved
			};
			resolveWaiting(module);
		}
	}

	function resolveWaiting(module) {
		var waitList = waiting[module];
		if (waitList) {
			for (var i = 0; i < waitList.length; i++) {
				var args = waitList[i];
				resolveDependencies.call(root, args.factory, args.dependencies, args.module);
			}
		}
		delete waiting[module];
	}

	function fetch(module) {
		try {
			var result = require(module);
			modules[module] = {
				factory: function () {
					return result;
				},
				resolved: []
			};
			resolveWaiting(module);
		} catch (e) {
			console.log(e);
		}
	}
})(this);
/*
 * Module: apply/core
 * Copyright 2012 David Meads
 * Released under the MIT license
 */
(function (root) {
	'use strict';

	define('apply/core', function () {
		root.apply = {};

		return root.apply;
	});
})(this);
/*
 * Module: apply/util
 * Copyright 2012 David Meads
 * Released under the MIT license
 */
(function (root) {
	'use strict';

	define('apply/util', ['apply/core'], function (apply) {

		// On Loan
		// -------
		var slice = [].slice;

		// apply.extend
		// ------------
		var extend = apply.extend = function (dest) {
			var deep = false;
			if (dest === true) {
				deep = true;
				dest = arguments[1];
			}
			for (var i = 1; i < arguments.length; i++) {
				for (var key in arguments[i]) {
					if (deep && isPlainObject(dest[key])) {
						extend(true, dest[key], arguments[i][key]);
					} else {
						dest[key] = arguments[i][key];
					}
				}
			}
			return dest;
		};

		// apply.proxy
		// -----------
		apply.proxy = function (func, context) {
			return function () {
				return func.apply(context, arguments);
			};
		};

		apply.array = function (obj) {
			return slice.call(obj);
		};

		var getPrototypeOf = function (obj) {
			if (isObject(obj) || isFunction(obj)) {
				if (isFunction(obj)) {
					return obj.prototype;
				}
				return Object.getPrototypeOf(obj);
			}
		};

		var isArray = function (obj) {
			return getPrototypeOf(obj) === Array.prototype;
		};

		var isDefined = function () {
			if (arguments[0] !== undefined) {
				var parts = arguments[0].split('.');
				var obj = arguments[1] || root;

				for (var i = 0; i < parts.length; i++) {
					if (!obj[parts[i]]) {
						return false;
					}
					obj = obj[parts[i]];
				}
				return true;
			}
			return false;
		};

		var isFunction = function (obj) {
			return typeof obj === 'function';
		};

		var isInstanceOf = function (constructor, instance) {
			if (isFunction(constructor)) {
				if (getPrototypeOf(instance) === constructor.prototype) {
					return true;
				} else if (isDefined('constructor.mixins', instance)) {
					var mixins = instance.constructor.mixins;
					for (var i = 0; i < mixins.length; i++) {
						if (mixins[i] === constructor) {
							return true;
						}
					}
				}
			}
			return false;
		};

		var isComposed = function (obj) {
			if (isFunction(obj)) {
				return obj.compose !== undefined;
			} else if (isPlainObject(obj)) {
				return obj.constructor.compose !== undefined;
			}
			return false;
		};

		var isNumber = function (obj) {
			return typeof obj === 'number';
		};

		var isObject = function (obj) {
			return isFunction(obj) || typeof obj === 'object';
		};

		var isPlainObject = function (obj) {
			return !isArray(obj) && typeof obj === 'object';
		};

		var isString = function (obj) {
			return typeof obj === 'string';
		};

		extend(apply, {
			getPrototypeOf: getPrototypeOf,
			isArray: isArray,
			isDefined: isDefined,
			isFunction: isFunction,
			isInstanceOf: isInstanceOf,
			isComposed: isComposed,
			isNumber: isNumber,
			isObject: isObject,
			isPlainObject: isPlainObject,
			isString: isString
		});

		// apply.collection
		// ----------------
		var last = function (collection, value) {
			if (value) {
				collection[collection.length - 1] = value;
			}
			return collection[collection.length - 1];
		};

		var loop = function (array, callback, options) {
			options = options || {};
			var context = options.context || this;
			var i;
			if (options.reverse) {
				for (i = options.start || array.length - 1; i >= 0; i--) {
					callback.call(context, array[i], i);
				}
			} else {
				for (i = options.start || 0; i < array.length; i++) {
					callback.call(context, array[i], i);
				}
			}
		};

		extend(apply, {
			last: last,
			loop: loop
		});

		// apply.string
		// ------------
		var numeric = /^(0|[1-9][0-9]*)$/;

		var isNumeric = function (string) {
			return numeric.test(string);
		};

		var endsWith = function (string, suffix) {
			return string.indexOf(suffix) === string.length - suffix.length;
		};

		apply.string = {
			endsWith: endsWith,
			isNumeric: isNumeric
		};

		// apply.namespace
		// ---------------
		var namespace = apply.namespace = function () {
			var args = slice.call(arguments);
			var obj = root;
			if (!isString(args[0])) {
				obj = args.shift();
				if (!obj) {
					throw 'Attempting to extend/access "' + args[0] + '" on an undefined namespace.';
				}
			}
			var namespace = args[0],
				object = args[1];
			if (namespace !== undefined) {
				var parts = namespace.split('.');
				loop(parts, function (part, index) {
					if (index === parts.length - 1) {
						if (object) {
							obj[part] = object;
						}
					} else if (!obj[part]) {
						obj[part] = {};
					}
					obj = obj[part];
				});
			}
			return obj;
		};

		// apply.delegateToParent
		// ----------------------
		apply.delegateToParent = function (method, callback) {
			return function () {
				if (this.parent && this.parent[method]) {
					return this.parent[method].apply(this.parent, arguments);
				}
				return callback.apply(this, arguments);
			};
		};

		// apply.propogate
		// ---------------
		apply.propogate = function (dest, src, field) {
			if (!dest[field] && src && src[field]) {
				dest[field] = src[field];
			}
			return dest[field];
		};

		return apply;

	});
})(this);
/*
 * Module: apply/construct
 * Copyright 2012 David Meads
 * Released under the MIT license
 */
define('apply/construct', ['apply/util'], function (apply) {
	'use strict';

	var array = apply.array,
		extend = apply.extend,
		isArray = apply.isArray,
		isComposed = apply.isComposed,
		isFunction = apply.isFunction,
		isInstanceOf = apply.isInstanceOf,
		isPlainObject = apply.isPlainObject,
		isString = apply.isString,
		loop = apply.loop,
		namespace = apply.namespace,
		push = [].push;

	// apply.cascade
	// -------------
	var cascade = apply.cascade = function (objects, funcName, reverse) {
		var cascades = [];
		loop(objects, function (object) {
			if (object[funcName]) {
				cascades.push(object[funcName]);
			}
		}, {
			reverse: reverse
		});
		if (cascades.length) {
			return function () {
				var result;
				var args = array(arguments);
				loop(cascades, function (cascade) {
					result = cascade.apply(this, args);
				}, {
					context: this
				});
				return result;
			};
		}
	};

	// apply.compose
	// -----------
	var buildConstructor = (function () {

		function prepArgs(constructor, oldArguments) {
			var args = array(oldArguments);
			return isString(args[0]) ? [args.shift(), constructor].concat(args) : [constructor].concat(args);
		}

		function create() {
			var constructor = function () {
				if (!this || this.constructor !== constructor) {
					return compose.apply(this || {}, prepArgs(constructor, arguments));
				}
				if (this.init) {
					this.init.apply(this, arguments);
				}
			};
			return constructor;
		}

		function decorateConstructor(constructor, mixins) {
			constructor.objects = [];
			constructor.mixins = mixins;
			constructor.composers = [];
			constructor.cascades = {
				'init': ['init']
			};
			constructor.cascade = function (funcName) {
				namespace(constructor, 'cascades.' + funcName, arguments);
				var cascaded = cascade.apply(this, [this.objects].concat(array(arguments)));
				if (cascaded) {
					constructor.prototype[funcName] = cascaded;
				}
				return constructor;
			};
			constructor.instance = function () {
				var args = array(arguments);
				args.push(constructor);
				return instance.apply(this, args);
			};
			constructor.merge = function (object) {
				extend(constructor.prototype, object);
				return constructor;
			};
			constructor.compose = function () {
				if (arguments.length === 0) {
					return buildConstructor(constructor.mixins, constructor);
				}
				return compose.apply(this, prepArgs(constructor, arguments));
			};
			constructor.composer = function (composer) {
				if (composer) {
					constructor.composers.push(composer);
				}
				return constructor;
			};
			loop(mixins, function (mixin) {
				if (isFunction(mixin)) {
					constructor.objects.push(mixin.prototype);
					extend(constructor.cascades, mixin['cascades']);
					if (mixin.composers) {
						push.apply(constructor.composers, mixin.composers);
					}
				} else {
					constructor.objects.push(mixin);
				}
			});
		}

		function addCascades(constructor) {
			var cascades = constructor.cascades;
			for (var key in cascades) {
				constructor.cascade.apply(constructor, cascades[key]);
			}
		}

		function addIsInstanceOf(constructor) {
			constructor.prototype.isInstanceOf = function (constructor) {
				return isInstanceOf(constructor, this);
			};
		}

		function decoratePrototype(constructor) {
			extend.apply(undefined, [constructor.prototype].concat(constructor.objects));
			addCascades(constructor);
			addIsInstanceOf(constructor);
		}

		function invokecomposers(constructor) {
			loop(constructor.composers, function (composer) {
				composer.call(constructor, constructor);
			});
		}

		return function (mixins, constructor) {
			if (!constructor) {
				constructor = create();
			}
			decorateConstructor(constructor, mixins);
			decoratePrototype(constructor);
			invokecomposers(constructor);
			return constructor;
		};
	})();

	var compose = apply.compose = function () {
		var args = array(arguments),
			ns;
		if (isString(args[0])) {
			ns = args.shift();
		}
		var constructor = buildConstructor(args);
		if (ns) {
			namespace(ns, constructor);
		}
		return constructor;
	};

	// apply.decompose
	// ----------------
	var cleanConstructor = function (constructor) {
		constructor.prototype = {};
	};

	apply.decompose = function () {
		var args = array(arguments),
			constructor;
		if (args.length > 1) {
			constructor = args.shift();
			if (isComposed(constructor)) {
				cleanConstructor(constructor);
				for (var i = 0; i < args.length; i++) {
					var indexOf = constructor.mixins.indexOf(args[i]);
					if (indexOf >= 0) {
						constructor.mixins.splice(indexOf, 1);
					}
				}
				constructor.compose();
			}
		}
		return constructor;
	};

	// apply.instance
	// ---------------
	var con = function () {};

	var instance = apply.instance = function () {
		var args = array(arguments);
		var nsargs = [];
		if (isPlainObject(args[0])) {
			nsargs.push(args.shift());
		}
		if (isString(args[0])) {
			nsargs.push(args.shift());
		}
		var conargs = [];
		if (isArray(args[0])) {
			conargs = args.shift();
		}
		var instance = {};
		if (isFunction(args[0])) {
			con.prototype = args[0].prototype;
			instance = new con();
			instance.constructor = args[0];
			args[0].apply(instance, conargs);
		}
		if (nsargs.length > 0) {
			nsargs.push(instance);
			namespace.apply(this, nsargs);
		}
		return instance;
	};

	return apply;
});
/*
 * Module: apply/events
 * Copyright 2012 David Meads
 * Released under the MIT license
 */
define('apply/events', ['apply/construct'], function (apply) {
	'use strict';

	apply.Events = apply.compose({
		init: function () {
			if (!this.events) {
				this.events = {};
			}
		},
		on: function (event, callback, context) {
			var callbacks = this.events[event];
			if (!callbacks) {
				callbacks = this.events[event] = [];
			}
			if (context) {
				callback = apply.proxy(callback, context);
			}
			callbacks.push(callback);
		},
		trigger: function (event) {
			var callbacks = this.events[event];
			if (callbacks) {
				var args = apply.array(arguments);
				args.shift();
				for (var i = 0; i < callbacks.length; i++) {
					callbacks[i].apply(this, args);
				}
			}
		}
	});

	return apply;
});
/*
 * Module: apply/model
 * Copyright 2012 David Meads
 * Released under the MIT license
 */
define('apply/model', ['apply/events'], function (apply) {
	'use strict';

	var extend = apply.extend;

	function inflate(object, mappings, parent) {
		if (mappings) {
			if (!object) {
				object = {};
			}
			for (var key in mappings) {
				if (object[key]) {
					var obj = new mappings[key](object[key]);
					if (parent) {
						obj.parent = parent;
					}
					object[key] = obj;
				}
			}
		}
		return object;
	}

	function deflate(object, mappings) {
		if (mappings) {
			for (var key in mappings) {
				if (object[key].deflate) {
					object[key] = object[key].deflate();
				}
			}
		}
		return object;
	}

	function defaultAttributes(model) {
		model.attributes = {};
		model.set(model.
	default);
	}

	apply.Model = apply.Events({
		id: 'id',
		urlRoot: '',
		init: function (attributes) {
			defaultAttributes(this);
			this.set(attributes);
		},
		set: function (attributes) {
			if (attributes && apply.isFunction(attributes.deflate)) {
				attributes = attributes.deflate();
			}
			extend(this.attributes, inflate(attributes, this.mappings, this));
			for (var key in attributes) {
				this.trigger('change:' + key, this.attributes[key], this);
			}
			this.trigger('change', this.attributes[key], key, this);
			return this;
		},
		setId: function (id) {
			this.attributes[this.id] = id;
			return this;
		},
		get: function (key) {
			return this.attributes[key];
		},
		getId: function () {
			return this.attributes[this.id];
		},
		clear: function () {
			var attributes = this.attributes;
			defaultAttributes(this);
			for (var key in attributes) {
				this.trigger('change:' + key, undefined, this);
				this.trigger('change', undefined, key, this);
			}
			return this;
		},
		deflate: function () {
			return deflate(extend({}, this.attributes), this.mappings);
		},
		inflate: function (data) {
			return this.set(data);
		},
		toString: function () {
			return JSON.stringify(this.deflate ? this.deflate() : this);
		},
	});

	return apply;
});
/*
 * Module: apply/list
 * Copyright 2012 David Meads
 * Released under the MIT license
 */
define('apply/list', ['apply/events', 'apply/model'], function (apply) {
	'use strict';

	var addAndTrigger = function (list, model) {
		list.list.push(model);
		list.trigger('add', model);
	};

	var removeAndTrigger = function (list, model) {
		for (var i = 0; i < list.list.length; i++) {
			if (list.list[i] === model) {
				list.list.splice(i, 1);
				list.trigger('remove', model);
			}
		}
	};

	var list = apply.List = apply.Events({
		urlRoot: '',
		mapping: apply.Model,
		init: function (list) {
			this.list = [];
			this.add(list);
		},
		size: function () {
			return this.list.length;
		},
		get: function (index) {
			return this.list[index];
		},
		add: function (list) {
			if (apply.isArray(list)) {
				for (var key in list) {
					addAndTrigger(this, new this.mapping(list[key]));
				}
			} else if (list) {
				if (apply.getPrototypeOf(list) === apply.getPrototypeOf(this.mapping)) {
					addAndTrigger(this, list);
				} else if (apply.isComposed(list)) {
					throw 'Attempted to add an incompatible model to a list.';
				} else {
					addAndTrigger(this, new this.mapping(list));
				}
			}
			return this;
		},
		remove: function (list) {
			if (!apply.isArray(list)) {
				list = [list];
			}
			for (var key in list) {
				removeAndTrigger(this, list[key]);
			}
			return this;
		},
		getUrl: function () {
			return this.urlRoot;
		},
		deflate: function () {
			var array = [];
			for (var i = 0; i < this.list.length; i++) {
				array.push(this.list[i].deflate ? this.list[i].deflate() : this.list[i]);
			}
			return array;
		},
		inflate: function (data) {
			return this.add(data);
		},
		toString: function () {
			return JSON.stringify(this.deflate ? this.deflate() : this);
		},
	});

	return apply;
});
/*
 * Module: apply/logger
 * Copyright 2012 David Meads
 * Released under the MIT license
 */
define('apply/logger', ['apply/construct'], function (apply) {
	'use strict';

	var addLoggers = function () {
		apply.loop(arguments, function (level) {
			this[level] = function (message) {
				return this.log({
					level: level,
					message: message
				});
			};
		}, {
			context: this
		});
	};

	var Logger = apply.Logger = apply.compose({
		init: function () {
			this.levels = {};
			this.config({
				debug: true,
				info: true,
				warning: true,
				error: true
			});
		},
		config: function (levels) {
			apply.extend(this.levels, levels);
			for (var key in levels) {
				if (!this[key]) {
					addLoggers.call(this, key);
				}
			}
		},
		log: function (options) {
			var level = options.level;
			if (level && this.levels[level] && options.message) {
				console.log(options.message);
			}
			return this;
		}
	}).cascade('log', true);

	apply.logger = Logger.instance();

	return apply;
});
/*
 * Module: apply/validation
 * Copyright 2012 David Meads
 * Released under the MIT license
 */
define('apply/validation', ['apply/model'], function (apply) {
	'use strict';

	var validations = {
		'required': function (value) {
			if (value && (apply.isObject(value) || (value.length && value.length > 0))) {
				return true;
			}
			return false;
		}
	};

	apply.namespace('apply.mixins.validation', {
		validate: function () {
			if (this.validation) {
				for (var field in this.validation) {
					var rules = this.validation[field];
					for (var i = 0; i < rules.length; i++) {
						if (validations[rules[i]] && !validations[rules[i]].call(this, this.attributes[field])) {
							return false;
						}
					}
				}
			}
			return true;
		}
	});

	return apply;
});
/*
 * Module: apply/router
 * Copyright 2012 David Meads
 * Released under the MIT license
 */
define('apply/router', ['apply/util', 'apply/construct'], function (apply) {
	'use strict';

	var slice = [].slice;

	apply.Router = apply.compose({
		init: function () {
			this.routes = {};
		},
		add: function (routes) {
			if (apply.isString(routes)) {
				routes = {};
				if (arguments.length === 2) {
					routes[arguments[0]] = arguments[1];
				}
			}
			try {
				for (var key in routes) {
					apply.namespace(this.routes, key.replace(/^\//, '').replace(/\//g, '.'), routes[key]);
				}
			} catch (e) {
				console.log(e);
			}
			return this;
		},
		route: function (route) {
			var args = [];
			return this.invoke(this.parse(route, args), args.concat(slice.call(arguments, 1)));
		},
		parse: function (route, args) {
			var parts = route.replace(/^#?\/?/, '').split('/');
			var fragments = this.routes;
			for (var i = 0; i < parts.length; i++) {
				var part = parts[i];
				if (fragments[part]) {
					fragments = fragments[part];
				} else if (fragments['*']) {
					args.push(apply.string.isNumeric(part) ? Number(part) : part);
					fragments = fragments['*'];
				} else {
					break;
				}
			}
			return fragments;
		},
		invoke: function (callback, args) {
			if (apply.isFunction(callback)) {
				callback.apply(this, args);
				return true;
			}
			return false;
		}
	});

	apply.router = apply.Router.instance();

	return apply;
});
/*
 * Module: apply
 * Copyright 2012 David Meads
 * Released under the MIT license
 */
define('apply', ['apply/construct', 'apply/core', 'apply/events', 'apply/list', 'apply/logger', 'apply/model', 'apply/router', 'apply/util'], function (apply) {
	'use strict';

	return apply;
});
/*
 * Module: apply.mongo
 * Copyright 2012 David Meads
 * Released under the MIT license
 */
define('apply/mongo', ['apply', 'mongodb', 'bson'], function (apply, mongodb, bson) {
	'use strict';

	function url(model) {
		return 'mongodb://' + model.host + ':' + model.port + '/' + model.db;
	}

	function collection(obj, callback) {
		mongodb.MongoClient.connect(url(obj), function (err, db) {
			if (db === null) {
				throw 'The \"' + obj.db + '\" database was not found.';
			}
			db.collection(obj.collection, function (err, coll) {
				callback.call(this, db, coll, obj);
			});
		});
	}

	function error(obj, err, options) {
		if (err && options.error) {
			options.error.call(err, obj);
			return true;
		}
		return false;
	}

	function normalize(obj) {
		if (typeof obj._id === 'string') {
			obj._id = bson.ObjectID(obj._id);
		}
		return obj;
	}

	apply.namespace('apply.mixins.mongo', {
		init: function () {
			if (!this.db || !this.collection) {
				throw 'All mongoDB models must have a db and collection declared.';
			}
		},
		host: 'localhost',
		port: 27017,
		save: function (options) {
			collection(this, function (db, coll, obj) {
				coll.insert(normalize(options.data || obj.deflate()), function (err, data) {
					if (!error(obj, err, options)) {
						obj.inflate(obj.add ? data : data[0]);
						if (options.success) {
							options.success.call(obj, obj);
						}
					}
					db.close();
				});
			});
		},
		fetch: function (options) {
			collection(this, function (db, coll, obj) {
				coll.find(normalize(options.data || obj.deflate())).toArray(function (err, data) {
					if (!error(obj, err, options)) {
						obj.inflate(obj.add ? data : data[0]);
						if (options.success) {
							options.success.call(obj, obj);
						}
					}
					db.close();
				});
			});
		},
		destroy: function (options) {
			collection(this, function (db, coll, obj) {
				coll.remove(normalize(options.data || obj.deflate()), function (err) {
					if (!error(obj, err, options)) {
						if (options.success) {
							options.success.call(obj, obj);
						}
					}
					db.close();
				});
			});
		},
		toString: function () {
			return JSON.stringify(this.deflate ? this.deflate() : this);
		}
	});

	apply.namespace('apply.mongo.Model', apply.Model(apply.mixins.mongo, {
		id: '_id'
	}));

	apply.namespace('apply.mongo.List', apply.List(apply.mixins.mongo, {
		mapping: apply.mongo.Model
	}).composer(function () {
		apply.propogate(this.prototype, this.prototype.mapping.prototype, 'db');
		apply.propogate(this.prototype, this.prototype.mapping.prototype, 'collection');
	}));

	return apply;
});
/*
 * Module: apply/node/router
 * Copyright 2013 David Meads
 * Released under the MIT license
 */
define('apply/node/router', ['apply'], function (apply) {
	'use strict';

	var invoke = apply.router.invoke;

	apply.router.invoke = function (callback, args) {
		var req = args[args.length - 2];
		if (apply.isPlainObject(callback) && req.method) {
			callback = callback[req.method];
		}
		return invoke.call(this, callback, args);
	};

	apply.namespace('apply.connect.router', function () {
		return function (req, res, next) {
			if (!apply.router.route.call(apply.router, req.url, req, res)) {
				next();
			}
		};
	});

	return apply;
});


text:
var assert = require('assert');
var test = require('../basePersistenceTest');

describe('jive', function () {

    describe('#persistence.file', function () {

        it('save', function (done) {
            var jive = this['jive'];
            var testUtils = this['testUtils'];

            testUtils.createTempDir().then( function(dir) {
                var persistence = new jive.persistence.file({ 'fileFlushInterval' : 200, 'dataDirPath': dir });

                test.testSave(testUtils, persistence).then(
                    function() {
                        setTimeout( function() {
                            done();
                        }, 1000);
                    },

                    function(e) {
                        assert.fail(e);
                    }
                ).finally( function() {
                    return persistence.close();
                });
            });
        });

        it('remove', function (done) {
            var jive = this['jive'];
            var testUtils = this['testUtils'];

            testUtils.createTempDir().then( function(dir) {
                var persistence = new jive.persistence.file({ 'dataDirPath': dir });

                test.testRemove(testUtils, persistence).then(
                    function() {
                        done();
                    },

                    function(e) {
                        assert.fail(e);
                    }
                ).finally( function() {
                    return persistence.close();
                });
            });
        });

        it('remove - object', function (done) {
            var jive = this['jive'];
            var testUtils = this['testUtils'];

            testUtils.createTempDir().then( function(dir) {
                var persistence = new jive.persistence.file({ 'dataDirPath': dir });

                test.testRemoveObject(testUtils, persistence).then(
                    function() {
                        done();
                    },

                    function(e) {
                        assert.fail(e);
                    }
                ).finally( function() {
                        return persistence.close();
                    });
            });
        });

        it('find', function (done) {
            var jive = this['jive'];
            var testUtils = this['testUtils'];

            testUtils.createTempDir().then( function(dir) {
                var persistence = new jive.persistence.file({ 'dataDirPath': dir });

                test.testFind(testUtils, persistence).then(
                    function() {
                        done();
                    },

                    function(e) {
                        assert.fail(e);
                    }
                ).finally( function() {
                    return persistence.close();
                });
            });
        });

        // xxx todo
    });

});

redpajama_set_name: RedPajamaGithub


text:
(function() {

  var proto = Object.create(HTMLElement.prototype);
  proto.createdCallback = function() {
    console.log(this.localName, 'created');
  }

  document.register('x-test', {prototype: proto});

})();


text:
extern char buffer_UART_RX[BUF_SIZE_UART_RX];
extern char buf_UART_RX_count;

//UART section is 0x10
void instrCall_UART(char instruction, char* datain, char dataLength)
{
  switch (instruction)
  {
  case UART_WRITE:
    {
      UART_write(datain, dataLength);
      break;
    }
  case UART_SET_BAUD:
    {
      UART_setBaudRate(datain);
      break;
    }
  case UART_SET_REGS:
    {
	  UART_setRegisters(datain);
	  break;
    }
  }
}

//Set baud rate method
void UART_setBaudRate(char* datain)
{
  UBRR1H = datain[1];
  UBRR1L = datain[0];
}

//data: UCSR1A UCSR1B UCSR1C UCSR1D UBRR1H UBRR1L
void UART_setRegisters(char *datain)
{
	UCSR1A = datain[0];
	UCSR1B = datain[1];
	UCSR1C = datain[2];
	UCSR1D = datain[3];

	UBRR1L = datain[4];
	UBRR1H = datain[5];
}

void UART_write(char* datain, char dataLength)
{
  unsigned char i;
  //Send dataPacket to uart buffer
  for (i = 0; i < dataLength; i++)
      putchar1(datain[i]);
}

//-------------- UART RX Code -----------------------------
// This interrupt will copy the byte to the UART RX buffer which will be
// automatically transmitted to the PC in IN_report.c

// USART1 Receiver interrupt service routine
ISR(USART1_RX_vect)
{
	char status,datain;
	status=UCSR1A;
	datain=UDR1;
	if ((status & (FRAMING_ERROR | PARITY_ERROR | DATA_OVERRUN))!=0)
		return;			//dump the byte if the status is bad

	if (buf_UART_RX_count == 0)	//a new in-report must be created
	{
		//This will be set later in the setInReport method (datalength)
		setReplyHeader(&buffer_UART_RX[0], S_UART, UART_ASYNC_RX, 0x00, 0x00, 0x00);
		buf_UART_RX_count = IN_REPORT_HEADER_LENGTH;
	}

	if (buf_UART_RX_count >= BUF_SIZE_UART_RX)
		return;			//dump any bytes if the buffer overflows

	buffer_UART_RX[buf_UART_RX_count] = datain;
	buf_UART_RX_count++;
}

//-------------- UART TX Code -----------------------------
char tx_buffer1[TX_BUFFER_SIZE1];
unsigned char tx_wr_index1,tx_rd_index1,tx_counter1;

// USART1 Transmitter interrupt service routine
ISR(USART1_TX_vect)
{
if (tx_counter1)
   {
   --tx_counter1;
   UDR1=tx_buffer1[tx_rd_index1];
   if (++tx_rd_index1 == TX_BUFFER_SIZE1) tx_rd_index1=0;
   }
}

// Write a character to the USART1 Transmitter buffer
void putchar1(char c)
{
while (tx_counter1 == TX_BUFFER_SIZE1);
asm("cli");
if (tx_counter1 || ((UCSR1A & DATA_REGISTER_EMPTY)==0))
   {
   tx_buffer1[tx_wr_index1]=c;
   if (++tx_wr_index1 == TX_BUFFER_SIZE1) tx_wr_index1=0;
   ++tx_counter1;
   }
else
   UDR1=c;
asm("sei");
}


text:
#include "sspace.h"

POINTER_SIZE_INT TOSPACE_SIZE = 0;
void* tospace_start;
void* tospace_end;

static unsigned int sspace_compute_num_tospace_blocks(Sspace* sspace)
{
  unsigned int num_tospace_blocks = 0;

  if(! TOSPACE_SIZE) /* if no specified size, use default one */
    return sspace->num_managed_blocks >> 3;

  if( (TOSPACE_SIZE << 1) >= sspace->committed_heap_size ){

    TOSPACE_SIZE = sspace->committed_heap_size >> 1;

    /* tospace should always smaller than fromspace, and at least 1 block. */
    TOSPACE_SIZE = round_down_to_size(TOSPACE_SIZE, GC_BLOCK_SIZE_BYTES);
    if( TOSPACE_SIZE != 0 ) TOSPACE_SIZE -= 1;

    if( TOSPACE_SIZE >= MB ){
        LWARN(66, "GC Init: TOSPACE_SIZE is too big, set it to be {0}MB" << TOSPACE_SIZE/MB);
    }else{
        LWARN(66, "GC Init: TOSPACE_SIZE is too big, set it to be {0}KB" << TOSPACE_SIZE/KB);
    }
  }

  num_tospace_blocks = (unsigned int)(TOSPACE_SIZE >> GC_BLOCK_SHIFT_COUNT);

  return num_tospace_blocks;
}

static void sspace_config_after_clean(Sspace* sspace)
{
  unsigned int num_tospace_blocks = sspace_compute_num_tospace_blocks(sspace);
  unsigned int num_fromspace_blocks = sspace->num_managed_blocks - num_tospace_blocks;
  unsigned int sspace_first_idx = sspace->first_block_idx;

  /* prepare for from-space, first half */
  Block_Header* fromspace_last_block = (Block_Header*)&(sspace->blocks[num_fromspace_blocks - 1]);
  fromspace_last_block->next = NULL;

  /* prepare for to-space */
  sspace->tospace_first_idx = sspace_first_idx + num_fromspace_blocks;
  sspace->ceiling_block_idx = sspace->tospace_first_idx +  num_tospace_blocks - 1;
  assert( sspace->ceiling_block_idx == sspace_first_idx + sspace->num_managed_blocks - 1 );
  sspace->free_block_idx = sspace->tospace_first_idx;

  /* no survivor area at the beginning */
  sspace->survivor_area_start = (Block_Header*)&(sspace->blocks[num_fromspace_blocks]);
  sspace->survivor_area_end = sspace->survivor_area_start;

  sspace->cur_free_block = (Block_Header*)sspace->heap_start;
  if(num_fromspace_blocks == 0) sspace->cur_free_block = NULL;

  sspace->num_used_blocks = 0;

}

Sspace *sspace_initialize(GC* gc, void* start, POINTER_SIZE_INT sspace_size, POINTER_SIZE_INT commit_size)
{
  assert( (sspace_size%GC_BLOCK_SIZE_BYTES) == 0 );
  Sspace* sspace = (Sspace *)STD_MALLOC(sizeof(Sspace));
  assert(sspace);
  memset(sspace, 0, sizeof(Sspace));

  sspace->reserved_heap_size = sspace_size;
  sspace->num_total_blocks = (unsigned int)(sspace_size >> GC_BLOCK_SHIFT_COUNT);

  void* reserved_base = start;
  /* commit sspace mem */
  if(!large_page_hint)
    vm_commit_mem(reserved_base, commit_size);
  memset(reserved_base, 0, commit_size);

  sspace->committed_heap_size = commit_size;
  sspace->heap_start = reserved_base;
  sspace->blocks = (Block*)reserved_base;

#ifdef STATIC_NOS_MAPPING
  sspace->heap_end = (void *)((POINTER_SIZE_INT)reserved_base + sspace->reserved_heap_size);
#else /* for dynamic mapping, nos->heap_end is gc->heap_end */
  sspace->heap_end = (void *)((POINTER_SIZE_INT)reserved_base + sspace->committed_heap_size);
#endif

  sspace->num_managed_blocks = (unsigned int)(commit_size >> GC_BLOCK_SHIFT_COUNT);

  unsigned int sspace_first_idx = GC_BLOCK_INDEX_FROM(gc->heap_start, sspace->heap_start);
  sspace->first_block_idx = sspace_first_idx;

  space_init_blocks((Blocked_Space*)sspace); /* it uses first_block_idx and num_managed_blocks */

  sspace_config_after_clean(sspace);  /* it uses first_block_idx and num_managed_blocks */

  sspace->move_object = TRUE;
  sspace->num_collections = 0;
  sspace->time_collections = 0;
  sspace->survive_ratio = 0.2f;
  sspace->last_alloced_size = 0;
  sspace->accumu_alloced_size = 0;
  sspace->total_alloced_size = 0;
  sspace->last_surviving_size = 0;
  sspace->period_surviving_size = 0;

  sspace->gc = gc;

  return sspace;
}

void sspace_destruct(Sspace *sspace)
{
#ifdef USE_32BITS_HASHCODE
  space_desturct_blocks((Blocked_Space*)sspace);
#endif
  /* we don't free the real space here, the heap will be freed altogether */
  STD_FREE(sspace);
  sspace = NULL;
}

POINTER_SIZE_INT sspace_free_space_size(Sspace* nos)
{
  POINTER_SIZE_INT tospace_free_size = blocked_space_free_mem_size((Blocked_Space*)nos);

  POINTER_SIZE_INT fromspace_free_size = 0;
  Block_Header* cur_free_block = nos->cur_free_block;
  POINTER_SIZE_INT num_free_blocks = 0;
  while(cur_free_block){
    num_free_blocks++;
    cur_free_block = cur_free_block->next;
  }
  fromspace_free_size = num_free_blocks << GC_BLOCK_SHIFT_COUNT;

  return tospace_free_size + fromspace_free_size;
}

POINTER_SIZE_INT sspace_used_space_size(Sspace* nos)
{
  return nos->committed_heap_size - sspace_free_space_size(nos);
}

/* adjust the next pointer of block to point correctly to its adjacent next */
void sspace_prepare_for_collection(Sspace* sspace)
{
  if(sspace->num_managed_blocks == 0)
    return;

  unsigned int tospace_first_idx = sspace->tospace_first_idx;
  unsigned int sspace_last_idx = sspace->first_block_idx + sspace->num_managed_blocks - 1;

  /* if to-space is in second half, need to do two connections:
     1. from-space last block to the first block of to-space, 2. connect from-space two parts cross survivor area */
  if(sspace->ceiling_block_idx == sspace_last_idx){
    Block_Header* tospace_first_block = (Block_Header*)&sspace->blocks[tospace_first_idx - sspace->first_block_idx];
    /* For 1. Fromspace has two parts only when tospace is not adjacent to survivor area. */
    if(tospace_first_block != sspace->survivor_area_end){
      Block_Header* block_before_tospace =  (Block_Header*)((Block*)tospace_first_block - 1);
      assert( block_before_tospace->next == NULL);
      block_before_tospace->next = tospace_first_block;
    }
    /* For 2. It doesn't matter if survivor_area size is 0. */
    Block_Header* block_before_survivor_area = (Block_Header*)((Block*)(sspace->survivor_area_start) - 1);
    block_before_survivor_area->next = (Block_Header*)(sspace->survivor_area_start);

  }else{  /* otherwise, tospace is in first half */

    /* Connect last block of from-space to first block of tospacde */
    Block_Header* block_before_tospace = (Block_Header*)&sspace->blocks[tospace_first_idx - sspace->first_block_idx - 1];
    block_before_tospace->next = (Block_Header*)((Block*)block_before_tospace + 1);

  }
  /* in any case, sspace last block's next should point to NULL. This is the case:
     1. when tospace is in second half and has 0 in size.
     2. when tospace is in first half, both tospace and survivor area have 0 in size.
     But the above code sets it to point to the first block of tospace, which is sspace->heap_end and the block is not mapped.
     */
  ((Block_Header*)&(sspace->blocks[sspace->num_managed_blocks - 1]))->next = NULL;

  return;
}

void sspace_reset_after_collection(Sspace* sspace)
{
  /* the space is zero size after major (or variant) collection. No need
     to reset its tospace and fromspace, but still we still set its allocation
     pointer to NULL so that nothing can be allocated. And we need set
     num_used_blocks to 0 in case GC need the data for space tuning whatever. */
  if(sspace->num_managed_blocks == 0) {
    sspace->cur_free_block = NULL;
    sspace->num_used_blocks = 0;
    return;
  }

  Block* blocks = (Block*)sspace->blocks;
   /* During LOS extension, NOS last block points back to MOS first block, so that,
     the first couple blocks of MOS are compacted to NOS end. We need reset the NOS last block next pointer.
     This is needed for next collection. And it's needed for from-space setup,
     so that the last block of from-space points to NULL. */
  Block_Header *sspace_last_block = (Block_Header*)((Block*)sspace->heap_end - 1);

  assert(sspace_last_block);

  sspace_last_block->next = NULL;

  unsigned int sspace_first_idx = sspace->first_block_idx;

  Boolean is_major_collection = collect_is_major();

  if( is_major_collection ){
    /* prepare for from-space, first half */
    sspace_config_after_clean(sspace);

    /* clean up the collected blocks */
    for(unsigned int i = sspace_first_idx; i <= sspace->ceiling_block_idx; i++){
      Block_Header* block = (Block_Header*)&(blocks[i - sspace_first_idx]);
      block_reset(block);
    }

    return;
  }

  /* for minor collection */
  unsigned int num_tospace_blocks = sspace_compute_num_tospace_blocks(sspace);
  unsigned int num_fromspace_blocks = sspace->num_managed_blocks - num_tospace_blocks;
  unsigned int sspace_last_idx = sspace_first_idx + sspace->num_managed_blocks - 1;

    /* clean up the collected blocks */
  unsigned int start_idx = 0;
  unsigned int end_idx = sspace->tospace_first_idx - sspace_first_idx - 1;
  for(unsigned int i = start_idx; i <= end_idx; i++){
    Block_Header* block = (Block_Header*)&(blocks[i]);
    block_reset(block);
  }

  /* when tospace is in first half. clean the part of fromspace after tospace. */
  if(sspace->ceiling_block_idx != sspace_last_idx){
    start_idx = sspace->ceiling_block_idx - sspace_first_idx + 1;
    end_idx = sspace_last_idx - sspace_first_idx;
    for(unsigned int i = start_idx; i <= end_idx; i++){
      Block_Header* block = (Block_Header*)&(blocks[i]);
      block_reset(block);
    }
  }

  sspace->cur_free_block = (Block_Header*)sspace->heap_start;

  /* minor collection always has a survivor area.
    (The size of survivor area can zero if tospace size is zero, e.g., sspace size is to small.
     This is no correctness issue, because it means all sspace objects are forwarded to MOS. )
  */
  sspace->survivor_area_start = (void *)&blocks[sspace->tospace_first_idx - sspace_first_idx];
  sspace->survivor_area_end = (void *)&blocks[sspace->free_block_idx - sspace_first_idx];
  sspace->num_used_blocks = sspace->free_block_idx - sspace->tospace_first_idx;

  /* if the survivor_area of this collection is at first half of sspace */
  if(  sspace->ceiling_block_idx != sspace_last_idx){

    /* Check if suvivor area is overlapped with new tospace. In that case, we should ensure fromspace covers survivor area. */
    if( sspace->survivor_area_end > &(sspace->blocks[num_fromspace_blocks]) ){
     /* this case might happen after nos_boundary adjusted. Since this function is only called before nos_boundary adjustment, that means,
        if execution comes here, it's because of last time minor collection boundary adjustment, and because we don't change the sspace config in minor collection.) */
      num_fromspace_blocks = ((POINTER_SIZE_INT)sspace->survivor_area_end - (POINTER_SIZE_INT)sspace->heap_start) >> GC_BLOCK_SHIFT_COUNT;
      num_tospace_blocks = sspace->num_managed_blocks - num_fromspace_blocks;
    }

    /* prepare for to-space in second half */
    sspace->tospace_first_idx = sspace_first_idx + num_fromspace_blocks;
    sspace->ceiling_block_idx = sspace->tospace_first_idx +  num_tospace_blocks - 1;
    sspace->free_block_idx = sspace->tospace_first_idx;

    /* prepare from-space */
    /* connect the free areas cross survivor area */
    Block_Header* block_before_survivor_area = (Block_Header*)((Block*)sspace->survivor_area_start - 1);
    /* set last block of fromspace next to NULL, if the size of survivor_area is zero or its adjacent to tospace.
       ensure we don't connect fromspace to tospace. */
    /* we intentionally don't use survivor_area_end->block_idx dereference, because survivor_area_end
       might point at the heap_end, which has no mem mapped. */
    if( sspace->survivor_area_end == &(sspace->blocks[num_fromspace_blocks]))
      block_before_survivor_area->next = NULL;
    else{
      block_before_survivor_area->next = (Block_Header*)sspace->survivor_area_end;
      ((Block_Header*)&(sspace->blocks[num_fromspace_blocks-1]))->next = NULL;
    }

  }else{ /* after minor collection, if the survivor_area is at second half of sspace */

    /* Check if sspace has no enough blocks to hold tospace. */
    if( sspace->tospace_first_idx - sspace->first_block_idx <= num_tospace_blocks ){
      /* this case shold never happen right after minor collection, might happen after nos_boundary adjusted */
      assert(0);
      num_tospace_blocks = (sspace->tospace_first_idx - sspace->first_block_idx) >> 3;
      num_fromspace_blocks = sspace->num_managed_blocks - num_tospace_blocks;
    }

    /* prepare for to-space */
    sspace->ceiling_block_idx = sspace->tospace_first_idx - 1;
    sspace->tospace_first_idx = sspace->tospace_first_idx - num_tospace_blocks;
    sspace->free_block_idx = sspace->tospace_first_idx;

    /* prepare for from-space */
    /* connect the free areas cross tospace and survivor_area */
    Block_Header* block_before_tospace = (Block_Header*)&blocks[sspace->tospace_first_idx - 1 - sspace_first_idx];
    /* in case survivor_area_end is heap_end, then block_after_survivor_area should be NULL */
    Block_Header* survivor_area_last_blk = (Block_Header*)((Block*)(sspace->survivor_area_end) - 1);
    block_before_tospace->next = survivor_area_last_blk->next;

  }

  return;
}

#ifndef STATIC_NOS_MAPPING
void* sspace_heap_start_adjust(Sspace* sspace, void* new_space_start, POINTER_SIZE_INT new_space_size)
{
  GC* gc = sspace->gc;

  /* we can simply change certain fields of sspace and keep the original semispace config.
     The issue is, the tospace was computed according to original space size.
     So we just do another round of config after major collection.
     It's troublesome to do config again after minor collection. */

  /* major collection leaves no survivor area in nos */
  if( collect_is_major()){
    /* retore the fromspace last block next pointer. It was set a moment ago in sspace_reset_after_collection. */
    Block_Header* block_before_survivor_area = (Block_Header*)((Block*)(sspace->survivor_area_start) - 1);
    block_before_survivor_area->next = (Block_Header*)(sspace->survivor_area_start);

    blocked_space_adjust((Blocked_Space*)sspace, new_space_start, new_space_size);

    sspace_config_after_clean(sspace);

    return new_space_start;
  }
  /* for minor collection */
  /* always leave at least one free block at the beginning of sspace for fromspace,
     so that sspace->cur_free_block always points to sspace start. */
  void* old_space_start = new_space_start;

  if( new_space_start >= sspace->survivor_area_start)
    new_space_start = (Block*)(sspace->survivor_area_start) - 1;

  void* tospace_start = &(sspace->blocks[sspace->free_block_idx - sspace->first_block_idx]);
  if( new_space_start >= tospace_start)
    new_space_start = (Block*)tospace_start - 1;

  new_space_size += (POINTER_SIZE_INT)old_space_start - (POINTER_SIZE_INT)new_space_start;

  /* change the fields that are changed */
  sspace->heap_start = new_space_start;
  sspace->blocks = (Block*)new_space_start;
  sspace->committed_heap_size = new_space_size;
  sspace->reserved_heap_size = new_space_size;
  sspace->num_managed_blocks = (unsigned int)(new_space_size >> GC_BLOCK_SHIFT_COUNT);
  sspace->num_total_blocks = sspace->num_managed_blocks;
  sspace->first_block_idx = ((Block_Header*)new_space_start)->block_idx;

  sspace->cur_free_block = (Block_Header*)sspace->heap_start;

  return new_space_start;
}
#endif /* #ifndef STATIC_NOS_MAPPING  */

void collector_execute_task(GC* gc, TaskType task_func, Space* space);

/* world is stopped when starting sspace_collection */
#include "../gen/gen.h"  /* for gc_is_gen_mode() */
void sspace_collection(Sspace *sspace)
{
  sspace->num_collections++;

  GC* gc = sspace->gc;

  /* we should not destruct rootset structure in case we need fall back */
  pool_iterator_init(gc->metadata->gc_rootset_pool);

  if(!gc_is_gen_mode()){
#ifdef MARK_BIT_FLIPPING
    TRACE2("gc.process", "GC: nongenerational semispace algo start ... \n");
    collector_execute_task(gc, (TaskType)nongen_ss_pool, (Space*)sspace);
    TRACE2("gc.process", "\nGC: end of nongen semispace pool algo ... \n");
#else
    assert(0);
#endif /*#ifdef MARK_BIT_FLIPPING #else */

  }else{
    TRACE2("gc.process", "generational semispace algo start ... \n");
    collector_execute_task(gc, (TaskType)gen_ss_pool, (Space*)sspace);
    TRACE2("gc.process", "\nGC: end of gen semispace pool algo ... \n");
  }

  return;
}


text:
#ifndef GAPPERIPHBONDMGR_H
#define GAPPERIPHBONDMGR_H

#ifdef __cplusplus
extern "C"
{
#endif

/*-------------------------------------------------------------------
 * INCLUDES
 */
#include "gap.h"

/*-------------------------------------------------------------------
 * CONSTANTS
 */

#if !defined ( GAP_BONDINGS_MAX )
  #define GAP_BONDINGS_MAX    10    //!< Maximum number of bonds that can be saved in NV.
#endif

/** @defgroup GAPBOND_CONSTANTS_NAME GAP Bond Manager Constants
 * @{
 */

/** @} End GAPBOND_CONSTANTS_NAME */

/** @defgroup GAPBOND_PROFILE_PARAMETERS GAP Bond Manager Parameters
 * @{
 */
#define GAPBOND_PAIRING_MODE       0x400  //!< Pairing Mode: @ref  GAPBOND_PAIRING_MODE_DEFINES. Read/Write. Size is uint8. Default is GAPBOND_PAIRING_MODE_WAIT_FOR_REQ.
#define GAPBOND_INITIATE_WAIT      0x401  //!< Pairing Mode Initiate wait timeout.  This is the time it will wait for a Pairing Request before sending the Slave Initiate Request. Read/Write. Size is uint16. Default is 1000(in milliseconds).
#define GAPBOND_MITM_PROTECTION    0x402  //!< Man-In-The-Middle (MITM) basically turns on Passkey protection in the pairing algorithm. Read/Write. Size is uint8. Default is 0(disabled).
#define GAPBOND_IO_CAPABILITIES    0x403  //!< I/O capabilities.  Read/Write. Size is uint8. Default is GAPBOND_IO_CAP_DISPLAY_ONLY @ref GAPBOND_IO_CAP_DEFINES.
#define GAPBOND_OOB_ENABLED        0x404  //!< OOB data available for pairing algorithm. Read/Write. Size is uint8. Default is 0(disabled).
#define GAPBOND_OOB_DATA           0x405  //!< OOB Data. Read/Write. size uint8[16]. Default is all 0's.
#define GAPBOND_BONDING_ENABLED    0x406  //!< Request Bonding during the pairing process if enabled.  Read/Write. Size is uint8. Default is 0(disabled).
#define GAPBOND_KEY_DIST_LIST      0x407  //!< The key distribution list for bonding.  size is uint8.  @ref GAPBOND_KEY_DIST_DEFINES. Default is sEncKey, sIdKey, mIdKey, mSign enabled.
#define GAPBOND_DEFAULT_PASSCODE   0x408  //!< The default passcode for MITM protection. size is uint32. Range is 0 - 999,999. Default is 0.
#define GAPBOND_ERASE_ALLBONDS     0x409  //!< Erase all of the bonded devices. Write Only. No Size.
#define GAPBOND_AUTO_FAIL_PAIRING  0x40A  //!< TEST MODE (DO NOT USE) to automatically send a Pairing Fail when a Pairing Request is received. Read/Write. size is uint8. Default is 0 (disabled).
#define GAPBOND_AUTO_FAIL_REASON   0x40B  //!< TEST MODE (DO NOT USE) Pairing Fail reason when auto failing. Read/Write. size is uint8. Default is 0x05 (SMP_PAIRING_FAILED_NOT_SUPPORTED).
#define GAPBOND_KEYSIZE            0x40C  //!< Key Size used in pairing. Read/Write. size is uint8. Default is 16.
/** @} End GAPBOND_PROFILE_PARAMETERS */

/** @defgroup GAPBOND_PAIRING_MODE_DEFINES GAP Bond Manager Pairing Modes
 * @{
 */
#define GAPBOND_PAIRING_MODE_NO_PAIRING          0x00  //!< Pairing is not allowed
#define GAPBOND_PAIRING_MODE_WAIT_FOR_REQ        0x01  //!< Wait for a pairing request or slave security request
#define GAPBOND_PAIRING_MODE_INITIATE            0x02  //!< Don't wait, initiate a pairing request or slave security request
/** @} End GAPBOND_PAIRING_MODE_DEFINES */

/** @defgroup GAPBOND_IO_CAP_DEFINES GAP Bond Manager I/O Capabilities
 * @{
 */
#define GAPBOND_IO_CAP_DISPLAY_ONLY              0x00  //!< Display Only Device
#define GAPBOND_IO_CAP_DISPLAY_YES_NO            0x01  //!< Display and Yes and No Capable
#define GAPBOND_IO_CAP_KEYBOARD_ONLY             0x02  //!< Keyboard Only
#define GAPBOND_IO_CAP_NO_INPUT_NO_OUTPUT        0x03  //!< No Display or Input Device
#define GAPBOND_IO_CAP_KEYBOARD_DISPLAY          0x04  //!< Both Keyboard and Display Capable
/** @} End GAPBOND_IO_CAP_DEFINES */

/** @defgroup GAPBOND_KEY_DIST_DEFINES GAP Bond Manager Key Distribution
 * @{
 */
#define GAPBOND_KEYDIST_SENCKEY                  0x01  //!< Slave Encryption Key
#define GAPBOND_KEYDIST_SIDKEY                   0x02  //!< Slave IRK and ID information
#define GAPBOND_KEYDIST_SSIGN                    0x04  //!< Slave CSRK
#define GAPBOND_KEYDIST_MENCKEY                  0x08  //!< Master Encrypton Key
#define GAPBOND_KEYDIST_MIDKEY                   0x10  //!< Master IRK and ID information
#define GAPBOND_KEYDIST_MSIGN                    0x20  //!< Master CSRK
/** @} End GAPBOND_IO_CAP_DEFINES */

/** @defgroup GAPBOND_PAIRING_STATE_DEFINES GAP Bond Manager Pairing States
 * @{
 */
#define GAPBOND_PAIRING_STATE_STARTED             0x00  //!< Pairing started
#define GAPBOND_PAIRING_STATE_COMPLETE            0x01  //!< Pairing complete
#define GAPBOND_PAIRING_STATE_BONDED              0x02  //!< Devices bonded
/** @} End GAPBOND_PAIRING_STATE_DEFINES */

/** @defgroup SMP_PAIRING_FAILED_DEFINES Pairing failure status values
 * @{
 */
#define SMP_PAIRING_FAILED_PASSKEY_ENTRY_FAILED   0x01 //!< The user input of the passkey failed, for example, the user cancelled the operation.
#define SMP_PAIRING_FAILED_OOB_NOT_AVAIL          0x02 //!< The OOB data is not available
#define SMP_PAIRING_FAILED_AUTH_REQ               0x03 //!< The pairing procedure can't be performed as authentication requirements can't be met due to IO capabilities of one or both devices
#define SMP_PAIRING_FAILED_CONFIRM_VALUE          0x04 //!< The confirm value doesn't match the calculated compare value
#define SMP_PAIRING_FAILED_NOT_SUPPORTED          0x05 //!< Pairing isn't supported by the device
#define SMP_PAIRING_FAILED_ENC_KEY_SIZE           0x06 //!< The resultant encryption key size is insufficient for the security requirements of this device.
#define SMP_PAIRING_FAILED_CMD_NOT_SUPPORTED      0x07 //!< The SMP command received is not supported on this device.
#define SMP_PAIRING_FAILED_UNSPECIFIED            0x08 //!< Pairing failed due to an unspecified reason
#define SMP_PAIRING_FAILED_REPEATED_ATTEMPTS      0x09 //!< Pairing or authenication procedure is disallowed because too little time has elapsed since the last pairing request or security request.
/** @} End SMP_PAIRING_FAILED_DEFINES */

/*-------------------------------------------------------------------
 * TYPEDEFS
 */
typedef void (*pfnPasscodeCB_t)
(
  uint8  *deviceAddr,                   //!< address of device to pair with, and could be either public or random.
  uint16 connectionHandle,              //!< Connection handle
  uint8  uiInputs,                      //!< Pairing User Interface Inputs - Ask user to input passcode
  uint8  uiOutputs                      //!< Pairing User Interface Outputs - Display passcode
 );

typedef void (*pfnPairStateCB_t)
(
  uint8  state,                         //!< Pairing state @ref GAPBOND_PAIRING_STATE_DEFINES
  uint8  status                         //!< Pairing status
);

/**
 * GAP Bond Manager Callbacks.
 */
typedef struct
{
  pfnPasscodeCB_t     passcodeCB;       //!< Passcode callback
  pfnPairStateCB_t    pairStateCB;      //!< Pairing state callback
} gapBondCBs_t;

/*-------------------------------------------------------------------
 * MACROS
 */

/*-------------------------------------------------------------------
 * API FUNCTIONS
 */

/**
 * @defgroup GAPROLES_BONDMGR_API GAP Bond Manager API Functions
 *
 * @{
 */

/**
 * @brief       Set a GAP Bond Manager parameter.
 *
 *  NOTE: You can call this function with a GAP Parameter ID and it will set the
 *        GAP Parameter.  GAP Parameters are defined in (gap.h).  Also,
 *        the "len" field must be set to the size of a "uint16" and the
 *        "pValue" field must point to a "uint16".
 *
 * @param       param - Profile parameter ID: @ref GAPBOND_PROFILE_PARAMETERS
 * @param       len - length of data to write
 * @param       pValue - pointer to data to write.  This is dependent on
 *          the parameter ID and WILL be cast to the appropriate
 *          data type (example: data type of uint16 will be cast to
 *          uint16 pointer).
 *
 * @return      SUCCESS or INVALIDPARAMETER (invalid paramID)
 */
extern bStatus_t GAPBondMgr_SetParameter( uint16 param, uint8 len, void *pValue );

/**
 * @brief       Get a GAP Bond Manager parameter.
 *
 *  NOTE: You can call this function with a GAP Parameter ID and it will get a
 *        GAP Parameter.  GAP Parameters are defined in (gap.h).  Also, the
 *        "pValue" field must point to a "uint16".
 *
 * @param       param - Profile parameter ID: @ref GAPBOND_PROFILE_PARAMETERS
 * @param       pValue - pointer to location to get the value.  This is dependent on
 *          the parameter ID and WILL be cast to the appropriate
 *          data type (example: data type of uint16 will be cast to
 *          uint16 pointer).
 *
 * @return      SUCCESS or INVALIDPARAMETER (invalid paramID)
 */
extern bStatus_t GAPBondMgr_GetParameter( uint16 param, void *pValue );

/**
 * @brief       Notify the Bond Manager that a connection has been made.
 *
 *   NOTE:      The GAP Peripheral or Peripheral/Broadcaster Role profile will
 *              call this function, if they are included in the project.
 *
 * @param       addrType - device's address type. Reference GAP_ADDR_TYPE_DEFINES in gap.h
 * @param       pDevAddr - device's address
 * @param       connHandle - connection handle
 *
 * @return      SUCCESS, otherwise failure
 */
extern bStatus_t GAPBondMgr_LinkEst( uint8 addrType, uint8 *pDevAddr, uint16 connHandle );

/**
 * @brief       Resolve an address from bonding information.
 *
 * @param       addrType - device's address type. Reference GAP_ADDR_TYPE_DEFINES in gap.h
 * @param       pDevAddr - device's address
 * @param       pResolvedAddr - pointer to buffer to put the resolved address
 *
 * @return      bonding index (0 - (GAP_BONDINGS_MAX-1) if found,
 *              GAP_BONDINGS_MAX if not found
 */
extern uint8 GAPBondMgr_ResolveAddr( uint8 addrType, uint8 *pDevAddr, uint8 *pResolvedAddr );

/**
 * @brief       Set/clear the service change indication in a bond record.
 *
 * @param       connectionHandle - connection handle of the connected device or 0xFFFF
 *                                 if all devices in database.
 * @param       setParam - TRUE to set the service change indication, FALSE to clear it.
 *
 * @return      SUCCESS - bond record found and changed,

 *              bleNoResources - bond record not found (for 0xFFFF connectionHandle),

 *              bleNotConnected - connection not found - connectionHandle is invalid (for non-0xFFFF connectionHandle).
 */
extern bStatus_t GAPBondMgr_ServiceChangeInd( uint16 connectionHandle, uint8 setParam );

/**
 * @brief       Register callback functions with the bond manager.
 *
 *   NOTE:      There is no need to register a passcode callback function
 *              if the passcode will be handled with the GAPBOND_DEFAULT_PASSCODE parameter.
 *
 * @param       pCB - pointer to callback function structure.
 *
 * @return      none
 */
extern void GAPBondMgr_Register( gapBondCBs_t *pCB );

/**
 * @brief       Respond to a passcode request.
 *
 * @param       connectionHandle - connection handle of the connected device or 0xFFFF
 *                                 if all devices in database.
 * @param       status - SUCCESS if passcode is available, otherwise see @ref SMP_PAIRING_FAILED_DEFINES.
 * @param       passcode - integer value containing the passcode.
 *
 * @return      SUCCESS - bond record found and changed,

 *              bleIncorrectMode - Link not found.
 */
extern bStatus_t GAPBondMgr_PasscodeRsp( uint16 connectionHandle, uint8 status, uint32 passcode );

/**
 * @brief       This is a bypass mechanism to allow the bond manager to process
 *              GAP messages.
 *
 *   NOTE:      This is an advanced feature and shouldn't be called unless
 *              the normal GAP Bond Manager task ID registration is overridden.
 *
 * @param       pMsg - GAP event message
 *
 * @return      none
 */
extern void gapBondMgr_ProcessGAPMsg( gapEventHdr_t *pMsg );

/**
 * @brief       This function will check the length of a Bond Manager NV Item.
 *
 * @param       id - NV ID.
 * @param       len - lengths in bytes of item.
 *
 * @return      SUCCESS or FAILURE
 */
extern uint8 GAPBondMgr_CheckNVLen( uint8 id, uint8 len );

/**
 * @} End GAPROLES_BONDMGR_API
 */

/*-------------------------------------------------------------------
 * TASK FUNCTIONS - Don't call these. These are system functions.
 */

/**
 * @internal
 *
 * @brief       Initialization function for the GAP Bond Manager Task.
 *          This is called during initialization and should contain
 *          any application specific initialization (ie. hardware
 *          initialization/setup, table initialization, power up
 *          notificaiton ... ).
 *
 * @param       the ID assigned by OSAL.  This ID should be
 *                    used to send messages and set timers.
 *
 * @return      void
 */
extern void GAPBondMgr_Init( uint8 task_id );

/**
 * @internal
 *
 * @brief       GAP Bond Manager Task event processor.
 *          This function is called to process all events for the task.
 *          Events include timers, messages and any other user defined
 *          events.
 *
 * @param   task_id  - The OSAL assigned task ID.
 * @param   events - events to process.  This is a bit map and can
 *                   contain more than one event.
 *
 * @return      events not processed
 */
extern uint16 GAPBondMgr_ProcessEvent( uint8 task_id, uint16 events );

/*-------------------------------------------------------------------
-------------------------------------------------------------------*/

#ifdef __cplusplus
}
#endif

#endif /* GAPPERIPHBONDMGR_H */


text:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="msu.ece.xiaozeng.mpf3.ShowPillActivity"
    tools:showIn="@layout/activity_show_pill">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <LinearLayout
            android:orientation="horizontal"
            android:layout_width="match_parent"
            android:layout_height="150dp"
            android:id="@+id/image_part">

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                app:srcCompat="@drawable/sb_10_942b4a7a"
                android:id="@+id/iv_pill_front_pic"
                android:layout_weight="1" />

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                app:srcCompat="@drawable/sb_12_c029e06f"
                android:id="@+id/iv_pill_back_pic"
                android:layout_weight="1" />

        </LinearLayout>

        <LinearLayout
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/image_part"
            android:layout_margin="10dp"
            android:background="@drawable/pill_detail_background">

            <LinearLayout
                android:orientation="vertical"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_margin="10dp"
>

                <TextView
                android:text="Pill Name"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textSize="15sp"
                android:textStyle="bold" android:layout_marginTop="15dp"/>

                <TextView
                    android:text="Name"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:textSize="25sp"
                    android:id="@+id/tv_pill_name"
                    android:textColor="@color/colorPrimary"
                    android:textStyle="bold"
                    android:layout_marginLeft="25dp"
                    />

                <TextView
                    android:text="Pill Color"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:textSize="15sp"
                    android:layout_marginTop="10dp"
                    android:textStyle="bold"/>

                <TextView
                    android:text="Color"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:textSize="25sp"
                    android:id="@+id/tv_pill_color"
                    android:textColor="#000000"
                    android:textStyle="bold"
                    android:layout_marginLeft="25dp"/>

                <TextView
                    android:text="Pill Imprint"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:textSize="15sp"
                    android:layout_marginTop="10dp"
                    android:textStyle="bold"/>

                <TextView
                    android:text="Imprint"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:textSize="25sp"
                    android:id="@+id/tv_pill_imprint"
                    android:textColor="#000000"
                    android:textStyle="bold"
                    android:layout_marginLeft="25dp"/>

                <TextView
                    android:text="Description"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:textSize="15sp"
                    android:layout_marginTop="10dp"
                    android:textStyle="bold"/>

                <TextView
                    android:text="@string/pill_description"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:textSize="15sp"
                    android:id="@+id/tv_pill_color"
                    android:textColor="#000000"
                    android:textStyle="bold"
                    android:layout_marginLeft="20dp"/>

            </LinearLayout>
        </LinearLayout>

    </RelativeLayout>
</android.support.v4.widget.NestedScrollView>


text:
require "util"
require "defines"

script.on_event(defines.events.on_tick, function(event)

	counter = game.tick

	if game.player.gui.top.mapCoord == nil then
		game.player.gui.top.add{type="label", name="mapCoord", caption="0, 0"}
		game.player.gui.left.add{type="label", name="tileName", caption="Tile: "}
	end

	if counter % 10 == 0 then
		printCoord()
		checkItem()
		--game.player.print(game.player.surface.name)
		--game.player.print(math.floor(game.player.position["x"]) .. ", " .. math.floor(game.player.position["y"]))
	end

end)

function printCoord()
	game.player.gui.top.mapCoord.caption = math.floor(game.player.position["x"]) .. ", " .. math.floor(game.player.position["y"]) .. " Tick: " .. game.tick
end

function checkItem()

	entityName = game.surfaces["nauvis"].find_entities{{math.floor(game.player.position["x"]), math.floor(game.player.position["y"])}, {math.floor(game.player.position["x"]) + 1, math.floor(game.player.position["y"]) + 1}}

	if entityName then
		if entityName[2] then
			enName = entityName[2].name
			game.write_file("ServerMap.out", math.floor(game.player.position["x"]) .. "," .. math.floor(game.player.position["y"]) .. "," .. enName .. "\n", true)
		else
			enName = ""
		end
		game.player.gui.left.tileName.caption = " Tile: " .. game.surfaces["nauvis"].get_tile(game.player.position["x"], game.player.position["y"]).name .. " --- Entity: " .. enName
	end

end


text:
{{'AdmServicePage' | translate}}

{{$ctrl.messageText | translate}}

{{'ServicePageAdd' | translate}}

<form class="form-adm">

        {{'AdmServiceTemplate' | translate}}
        <input class="form-control" type="hidden" id="" ng-model="$ctrl.item.id">
        <input class="form-control" type="text" id="abTemplate" ng-model="$ctrl.item.nameTemplate">

        {{'AdmMenuItemBind' | translate}}
        <select id="menuUri" class="form-control" ng-model="$ctrl.item.menuItemId">
            <option ng-repeat="menuItem in $ctrl.menuList track by $index" ng-value="menuItem.id">{{menuItem.name | translate}}</option>
        </select>

        {{'AdmServiceDescTemplate' | translate}}
        <input class="form-control" type="text" id="descTemplate" ng-model="$ctrl.item.descTemplate">

    <button type="submit" class="btn btn-success" ng-click="$ctrl.saveItem()">{{'AdmSave' | translate}}</button>
</form>

{{'AdmServicePages' | translate}}

                                    <input type="file" nv-file-select="" id="fileSelect{{item.id}}" accept="" uploader="$ctrl.uploader" options="{formData: [{id: item.id}], queueLimit: 1}" class="hide">

                                <button ng-show="item.icon" class="glyphicon glyphicon-remove pos-top-right" aria-hidden="true" ng-click="$ctrl.deleteIcon(item)"></button>

                                    <input type="file" nv-file-select="" id="fileSelectBg{{item.id}}" accept="" uploader="$ctrl.uploaderBg" options="{formData: [{id: item.id}], queueLimit: 1}" class="hide">

                                <button ng-show="item.background" class="glyphicon glyphicon-remove pos-top-right" aria-hidden="true" ng-click="$ctrl.deleteBackground(item)"></button>

{{item.name_template | translate}}

                                            <button class="glyphicon glyphicon-edit" aria-hidden="true" ng-click="$ctrl.editItem(item)" tooltip-placement="top" uib-tooltip="{{'editItem' | translate}}"></button>
                                            <button class="glyphicon glyphicon-remove" aria-hidden="true" ng-click="$ctrl.deleteItem(item.id)" tooltip-placement="top" uib-tooltip="{{'deleteItem' | translate}}"></button>
                                            <button class="glyphicon glyphicon-picture" aria-hidden="true" ui-sref="app.admin.service.images({idService: item.id})" tooltip-placement="top" uib-tooltip="{{'editImages' | translate}}"></button>

<ui-view></ui-view>


text:
  <%= member.user().get("name") %>

  <a href="mailto:<%= member.user().get('email') %>"><%= member.user().get("email") %>

  <%= member.get("level") %>
  <select name="level" id="level" />

  <%= member.get("role") %>
  <select name="role" id="role" />

remove


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Mycena cyaneobasis Peck

### Remarks
null


text:
package mux

import (
	"time"

	"github.com/Shopify/sarama"

	"go.ligato.io/cn-infra/v2/config"
	"go.ligato.io/cn-infra/v2/logging"
	"go.ligato.io/cn-infra/v2/messaging/kafka/client"
	"go.ligato.io/cn-infra/v2/utils/clienttls"
)

const (
	// DefAddress default kafka address/port (if not specified in config)
	DefAddress = "127.0.0.1:9092"
	// DefPartition is used if no specific partition is set
	DefPartition = 0
	// OffsetNewest is head offset which will be assigned to the new message produced to the partition
	OffsetNewest = sarama.OffsetNewest
	// OffsetOldest is oldest offset available on the partition
	OffsetOldest = sarama.OffsetOldest
)

// Config holds the settings for kafka multiplexer.
type Config struct {
	Addrs   []string      `json:"addrs"`
	GroupID string        `json:"group_id"`
	TLS     clienttls.TLS `json:"tls"`
}

// ConsumerFactory produces a consumer for the selected topics in a specified consumer group.
// The reason why a function(factory) is passed to Multiplexer instead of consumer instance is
// that list of topics to be consumed has to be known on consumer initialization.
// Multiplexer calls the function once the list of topics to be consumed is selected.
type ConsumerFactory func(topics []string, groupId string) (*client.Consumer, error)

// ConfigFromFile loads the Kafka multiplexer configuration from the
// specified file. If the specified file is valid and contains
// valid configuration, the parsed configuration is
// returned; otherwise, an error is returned.
func ConfigFromFile(fpath string) (*Config, error) {
	cfg := &Config{}
	err := config.ParseConfigFromYamlFile(fpath, cfg)
	if err != nil {
		return nil, err
	}
	return cfg, err
}

func getConsumerFactory(config *client.Config) ConsumerFactory {
	return func(topics []string, groupId string) (*client.Consumer, error) {
		config.SetRecvMessageChan(make(chan *client.ConsumerMessage))
		config.Topics = topics
		config.GroupID = groupId
		config.SetInitialOffset(sarama.OffsetOldest)

		// create new consumer and start message handlers
		return client.NewConsumer(config, nil)
	}
}

// InitMultiplexer initialize and returns new kafka multiplexer based on the supplied config file.
// Name is used as groupId identification of consumer. Kafka allows to store last read offset for
// a groupId. This is leveraged to deliver unread messages after restart.
func InitMultiplexer(configFile string, name string, log logging.Logger) (*Multiplexer, error) {
	var err error
	var tls clienttls.TLS
	cfg := &Config{[]string{DefAddress}, "", tls}
	if configFile != "" {
		cfg, err = ConfigFromFile(configFile)
		if err != nil {
			return nil, err
		}
	}

	// prepare client config
	clientCfg := client.NewConfig(log)
	clientCfg.SetSendSuccess(true)
	clientCfg.SetSuccessChan(make(chan *client.ProducerMessage))
	clientCfg.SetSendError(true)
	clientCfg.SetErrorChan(make(chan *client.ProducerError))
	clientCfg.SetBrokers(cfg.Addrs...)
	if cfg.TLS.Enabled {
		tlsConfig, err := clienttls.CreateTLSConfig(cfg.TLS)
		if err != nil {
			return nil, err
		}
		clientCfg.SetTLS(tlsConfig)
	}

	// create hash client
	sClientHash, err := client.NewClient(clientCfg, client.Hash)
	if err != nil {
		return nil, err
	}

	// create manual client
	sClientManual, err := client.NewClient(clientCfg, client.Manual)
	if err != nil {
		return nil, err
	}

	// todo client is currently set always as hash
	return InitMultiplexerWithConfig(clientCfg, sClientHash, sClientManual, name, log)
}

// InitMultiplexerWithConfig initialize and returns new kafka multiplexer based on the supplied mux configuration.
// Name is used as groupId identification of consumer. Kafka allows to store last read offset for a groupId.
// This is leveraged to deliver unread messages after restart.
func InitMultiplexerWithConfig(clientCfg *client.Config, hsClient sarama.Client, manClient sarama.Client, name string, log logging.Logger) (*Multiplexer, error) {
	const errorFmt = "Failed to create Kafka %s, Configured broker(s) %v, Error: '%s'"

	log.WithField("addrs", hsClient.Brokers()).Debug("Kafka connecting")

	startTime := time.Now()
	producers := multiplexerProducers{}

	// Prepare sync/async producer
	if hsClient != nil {
		hashSyncProducer, err := client.NewSyncProducer(clientCfg, hsClient, client.Hash, nil)
		if err != nil {
			log.Errorf(errorFmt, "SyncProducer (hash)", clientCfg.Brokers, err)
			return nil, err
		}
		hashAsyncProducer, err := client.NewAsyncProducer(clientCfg, hsClient, client.Hash, nil)
		if err != nil {
			log.Errorf(errorFmt, "AsyncProducer", clientCfg.Brokers, err)
			return nil, err
		}
		producers.hashSyncProducer = hashSyncProducer
		producers.hashAsyncProducer = hashAsyncProducer
	}
	// Prepare manual sync/async producer
	if manClient != nil {
		manualSyncProducer, err := client.NewSyncProducer(clientCfg, manClient, client.Manual, nil)
		if err != nil {
			log.Errorf(errorFmt, "SyncProducer (manual)", clientCfg.Brokers, err)
			return nil, err
		}

		manualAsyncProducer, err := client.NewAsyncProducer(clientCfg, manClient, client.Manual, nil)
		if err != nil {
			log.Errorf(errorFmt, "AsyncProducer", clientCfg.Brokers, err)
			return nil, err
		}
		producers.manSyncProducer = manualSyncProducer
		producers.manAsyncProducer = manualAsyncProducer
	}

	kafkaConnect := time.Since(startTime)
	log.WithField("durationInNs", kafkaConnect.Nanoseconds()).Info("Connecting to kafka took ", kafkaConnect)

	return NewMultiplexer(getConsumerFactory(clientCfg), producers, clientCfg, name, log), nil
}