text:
(function (root, factory) {

	if (typeof define === "function" && define.amd) {
		define(factory);
	} else if (typeof exports === "object") {
		module.exports = factory();
	} else {
		root.way = factory();
	}

}(this, function () {

	"use strict";

	var way, w, tagPrefix = "way";

	//////////////////////////////
	// EVENT EMITTER DEFINITION //
	//////////////////////////////

	var EventEmitter = function () {

		this._watchers = {};
		this._watchersAll = {};

	};

	EventEmitter.prototype.constructor = EventEmitter;

	EventEmitter.prototype.watchAll = function(handler) {

		this._watchersAll = this._watchersAll || [];
		if (!_w.contains(this._watchersAll, handler)) { this._watchersAll.push(handler); }

	}

	EventEmitter.prototype.watch = function(selector, handler) {

		if (!this._watchers) { this._watchers = {}; }
		this._watchers[selector] = this._watchers[selector] || [];
		this._watchers[selector].push(handler);

	}

	EventEmitter.prototype.findWatcherDeps = function(selector) {

		// Go up to look for parent watchers
		// ex: if "some.nested.value" is the selector, it should also trigger for "some"

		var result = [];
		var watchers = _w.keys(this._watchers);
		watchers.forEach(function(watcher) {
			if (startsWith(selector, watcher)) { result.push(watcher); }
		});
		return result;

	}

	EventEmitter.prototype.emitChange = function(selector /* , arguments */) {

		if (!this._watchers) { this._watchers = {}; }

		var self = this;

		// Send data down to the local watchers
		var deps = self.findWatcherDeps(selector);
		deps.forEach(function(item) {
			if (self._watchers[item]) {
				self._watchers[item].forEach(function(handler) {
					handler.apply(self, [self.get(item)]);
				});
			}
		});

		// Send data down to the global watchers
		if (!self._watchersAll || !_w.isArray(self._watchersAll)) { return; }
		self._watchersAll.forEach(function(watcher) {
			if (_w.isFunction(watcher)) { watcher.apply(self, [selector, self.get(selector)]); }
		});

	}

	////////////////////
	// WAY DEFINITION //
	////////////////////

	var WAY = function () {

		this.data = {};
		this._bindings = {};
		this.options = {
			persistent: true,
			timeoutInput: 50,
			timeoutDOM: 500
		};

	};

	// Inherit from EventEmitter
	WAY.prototype = Object.create(EventEmitter.prototype);
	WAY.constructor = WAY;

	//////////////////////////
	// DOM METHODS CHAINING //
	//////////////////////////

	WAY.prototype.dom = function(element) {

		this._element = w.dom(element).get(0);
		return this;

	};

	//////////////////////////////
	// DOM METHODS: DOM -> JSON //
	//////////////////////////////

	WAY.prototype.toStorage = function(options, element) {

		var self = this,
			element = element || self._element,
			options = options || self.dom(element).getOptions(),
			data = self.dom(element).toJSON(options),
			scope = self.dom(element).scope(),
			selector = scope ? scope + "." + options.data : options.data;

		if (options.readonly) { return false; }
		self.set(selector, data, options);

	}

	WAY.prototype.toJSON = function(options, element) {

		var self = this,
			element = element || self._element,
			data = self.dom(element).getValue(),
			options = options || self.dom(element).getOptions();

		if (_w.isArray(options.pick)) { data = selectNested(data, options.pick, true); }
		if (_w.isArray(options.omit)) { data = selectNested(data, options.omit, false); }

		return data;

	}

	//////////////////////////////
	// DOM METHODS: JSON -> DOM //
	//////////////////////////////

	WAY.prototype.fromStorage = function(options, element) {

		var self = this,
			element = element || self._element,
			options = options || self.dom(element).getOptions();

		if (options.writeonly) { return false; }

		var scope = self.dom(element).scope(),
				selector = scope ? scope + "." + options.data : options.data,
				data = self.get(selector);

		self.dom(element).fromJSON(data, options);

	}

	WAY.prototype.fromJSON = function(data, options, element) {

		var self = this,
				element = element || self._element,
				options = options || self.dom(element).getOptions();

		if (options.writeonly) { return false; }

		if (_w.isObject(data)) {
			if (_w.isArray(options.pick)) { data = selectNested(data, options.pick, true); }
			if (_w.isArray(options.omit)) { data = selectNested(data, options.omit, false); }
			var currentData = _w.isObject(self.dom(element).toJSON()) ? self.dom(element).toJSON() : {};
			data = _w.extend(currentData, data);
		}

		if (options.json) { data = _json.isStringified(data) ? data : _json.prettyprint(data); }

		self.dom(element).setValue(data, options);

	}

	/////////////////////////////////
	// DOM METHODS: GET - SET HTML //
	/////////////////////////////////

	WAY.prototype.getValue = function(element) {

		var self = this,
			element = element || self._element;

		var getters = {
			"SELECT": function() {
				return w.dom(element).val();
			},
			"INPUT": function() {
				var type = w.dom(element).type();
				if (_w.contains(["text", "password"], type)) {
					return w.dom(element).val();
				}
				if (_w.contains(["checkbox", "radio"], type)) {
					return w.dom(element).prop("checked") ? w.dom(element).val() : null;
				}

			},
			"TEXTAREA": function() {
				return w.dom(element).val();
			}
		}
		var defaultGetter = function(a) {
			return w.dom(element).html();
		}

		var elementType = w.dom(element).get(0).tagName;
		var getter = getters[elementType] || defaultGetter;
		return getter();

	}

	WAY.prototype._transforms = {
		uppercase: function(data) {
			return _w.isString(data) ? data.toUpperCase() : data;
		},
		lowercase: function(data) {
			return _w.isString(data) ? data.toLowerCase() : data;
		},
		reverse: function(data) {
			return data && data.split && _w.isFunction(data.split) ? data.split("").reverse().join("") : data;
		}
	};

	WAY.prototype.registerTransform = function(name, transform) {
		var self = this;
		if (_w.isFunction(transform)) { self._transforms[name] = transform; }
	}

	WAY.prototype.setValue = function(data, options, element) {

		var self = this,
			element = element || self._element,
			options = options || self.dom(element).getOptions();

		options.transform = options.transform || [];
		options.transform.forEach(function(transformName) {
			var transform = self._transforms[transformName] || function(data) { return data };
			data = transform(data);
		});

		var setters = {

			"SELECT": function(a) {
				w.dom(element).val(a);
			},
			"INPUT": function(a) {
				if (!_w.isString(a)) { a = JSON.stringify(a); }
				var type = w.dom(element).get(0).type;
				if (_w.contains(["text", "password"], type)) {
					w.dom(element).val(a || "");
				}
				if (_w.contains(["checkbox", "radio"], type)) {
					if (a === w.dom(element).val()) {
						w.dom(element).prop("checked", true);
					} else {
						w.dom(element).prop("checked", false);
					}
				}
			},
			"TEXTAREA": function(a) {
				if (!_w.isString(a)) { a = JSON.stringify(a); }
				w.dom(element).val(a || "");
			},
			"PRE": function(a) {
				if (options.html) {
					w.dom(element).html(a);
				} else {
					w.dom(element).text(a);
				}
			},
			"IMG": function(a) {

				if (!a) {
					a = options.default || "";
					w.dom(element).attr("src", a);
					return false;
				}

				var isValidImageUrl = function(url, cb) {
					w.dom(element).addClass("way-loading");
					w.dom("img", {
						src: url,
						onerror: function() { cb(false); },
						onload: function() { cb(true); }
					});
				}

				isValidImageUrl(a, function(response) {
					w.dom(element).removeClass("way-loading");
					if (response) {
						w.dom(element).removeClass("way-error").addClass("way-success");
					} else {
						if (a) {
							w.dom(element).addClass("way-error");
						} else {
							w.dom(element).removeClass("way-error").removeClass("way-success");
						}
						a = options.default || "";
					}
					w.dom(element).attr("src", a);
				});

			}

		}
		var defaultSetter = function(a) {

			if (options.html) {
				w.dom(element).html(a);
			} else {
				w.dom(element).text(a);
			}

		}

		var elementType = w.dom(element).get(0).tagName;
		var setter = setters[elementType] || defaultSetter;
		setter(data);

	}

	WAY.prototype.setDefault = function(force, options, element) {

		var self = this,
			element = element || self._element,
			force = force || false,
			options = options ? _w.extend(self.dom(element).getOptions(), options) : self.dom(element).getOptions();

		// Should we just set the default value in the DOM, or also in the datastore?
		if (!options.default) { return false; }
		if (force) {
			self.set(options.data, options.default, options);
		} else {
			self.dom(element).setValue(options.default, options);
		}

	}

	WAY.prototype.setDefaults = function() {

		var self = this,
			dataSelector = "[" + tagPrefix + "-default]";

		var elements = w.dom(dataSelector).get();
		for (var i in elements) {
			var element = elements[i],
					options = self.dom(element).getOptions(),
					selector = options.data || null,
					data = selector ? self.get(selector) : null;
			if (!data) { self.dom(element).setDefault(); }
		}

	}

	/////////////////////////////////////
	// DOM METHODS: GET - SET BINDINGS //
	/////////////////////////////////////

	// Scans the DOM to look for new bindings
	WAY.prototype.registerBindings = function() {

		// Dealing with bindings removed from the DOM by just resetting all the bindings all the time.
		// Isn't there a better way?
		// One idea would be to add a "way-bound" class to bound elements
		// self._bindings = {};

		var self = this;
		var selector = "[" + tagPrefix + "-data]";
		self._bindings = {};

		var elements = w.dom(selector).get();
		for (var i in elements) {
			var element = elements[i],
					options = self.dom(element).getOptions(),
					scope = self.dom(element).scope(),
					selector = scope ? scope + "." + options.data : options.data;

			self._bindings[selector] = self._bindings[selector] || [];
			if (!_w.contains(self._bindings[selector], w.dom(element).get(0))) {
				self._bindings[selector].push(w.dom(element).get(0));
			}

		}

	}

	WAY.prototype.updateBindings = function(selector) {

		var self = this;
				self._bindings = self._bindings || {};

		// Set bindings for the data selector
		var bindings = pickAndMergeParentArrays(self._bindings, selector);
		bindings.forEach(function(element) {
			var focused = (w.dom(element).get(0) === w.dom(":focus").get(0)) ? true : false;
			if (!focused) { self.dom(element).fromStorage(); }
		});

		// Set bindings for the global selector
		if (self._bindings["__all__"]) {
			self._bindings["__all__"].forEach(function(element) {
				self.dom(element).fromJSON(self.data);
			});
		}

	}

	////////////////////////////////////
	// DOM METHODS: GET - SET REPEATS //
	////////////////////////////////////

	WAY.prototype.registerRepeats = function() {

		// Register repeats
		var self = this;
		var selector = "[" + tagPrefix + "-repeat]";
		self._repeats = self._repeats || {};
		self._repeatsCount = self._repeatsCount || 0;

		var elements = w.dom(selector).get();
		for (var i in elements) {
			var element = elements[i],
					options = self.dom(element).getOptions();

			self._repeats[options.repeat] = self._repeats[options.repeat] || [];

			var wrapperAttr = tagPrefix + "-repeat-wrapper=\"" + self._repeatsCount + "\"",
					parent = w.dom(element).parent("[" + wrapperAttr + "]");
			if (!parent.length) {

				self._repeats[options.repeat].push({
					id: self._repeatsCount,
					element: w.dom(element).clone(true).removeAttr(tagPrefix + "-repeat").removeAttr(tagPrefix + "-filter").get(0),
					selector: options.repeat,
					filter: options.filter
				});

				var wrapper = document.createElement("div");
				w.dom(wrapper).attr(tagPrefix + "-repeat-wrapper", self._repeatsCount);
				w.dom(wrapper).attr(tagPrefix + "-scope", options.repeat);
				if (options.filter) { w.dom(wrapper).attr(tagPrefix + "-filter", options.filter); }

				w.dom(element).replaceWith(wrapper);
				self.updateRepeats(options.repeat);

				self._repeatsCount++;

			}

		}

	}

	/*
	WAY.prototype._filters = {
		noFalsy: function(item ) {
			if (!item) {
				return false;
			} else {
				return true;
			}
		}
	};

	WAY.prototype.registerFilter = function(name, filter) {
		var self = this;
		if (_w.isFunction(filter)) { self._filters[name] = filter; }
	}
	*/

	WAY.prototype.updateRepeats = function(selector) {

		var self = this;
			self._repeats = self._repeats || {};

		var repeats = pickAndMergeParentArrays(self._repeats, selector);

		repeats.forEach(function(repeat) {

			var wrapper = "[" + tagPrefix + "-repeat-wrapper=\"" + repeat.id + "\"]",
					data = self.get(repeat.selector),
					items = [];

			repeat.filter = repeat.filter || [];
			w.dom(wrapper).empty();

			for (var key in data) {

				/*
				var item = data[key],
						test = true;
				for (var i in repeat.filter) {
					var filterName = repeat.filter[i];
					var filter = self._filters[filterName] || function(data) { return data };
					test = filter(item);
					if (!test) { break; }
				}
				if (!test) { continue; }
				*/

				w.dom(repeat.element).attr(tagPrefix + "-scope", key);
				var html = w.dom(repeat.element).get(0).outerHTML;
				html = html.replace(/\$\$key/gi, key);
				items.push(html);

			}

			w.dom(wrapper).html(items.join(""));
			self.registerBindings();
			self.updateBindings();

		});

	}

	////////////////////////
	// DOM METHODS: FORMS //
	////////////////////////

	WAY.prototype.updateForms = function() {

		// If we just parse the forms with form2js (see commits before 08/19/2014) and set the data with way.set(),
		// we reset the entire data for this pathkey in the datastore. It causes the bug
		// reported here: https://github.com/gwendall/way.js/issues/10
		// Solution:
		// 1. watch new forms with a [way-data] attribute
		// 2. remove this attribute
		// 3. attach the appropriate attributes to its child inputs
		// -> so that each input is set separately to way.js' datastore

		var self = this;
		var selector = "form[" + tagPrefix + "-data]";

		var elements = w.dom(selector).get();
		for (var i in elements) {

			var form = elements[i],
					options = self.dom(form).getOptions(),
					formDataSelector = options.data;
			w.dom(form).removeAttr(tagPrefix + "-data");

			// Reverse needed to set the right index for "[]" names
			var inputs = w.dom(form).find("[name]").reverse().get();
			for (var i in inputs) {

				var input = inputs[i],
						name = w.dom(input).attr("name");

				if (endsWith(name, "[]")) {
					var array = name.split("[]")[0],
							arraySelector = "[name^='" + array + "']",
							arrayIndex = w.dom(form).find(arraySelector).get().length;
					name = array + "." + arrayIndex;
				}
				var selector = formDataSelector + "." + name;
				options.data = selector;
				self.dom(input).setOptions(options);
				w.dom(input).removeAttr("name");

			}

		}

	}

	/////////////////////////////////////////////
	// DOM METHODS: GET - SET ALL DEPENDENCIES //
	/////////////////////////////////////////////

	WAY.prototype.registerDependencies = function() {

		this.registerBindings();
		this.registerRepeats();

	}

	WAY.prototype.updateDependencies = function(selector) {

		this.updateBindings(selector);
		this.updateRepeats(selector);
		this.updateForms(selector);

	}

	//////////////////////////////////
	// DOM METHODS: OPTIONS PARSING //
	//////////////////////////////////

	WAY.prototype.setOptions = function(options, element) {

			var self = this,
					element = self._element || element;

			for (var k in options) {
				var attr = tagPrefix + "-" + k,
						value = options[k];
				w.dom(element).attr(attr, value);
			}

	}

	WAY.prototype.getOptions = function(element) {

		var self = this,
			element = element || self._element,
			defaultOptions = {
				data: null,
				html: false,
				readonly: false,
				writeonly: false,
				persistent: false
			};
		return _w.extend(defaultOptions, self.dom(element).getAttrs(tagPrefix));

	}

	WAY.prototype.getAttrs = function(prefix, element) {

		var self = this,
				element = element || self._element;

		var parseAttrValue = function(key, value) {

			var attrTypes = {
				pick: "array",
				omit: "array",
				readonly: "boolean",
				writeonly: "boolean",
				json: "boolean",
				html: "boolean",
				persistent: "boolean"
			};

			var parsers = {
				array: function(value) {
					return value.split(",");
				},
				boolean: function(value) {
					if (value === "true") { return true; }
					if (value === "false") { return false; }
					return true;
				}
			};
			var defaultParser = function() { return value; };
			var valueType = attrTypes[key] || null;
			var parser = parsers[valueType] || defaultParser;

			return parser(value);

		}

		var attributes = {};
		var attrs = [].slice.call(w.dom(element).get(0).attributes);
		attrs.forEach(function(attr) {
			var include = (prefix && startsWith(attr.name, prefix + "-")) ? true : false;
			if (include) {
				var name = (prefix) ? attr.name.slice(prefix.length + 1, attr.name.length) : attr.name;
				var value = parseAttrValue(name, attr.value);
				if (_w.contains(["transform", "filter"], name)) { value = value.split("|"); }
				attributes[name] = value;
			}
		});

		return attributes;

	}

	//////////////////////////
	// DOM METHODS: SCOPING //
	//////////////////////////

	WAY.prototype.scope = function(options, element) {

		var self = this,
				element = element || self._element,
				scopeAttr = tagPrefix + "-scope",
				scopeBreakAttr = tagPrefix + "-scope-break",
				scopes = [],
				scope = "";

		var parentsSelector = "[" + scopeBreakAttr + "], [" + scopeAttr + "]";
		var elements = w.dom(element).parents(parentsSelector).get();
		for (var i in elements) {
			var el = elements[i];
			if (w.dom(el).attr(scopeBreakAttr)) { break; }
			var attr = w.dom(el).attr(scopeAttr);
			scopes.unshift(attr);
		}
		if (w.dom(element).attr(scopeAttr)) { scopes.push(w.dom(element).attr(scopeAttr)); }
		if (w.dom(element).attr(scopeBreakAttr)) { scopes = []; }

		scope = _w.compact(scopes).join(".");

		return scope;

	}

	//////////////////
	// DATA METHODS //
	//////////////////

	WAY.prototype.get = function(selector) {

		var self = this;
		if (selector !== undefined && !_w.isString(selector)) { return false; }
		if (!self.data) { return {}; }
		return selector ? _json.get(self.data, selector) : self.data;

	}

	WAY.prototype.set = function(selector, value, options) {

		if (!selector) { return false; }
		if (selector.split(".")[0] === "this") {
			console.log("Sorry, \"this\" is a reserved word in way.js");
			return false;
		}

		var self = this;
		options = options || {};

		if (selector) {

			if (!_w.isString(selector)) { return false; }
			self.data = self.data || {};
			self.data = selector ? _json.set(self.data, selector, value) : {};

			self.updateDependencies(selector);
			self.emitChange(selector, value);
			if (options.persistent) { self.backup(selector); }
		}

	}

	WAY.prototype.push = function(selector, value, options) {

		if (!selector) { return false; }

		var self = this;
		options = options || {};

		if (selector) {
			self.data = selector ? _json.push(self.data, selector, value, true) : {};
		}

		self.updateDependencies(selector);
		self.emitChange(selector, null);
		if (options.persistent) { self.backup(selector); }

	}

	WAY.prototype.remove = function(selector, options) {

		var self = this;
		options = options || {};

		if (selector) {
			self.data = _json.remove(self.data, selector);
		} else {
			self.data = {};
		}

		self.updateDependencies(selector);
		self.emitChange(selector, null);
		if (options.persistent) { self.backup(selector); }

	}

	WAY.prototype.clear = function() {

		this.remove(null, { persistent: true });

	}

	//////////////////////////
	// LOCALSTORAGE METHODS //
	//////////////////////////

	WAY.prototype.backup = function() {

		var self = this;
		if (!self.options.persistent) { return; }
		try {
			var data = self.data || {};
			localStorage.setItem(tagPrefix, JSON.stringify(data));
		} catch(e) {
			console.log("Your browser does not support localStorage.");
		}

	}

	WAY.prototype.restore = function() {

		var self = this;
		if (!self.options.persistent) { return; }
		try {
			var data = localStorage.getItem(tagPrefix);
			try {
				data = JSON.parse(data);
				for (var key in data) {
					self.set(key, data[key]);
				}
			} catch(e) {}
		} catch(e) {
			console.log("Your browser does not support localStorage.");
		}

	}

	//////////
	// MISC //
	//////////

	var matchesSelector = function(el, selector) {
		var matchers = ["matches", "matchesSelector", "webkitMatchesSelector", "mozMatchesSelector", "msMatchesSelector", "oMatchesSelector"],
				fn = null;
		for (var i in matchers) {
			fn = matchers[i];
			if (_w.isFunction(el[fn])) {
				return el[fn](selector);
			}
		}
		return false;
	}

	var startsWith = function(str, starts) {

		if (starts === "") { return true; }
		if (str === null || starts === null) { return false; }
		str = String(str); starts = String(starts);
		return str.length >= starts.length && str.slice(0, starts.length) === starts;

	}

	var endsWith = function(str, ends) {

		if (ends === "") { return true; }
		if (str === null || ends === null) { return false; }
		str = String(str); ends = String(ends);
		return str.length >= ends.length && str.slice(str.length - ends.length, str.length) === ends;

	}

	var cleanEmptyKeys = function(object) {

		return _w.pick(object, _w.compact(_w.keys(object)));

	}

	var filterStartingWith = function(object, string, type) { // true: pick - false: omit

		var keys = _w.keys(object);
		keys.forEach(function(key) {
			if (type) {
				if (!startsWith(key, string)) { delete object[key]; }
			} else {
				if (startsWith(key, string)) { delete object[key]; }
			}
		});
		return object;

	}

	var selectNested = function(data, keys, type) { // true: pick - false: omit

		// Flatten / unflatten to allow for nested picks / omits (doesn't work with regular pick)
		// ex:  data = {something:{nested:"value"}}
		//		keys = ['something.nested']

		var flat = _json.flatten(data);
		for (var i in keys) flat = filterStartingWith(flat, keys[i], type);
		var unflat = _json.unflatten(flat);
		// Unflatten returns an object with an empty property if it is given an empty object
		return cleanEmptyKeys(unflat);

	}

	var pickAndMergeParentArrays = function(object, selector) {

		// Example:
		// object = { a: [1,2,3], a.b: [4,5,6], c: [7,8,9] }
		// fn(object, "a.b")
		// > [1,2,3,4,5,6]

		var keys = [];
		if (selector) {

			// Set bindings for the specified selector

			// (bindings that are repeat items)
			var split = selector.split("."),
					lastKey = split[split.length - 1],
					isArrayItem = !isNaN(lastKey);

			if (isArrayItem) {
					split.pop();
					var key = split.join(".");
					keys = object[key] ? _w.union(keys, object[key]) : keys;
			}

			// (bindings with keys starting with, to include nested bindings)
			for (var key in object) {
				if (startsWith(key, selector)) { keys = _w.union(keys, object[key]); }
			}

		} else {

			// Set bindings for all selectors
			for (var key in object) {
				keys = _w.union(keys, object[key]);
			}

		}
		return keys;

	}

	var isPrintableKey = function(e) {

		var keycode = e.keyCode;
		if (!keycode) { return true; }

		var valid =
			(keycode === 8)					 || // delete
			(keycode > 47 && keycode < 58)   || // number keys
			keycode === 32 || keycode === 13   || // spacebar & return key(s) (if you want to allow carriage returns)
			(keycode > 64 && keycode < 91)   || // letter keys
			(keycode > 95 && keycode < 112)  || // numpad keys
			(keycode > 185 && keycode < 193) || // ;=,-./` (in order)
			(keycode > 218 && keycode < 223);   // [\]' (in order)

		return valid;

	}

	var escapeHTML = function(str) {
		return str && _w.isString(str) ? str.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">") : str;
	}

	///////////////////////////////////////////////////
	// _w (strip of the required underscore methods) //
	///////////////////////////////////////////////////

	var _w = {};

	var ArrayProto = Array.prototype,
			ObjProto = Object.prototype,
			FuncProto = Function.prototype;

	var nativeIsArray = Array.isArray,
			nativeKeys = Object.keys,
			nativeBind = FuncProto.bind;

	var
		push             = ArrayProto.push,
		slice            = ArrayProto.slice,
		concat           = ArrayProto.concat,
		toString         = ObjProto.toString,
		hasOwnProperty   = ObjProto.hasOwnProperty;

	var flatten = function(input, shallow, strict, output) {
		if (shallow && _w.every(input, _w.isArray)) {
			return concat.apply(output, input);
		}
		for (var i = 0, length = input.length; i < length; i++) {
			var value = input[i];
			if (!_w.isArray(value) && !_w.isArguments(value)) {
				if (!strict) output.push(value);
			} else if (shallow) {
				push.apply(output, value);
			} else {
				flatten(value, shallow, strict, output);
			}
		}
		return output;
	};

	var createCallback = function(func, context, argCount) {
		if (context === void 0) return func;
		switch (argCount == null ? 3 : argCount) {
			case 1: return function(value) {
				return func.call(context, value);
			};
			case 2: return function(value, other) {
				return func.call(context, value, other);
			};
			case 3: return function(value, index, collection) {
				return func.call(context, value, index, collection);
			};
			case 4: return function(accumulator, value, index, collection) {
				return func.call(context, accumulator, value, index, collection);
			};
		}
		return function() {
			return func.apply(context, arguments);
		};
	};

	_w.compact = function(array) {
		return _w.filter(array, _w.identity);
	};

	_w.filter = function(obj, predicate, context) {
		var results = [];
		if (obj == null) return results;
		predicate = _w.iteratee(predicate, context);
		_w.each(obj, function(value, index, list) {
			if (predicate(value, index, list)) results.push(value);
		});
		return results;
	};

	_w.identity = function(value) {
		return value;
	};

	_w.every = function(obj, predicate, context) {
		if (obj == null) return true;
		predicate = _w.iteratee(predicate, context);
		var keys = obj.length !== +obj.length && _w.keys(obj),
				length = (keys || obj).length,
				index, currentKey;
		for (index = 0; index < length; index++) {
			currentKey = keys ? keys[index] : index;
			if (!predicate(obj[currentKey], currentKey, obj)) return false;
		}
		return true;
	};

	_w.union = function() {
		return _w.uniq(flatten(arguments, true, true, []));
	};

	_w.uniq = function(array, isSorted, iteratee, context) {
		if (array == null) return [];
		if (!_w.isBoolean(isSorted)) {
			context = iteratee;
			iteratee = isSorted;
			isSorted = false;
		}
		if (iteratee != null) iteratee = _w.iteratee(iteratee, context);
		var result = [];
		var seen = [];
		for (var i = 0, length = array.length; i < length; i++) {
			var value = array[i];
			if (isSorted) {
				if (!i || seen !== value) result.push(value);
				seen = value;
			} else if (iteratee) {
				var computed = iteratee(value, i, array);
				if (_w.indexOf(seen, computed) < 0) {
					seen.push(computed);
					result.push(value);
				}
			} else if (_w.indexOf(result, value) < 0) {
				result.push(value);
			}
		}
		return result;
	};

	_w.pick = function(obj, iteratee, context) {
		var result = {}, key;
		if (obj == null) return result;
		if (_w.isFunction(iteratee)) {
			iteratee = createCallback(iteratee, context);
			for (key in obj) {
				var value = obj[key];
				if (iteratee(value, key, obj)) result[key] = value;
			}
		} else {
			var keys = concat.apply([], slice.call(arguments, 1));
			obj = new Object(obj);
			for (var i = 0, length = keys.length; i < length; i++) {
				key = keys[i];
				if (key in obj) result[key] = obj[key];
			}
		}
		return result;
	};

	_w.has = function(obj, key) {
		return obj != null && hasOwnProperty.call(obj, key);
	};

	_w.keys = function(obj) {
		if (!_w.isObject(obj)) return [];
		if (nativeKeys) return nativeKeys(obj);
		var keys = [];
		for (var key in obj) if (_w.has(obj, key)) keys.push(key);
		return keys;
	};

	_w.contains = function(obj, target) {
		if (obj == null) return false;
		if (obj.length !== +obj.length) obj = _w.values(obj);
		return _w.indexOf(obj, target) >= 0;
	};

	_w.sortedIndex = function(array, obj, iteratee, context) {
		iteratee = _w.iteratee(iteratee, context, 1);
		var value = iteratee(obj);
		var low = 0, high = array.length;
		while (low < high) {
			var mid = low + high >>> 1;
			if (iteratee(array[mid]) < value) low = mid + 1; else high = mid;
		}
		return low;
	};

	_w.property = function(key) {
		return function(obj) {
			return obj[key];
		};
	};

	_w.iteratee = function(value, context, argCount) {
		if (value == null) return _w.identity;
		if (_w.isFunction(value)) return createCallback(value, context, argCount);
		if (_w.isObject(value)) return _w.matches(value);
		return _w.property(value);
	};

	_w.pairs = function(obj) {
		var keys = _w.keys(obj);
		var length = keys.length;
		var pairs = Array(length);
		for (var i = 0; i < length; i++) {
			pairs[i] = [keys[i], obj[keys[i]]];
		}
		return pairs;
	};

	_w.matches = function(attrs) {
		var pairs = _w.pairs(attrs), length = pairs.length;
		return function(obj) {
			if (obj == null) return !length;
			obj = new Object(obj);
			for (var i = 0; i < length; i++) {
				var pair = pairs[i], key = pair[0];
				if (pair[1] !== obj[key] || !(key in obj)) return false;
			}
			return true;
		};
	};

	_w.indexOf = function(array, item, isSorted) {
		if (array == null) return -1;
		var i = 0, length = array.length;
		if (isSorted) {
			if (typeof isSorted == 'number') {
				i = isSorted < 0 ? Math.max(0, length + isSorted) : isSorted;
			} else {
				i = _w.sortedIndex(array, item);
				return array[i] === item ? i : -1;
			}
		}
		for (; i < length; i++) if (array[i] === item) return i;
		return -1;
	};

	_w.values = function(obj) {
		var keys = _w.keys(obj);
		var length = keys.length;
		var values = Array(length);
		for (var i = 0; i < length; i++) {
			values[i] = obj[keys[i]];
		}
		return values;
	};

	_w.extend = function(obj) {
		if (!_w.isObject(obj)) return obj;
		var source, prop;
		for (var i = 1, length = arguments.length; i < length; i++) {
			source = arguments[i];
			for (prop in source) {
				if (hasOwnProperty.call(source, prop)) {
					obj[prop] = source[prop];
				}
			}
		}
		return obj;
	};

	_w.isArray = function(obj) {
		return toString.call(obj) === '[object Array]';
	};

	_w.isBoolean = function(obj) {
		return obj === true || obj === false || toString.call(obj) === '[object Boolean]';
	};

	_w.isUndefined = function(obj) {
		return obj === void 0;
	};

	_w.isObject = function(obj) {
		var type = typeof obj;
		return type === 'function' || type === 'object' && !!obj;
	};

	_w.each = function(obj, iteratee, context) {
		if (obj == null) return obj;
		iteratee = createCallback(iteratee, context);
		var i, length = obj.length;
		if (length === +length) {
			for (i = 0; i < length; i++) {
				iteratee(obj[i], i, obj);
			}
		} else {
			var keys = _w.keys(obj);
			for (i = 0, length = keys.length; i < length; i++) {
				iteratee(obj[keys[i]], keys[i], obj);
			}
		}
		return obj;
	};

	_w.each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp'], function(name) {
		_w['is' + name] = function(obj) {
			return toString.call(obj) === '[object ' + name + ']';
		};
	});

	///////////////////////////////////////////////////////////
	// _json (strip of the required underscore.json methods) //
	///////////////////////////////////////////////////////////

	var deepJSON = function (obj, key, value, remove) {

		var keys = key.replace(/\[(["']?)([^\1]+?)\1?\]/g, '.$2').replace(/^\./, '').split('.'),
				root,
				i = 0,
				n = keys.length;

		// Set deep value
		if (arguments.length > 2) {

			root = obj;
			n--;

			while (i < n) {
				key = keys[i++];
				obj = obj[key] = _w.isObject(obj[key]) ? obj[key] : {};
			}

			if (remove) {
				if (_w.isArray(obj)) {
					obj.splice(keys[i], 1);
				} else {
					delete obj[keys[i]];
				}
			} else {
				obj[keys[i]] = value;
			}

			value = root;

		// Get deep value
		} else {
			while ((obj = obj[keys[i++]]) != null && i < n) {};
			value = i < n ? void 0 : obj;
		}

		return value;

	}

	var _json = {}

	_json.VERSION = '0.1.0';
	_json.debug = true;

	_json.exit = function(source, reason, data, value) {

		if (!_json.debug) return;

		var messages = {};
		messages.noJSON = "Not a JSON";
		messages.noString = "Not a String";
		messages.noArray = "Not an Array";
		messages.missing = "Missing argument";

		var error = { source: source, data: data, value: value };
		error.message = messages[reason] ? messages[reason] : "No particular reason";
		console.log("Error", error);
		return;

	}

	_json.is = function(json) {

		return (toString.call(json) == "[object Object]");

	}

	_json.isStringified = function(string) {

		var test = false;
		try {
			test = /^[\],:{}\s]*$/.test(string.replace(/\\["\\\/bfnrtu]/g, '@').
			replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
			replace(/(?:^|:|,)(?:\s*\[)+/g, ''));
		} catch (e) {}
		return test;

	}

	_json.get = function(json, selector) {

		if (json == undefined) return _json.exit("get", "missing", "json", json);
		if (selector == undefined) return _json.exit("get", "missing", "selector", selector);
		if (!_w.isString(selector)) return _json.exit("get", "noString", "selector", selector);
		return deepJSON(json, selector);

	};

	_json.set = function(json, selector, value) {

		if (json == undefined) return _json.exit("set", "missing", "json", json);
		if (selector == undefined) return _json.exit("set", "missing", "selector", selector);
		if (!_w.isString(selector)) return _json.exit("set", "noString", "selector", selector);
		return value ? deepJSON(json, selector, value) : _json.remove(json, selector);
		// return deepJSON(json, selector, value); // Now removes the property if the value is empty. Maybe should keep it instead?

	};

	_json.remove = function(json, selector) {

		if (json == undefined) return _json.exit("remove", "missing", "json", json);
		if (selector == undefined) return _json.exit("remove", "missing", "selector", selector);
		if (!_w.isString(selector)) return _json.exit("remove", "noString", "selector", selector);
		return deepJSON(json, selector, null, true);

	}

	_json.push = function(json, selector, value, force) {

		if (json == undefined) return _json.exit("push", "missing", "json", json);
		if (selector == undefined) return _json.exit("push", "missing", "selector", selector);
		var array = _json.get(json, selector);
		if (!_w.isArray(array)) {
			if (force) {
				array = [];
			} else {
				return _json.exit("push", "noArray", "array", array);
			}
		}
		array.push(value);
		return _json.set(json, selector, array);

	}

	_json.unshift = function(json, selector, value) {

		if (json == undefined) return _json.exit("unshift", "missing", "json", json);
		if (selector == undefined) return _json.exit("unshift", "missing", "selector", selector);
		if (value == undefined) return _json.exit("unshift", "missing", "value", value);
		var array = _json.get(json, selector);
		if (!_w.isArray(array)) return _json.exit("unshift", "noArray", "array", array);
		array.unshift(value);
		return _json.set(json, selector, array);

	}

	_json.flatten = function(json) {

		if (json.constructor.name != "Object") return _json.exit("flatten", "noJSON", "json", json);

		var result = {};
		function recurse (cur, prop) {
			if (Object(cur) !== cur) {
				result[prop] = cur;
			} else if (Array.isArray(cur)) {
				for (var i = 0, l = cur.length; i < l; i++) {
					recurse(cur[i], prop ? prop + "." + i : "" + i);
					if (l == 0) result[prop] = [];
				}
			} else {
				var isEmpty = true;
				for (var p in cur) {
					isEmpty = false;
					recurse(cur[p], prop ? prop + "." + p : p);
				}
				if (isEmpty) result[prop] = {};
			}
		}
		recurse(json, "");
		return result;

	}

	_json.unflatten = function(data) {

		if (Object(data) !== data || Array.isArray(data))
			return data;
		var result = {}, cur, prop, idx, last, temp;
		for (var p in data) {
			cur = result, prop = "", last = 0;
			do {
				idx = p.indexOf(".", last);
				temp = p.substring(last, idx !== -1 ? idx : undefined);
				cur = cur[prop] || (cur[prop] = (!isNaN(parseInt(temp)) ? [] : {}));
				prop = temp;
				last = idx + 1;
			} while(idx >= 0);
			cur[prop] = data[p];
		}
		return result[""];

	}

	_json.prettyprint = function(json) {

		return JSON.stringify(json, undefined, 2);

	}

	//////////////////////////////////////////
	// wQuery (mini replacement for jQuery) //
	//////////////////////////////////////////

	var wQuery = function () {};
	wQuery.constructor = wQuery;

	wQuery.prototype.dom = function(selector, createOptions) {

		var self = this,
				elements = [];

		if (createOptions) {
			var element = document.createElement(selector);
			for (var k in createOptions) {
				element[k] = createOptions[k];
			}
		} else {
			if (_w.isString(selector)) {
				elements = [].slice.call(document.querySelectorAll(selector));
			} else {
				if (_w.isObject(selector) && selector.attributes) { elements = [selector]; }
			}
			self._elements = elements;
			self.length = elements.length;
			return self;
		}

	}

	wQuery.prototype.on = function(events, fn) {

		var self = this,
				elements = self._elements;
		events = events.split(" ");
		for (var i = 0, lenEl = elements.length; i < lenEl; i++) {
			var element = elements[i];
			for (var j = 0, lenEv = events.length; j < lenEv; j++) {
				if (element.addEventListener) { element.addEventListener(events[j], fn, false); }
			}
		}

	}

	wQuery.prototype.find = function(selector) {

			var self = this,
					element = self.get(0),
					elements = [];

			if (_w.isString(selector)) {
				elements = [].slice.call(element.querySelectorAll(selector));
			}
			self._elements = elements;
			return self;

	}

	wQuery.prototype.get = function(index, chain) {

			var self = this,
					elements = self._elements || [],
					element = elements[index] || {};

			if (chain) {
				self._element = element;
				return self;
			} else {
				return _w.isNumber(index) ? element : elements;
			}

	}

	wQuery.prototype.reverse = function() {
		this._elements = this._elements.reverse();
		return this;
	}

	wQuery.prototype.val = function(value) {
		return this.prop("value", value);
	}

	wQuery.prototype.type = function(value) {
		return this.prop("type", value);
	}

	wQuery.prototype.html = function(value) {
		return this.prop("innerHTML", value);
	}

	wQuery.prototype.text = function(value) {
		return this.prop("innerHTML", escapeHTML(value));
	}

	wQuery.prototype.prop = function(prop, value) {

		var self = this,
				elements = self._elements;

		for (var i in elements) {
			if (_w.isUndefined(value)) {
				return elements[i][prop];
			} else {
				elements[i][prop] = value;
			}
		}

	}

	wQuery.prototype.attr = function(attr, value) {

		var self = this,
				elements = self._elements;
		for (var i in elements) {
			if (value === undefined) {
				return elements[i].getAttribute(attr);
			} else {
				elements[i].setAttribute(attr, value);
			}
		}
		return self;

	}

	wQuery.prototype.removeAttr = function(attr) {
		var self = this;
		for (var i in self._elements) self._elements[i].removeAttribute(attr);
		return self;
	}

	wQuery.prototype.addClass = function(c) {
		var self = this;
		for (var i in self._elements) self._elements[i].classList.add(c);
		return self;
	}

	wQuery.prototype.removeClass = function(c) {
		var self = this;
		for (var i in self._elements) self._elements[i].classList.remove(c);
		return self;
	}

	wQuery.prototype.parents = function(selector) {
		var self = this,
				element = self.get(0),
				parent = element.parentNode,
				parents = [];

		while (parent !== null) {
			var o = parent,
					matches = matchesSelector(o, selector),
					isNotDomRoot = (o.doctype === undefined) ? true : false;
			if (!selector) { matches = true; }
			if (matches && isNotDomRoot) { parents.push(o); }
			parent = o.parentNode;
		}
		self._elements = parents;
		return self;
	}

	wQuery.prototype.parent = function(selector) {
		var self = this,
				element = self.get(0),
				o = element.parentNode,
				matches = matchesSelector(o, selector);
		if (!selector) { matches = true; }
		return matches ? o : {};
	}

	wQuery.prototype.clone = function(chain) {
		var self = this,
				element = self.get(0),
				clone = element.cloneNode(true);
		self._elements = [clone];
		return chain ? self : clone;
	}

	wQuery.prototype.empty = function(chain) {
		var self = this,
				element = self.get(0);
		if (!element || !element.hasChildNodes) { return chain ? self : element; }

		while (element.hasChildNodes()) {
			element.removeChild(element.lastChild);
		}
		return chain ? self : element;
	}

	wQuery.prototype.replaceWith = function(newDOM) {
		var self = this,
				oldDOM = self.get(0),
				parent = oldDOM.parentNode;
		parent.replaceChild(newDOM, oldDOM);
	}

	wQuery.prototype.ready = function(callback) {

		if (document && _w.isFunction(document.addEventListener)) {
			document.addEventListener("DOMContentLoaded", callback, false);
		} else if (window && _w.isFunction(window.addEventListener)) {
			window.addEventListener("load", callback, false);
		} else {
			document.onreadystatechange = function() {
				if (document.readyState === "complete") { callback(); }
			}
		}

	}

	//////////////////////
	// WATCH DOM EVENTS //
	//////////////////////

	way = new WAY();

	var timeoutInput = null;
	var eventInputChange = function(e) {
		if (timeoutInput) { clearTimeout(timeoutInput); }
		timeoutInput = setTimeout(function() {
			var element = w.dom(e.target).get(0);
			way.dom(element).toStorage();
		}, way.options.timeout);
	}

	var eventClear = function(e) {
		e.preventDefault();
		var options = way.dom(this).getOptions();
		way.remove(options.data, options);
	}

	var eventPush = function(e) {
		e.preventDefault();
		var options = way.dom(this).getOptions();
		if (!options || !options["action-push"]) { return false; }
		var split = options["action-push"].split(":"),
				selector = split[0] || null,
				value = split[1] || null;
		way.push(selector, value, options);
	}

	var eventRemove = function(e) {
		e.preventDefault();
		var options = way.dom(this).getOptions();
		if (!options || !options["action-remove"]) { return false; }
		way.remove(options["action-remove"], options);
	}

	var timeoutDOM = null;
	var eventDOMChange = function() {

		// We need to register dynamically added bindings so we do it by watching DOM changes
		// We use a timeout since "DOMSubtreeModified" gets triggered on every change in the DOM (even input value changes)
		// so we can limit the number of scans when a user is typing something
		if (timeoutDOM) { clearTimeout(timeoutDOM); }
		timeoutDOM = setTimeout(function() {
			way.registerDependencies();
			setEventListeners();
		}, way.options.timeoutDOM);

	}

	//////////////
	// INITIATE //
	//////////////

	w = new wQuery();
	way.w = w;

	var setEventListeners = function() {

			w.dom("body").on("DOMSubtreeModified", eventDOMChange);
			w.dom("[" + tagPrefix + "-data]").on("input change", eventInputChange);
			w.dom("[" + tagPrefix + "-clear]").on("click", eventClear);
			w.dom("[" + tagPrefix + "-action-remove]").on("click", eventRemove);
			w.dom("[" + tagPrefix + "-action-push]").on("click", eventPush);

	}

	var eventInit = function() {

		setEventListeners();
		way.restore();
		way.setDefaults();
		way.registerDependencies();
		way.updateDependencies();

	}

	w.ready(eventInit);

	return way;

}));


text:
#ifndef WebConnectionMessageKinds_h
#define WebConnectionMessageKinds_h

#include "MessageID.h"

namespace WebConnectionLegacyMessage {

enum Kind {
    PostMessage
};

}

namespace CoreIPC {

template<> struct MessageKindTraits<WebConnectionLegacyMessage::Kind> {
    static const MessageClass messageClass = MessageClassWebConnectionLegacy;
};

}

#endif // WebConnectionMessageKinds_h

redpajama_set_name: RedPajamaGithub


text:
import os
import sys
import re
import base64
import webapp2
import jinja2
import json
import itertools

from jinja2 import Environment, meta
from random import randint
from sets import Set
from datetime import datetime

from google.appengine.api import users
from google.appengine.api import taskqueue
from google.appengine.ext import blobstore
from google.appengine.ext import ndb
from google.appengine.ext.ndb import model
from google.appengine.ext.webapp import blobstore_handlers
from google.appengine.ext import vendor
vendor.add('thirdparty')

from bigrig.models import Project
from bigrig.models import Action
from bigrig.models import Subscription
from bigrig.models import SubscriptionMessage
from bigrig.processor import TraceProcessor
from bigrig.usermanager import UserManager
from bigrig.pushmessage import PushMessage

JINJA_ENVIRONMENT = jinja2.Environment(
    loader=jinja2.FileSystemLoader(
        os.path.join(
          os.path.dirname(__file__), '..'
        )
      ),
    extensions=['jinja2.ext.autoescape'],
    autoescape=True)

class PushHandler(webapp2.RequestHandler):
  def get(self):

    # Enable CORS
    self.response.headers.add_header("Access-Control-Allow-Origin", "*")

    project_key_string = self.request.get('project-key')
    action_key_string = self.request.get('action-key')

    if project_key_string == '' or project_key_string is None:
      self.response.write('No project key')
      return
    elif action_key_string == '' or action_key_string is None:
      self.response.write('No action key')
      return

    action_key = ndb.Key(Project, int(project_key_string),
        Action, int(action_key_string))

    subscriptions = Subscription.query(
        ancestor=action_key)

    for s in subscriptions:

      endpoint_parts = s.endpoint.split('/')
      subscription_id = endpoint_parts[len(endpoint_parts) - 1]

      # Pop a message in the store
      subscription_message = SubscriptionMessage(
        subscription_id=subscription_id,
        datetime=datetime.today(),
        title='Wowser!',
        message='Your new Speed Index is 3,301 (+208)',
        url='/project/5629499534213120/6473924464345088/')

      subscription_message.put()

      PushMessage.ping(s.endpoint)

app = webapp2.WSGIApplication([
    ('/push-test', PushHandler)
], debug=True)


text:
package reflection;

public class MethodTarget002 {

	public int methodOne() {
		return 37;
	}

	public int lateMethod() {
		return 42;
	}

	@AnnoT2
	@AnnoT
	public void methodAnnotated() {

	}

	@AnnoT2
	public void methodAnnotated2() {
	}

	// changed, deleted, reordered
	public void methodAnnotated3(@AnnoT2 String s, int i, @AnnoT2 @AnnoT float f) {
	}

}


text:
package com.github.hburgmeier.jerseyoauth2.testsuite.base;

import static org.junit.Assert.assertNotNull;

import org.junit.BeforeClass;
import org.scribe.model.Token;

import com.github.hburgmeier.jerseyoauth2.testsuite.base.client.ClientManagerClient;
import com.github.hburgmeier.jerseyoauth2.testsuite.base.client.ResourceClient;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;

public class PerformanceTest {

	protected static Token token;
	protected static ResourceClient client;
	protected static ClientEntity clientEntity;

	@BeforeClass
	public static void classSetup()
	{
		ClientConfig cc = new DefaultClientConfig();
		Client restClient = Client.create(cc);
		ClientManagerClient authClient = new ClientManagerClient(restClient);
		clientEntity = authClient.createClient("confidential");

		String code = authClient.authorizeClient(clientEntity, "test1 test2").getCode();
		assertNotNull(code);
		restClient.setFollowRedirects(false);

		client = new ResourceClient(clientEntity);
		token = client.getAccessToken(code);
	}

}


text:
using System;

namespace Lucene.Net.Store
{

    /// <summary>
    /// Extension of IndexInput, computing checksum as it goes.
    /// Callers can retrieve the checksum via <seealso cref="#getChecksum()"/>.
    /// </summary>
    public abstract class ChecksumIndexInput : IndexInput
    {
        /// <summary>
        /// resourceDescription should be a non-null, opaque string
        ///  describing this resource; it's returned from
        ///  <seealso cref="#toString"/>.
        /// </summary>
        protected internal ChecksumIndexInput(string resourceDescription)
            : base(resourceDescription)
        {
        }

        /// <summary>
        /// Returns the current checksum value </summary>
        public abstract long Checksum { get; }

        /// <summary>
        /// {@inheritDoc}
        ///
        /// <seealso cref="ChecksumIndexInput"/> can only seek forward and seeks are expensive
        /// since they imply to read bytes in-between the current position and the
        /// target position in order to update the checksum.
        /// </summary>
        public override void Seek(long pos)
        {
            long skip = pos - FilePointer;
            if (skip < 0)
            {
                throw new InvalidOperationException(this.GetType() + " cannot seek backwards");
            }
            SkipBytes(skip);
        }
    }
}


text:
package org.hl7.fhir.dstu3.model;

// Generated on Tue, Dec 6, 2016 09:42-0500 for FHIR v1.8.0

import java.util.*;

import org.hl7.fhir.utilities.Utilities;
import ca.uhn.fhir.model.api.annotation.ResourceDef;
import ca.uhn.fhir.model.api.annotation.SearchParamDefinition;
import ca.uhn.fhir.model.api.annotation.Child;
import ca.uhn.fhir.model.api.annotation.ChildOrder;
import ca.uhn.fhir.model.api.annotation.Description;
import ca.uhn.fhir.model.api.annotation.Block;
import org.hl7.fhir.instance.model.api.*;
import org.hl7.fhir.exceptions.FHIRException;
/**
 * A container for slot(s) of time that may be available for booking appointments.
 */
@ResourceDef(name="Schedule", profile="http://hl7.org/fhir/Profile/Schedule")
public class Schedule extends DomainResource {

    /**
     * External Ids for this item.
     */
    @Child(name = "identifier", type = {Identifier.class}, order=0, min=0, max=Child.MAX_UNLIMITED, modifier=false, summary=true)
    @Description(shortDefinition="External Ids for this item", formalDefinition="External Ids for this item." )
    protected List<Identifier> identifier;

    /**
     * Whether this schedule record is in active use, or should not be used (such as was entered in error).
     */
    @Child(name = "active", type = {BooleanType.class}, order=1, min=0, max=1, modifier=true, summary=true)
    @Description(shortDefinition="Whether this schedule is in active use", formalDefinition="Whether this schedule record is in active use, or should not be used (such as was entered in error)." )
    protected BooleanType active;

    /**
     * A broad categorisation of the service that is to be performed during this appointment.
     */
    @Child(name = "serviceCategory", type = {CodeableConcept.class}, order=2, min=0, max=1, modifier=false, summary=true)
    @Description(shortDefinition="A broad categorisation of the service that is to be performed during this appointment", formalDefinition="A broad categorisation of the service that is to be performed during this appointment." )
    @ca.uhn.fhir.model.api.annotation.Binding(valueSet="http://hl7.org/fhir/ValueSet/service-category")
    protected CodeableConcept serviceCategory;

    /**
     * The specific service that is to be performed during this appointment.
     */
    @Child(name = "serviceType", type = {CodeableConcept.class}, order=3, min=0, max=Child.MAX_UNLIMITED, modifier=false, summary=true)
    @Description(shortDefinition="The specific service that is to be performed during this appointment", formalDefinition="The specific service that is to be performed during this appointment." )
    @ca.uhn.fhir.model.api.annotation.Binding(valueSet="http://hl7.org/fhir/ValueSet/service-type")
    protected List<CodeableConcept> serviceType;

    /**
     * The specialty of a practitioner that would be required to perform the service requested in this appointment.
     */
    @Child(name = "specialty", type = {CodeableConcept.class}, order=4, min=0, max=Child.MAX_UNLIMITED, modifier=false, summary=true)
    @Description(shortDefinition="The specialty of a practitioner that would be required to perform the service requested in this appointment", formalDefinition="The specialty of a practitioner that would be required to perform the service requested in this appointment." )
    @ca.uhn.fhir.model.api.annotation.Binding(valueSet="http://hl7.org/fhir/ValueSet/c80-practice-codes")
    protected List<CodeableConcept> specialty;

    /**
     * The resource this Schedule resource is providing availability information for. These are expected to usually be one of HealthcareService, Location, Practitioner, Device, Patient or RelatedPerson.
     */
    @Child(name = "actor", type = {Patient.class, Practitioner.class, RelatedPerson.class, Device.class, HealthcareService.class, Location.class}, order=5, min=1, max=1, modifier=false, summary=true)
    @Description(shortDefinition="The resource this Schedule resource is providing availability information for. These are expected to usually be one of HealthcareService, Location, Practitioner, Device, Patient or RelatedPerson", formalDefinition="The resource this Schedule resource is providing availability information for. These are expected to usually be one of HealthcareService, Location, Practitioner, Device, Patient or RelatedPerson." )
    protected Reference actor;

    /**
     * The actual object that is the target of the reference (The resource this Schedule resource is providing availability information for. These are expected to usually be one of HealthcareService, Location, Practitioner, Device, Patient or RelatedPerson.)
     */
    protected Resource actorTarget;

    /**
     * The period of time that the slots that are attached to this Schedule resource cover (even if none exist). These  cover the amount of time that an organization's planning horizon; the interval for which they are currently accepting appointments. This does not define a "template" for planning outside these dates.
     */
    @Child(name = "planningHorizon", type = {Period.class}, order=6, min=0, max=1, modifier=false, summary=true)
    @Description(shortDefinition="The period of time that the slots that are attached to this Schedule resource cover (even if none exist). These  cover the amount of time that an organization's planning horizon; the interval for which they are currently accepting appointments. This does not define a \"template\" for planning outside these dates", formalDefinition="The period of time that the slots that are attached to this Schedule resource cover (even if none exist). These  cover the amount of time that an organization's planning horizon; the interval for which they are currently accepting appointments. This does not define a \"template\" for planning outside these dates." )
    protected Period planningHorizon;

    /**
     * Comments on the availability to describe any extended information. Such as custom constraints on the slot(s) that may be associated.
     */
    @Child(name = "comment", type = {StringType.class}, order=7, min=0, max=1, modifier=false, summary=false)
    @Description(shortDefinition="Comments on the availability to describe any extended information. Such as custom constraints on the slot(s) that may be associated", formalDefinition="Comments on the availability to describe any extended information. Such as custom constraints on the slot(s) that may be associated." )
    protected StringType comment;

    private static final long serialVersionUID = 2029938060L;

  /**
   * Constructor
   */
    public Schedule() {
      super();
    }

  /**
   * Constructor
   */
    public Schedule(Reference actor) {
      super();
      this.actor = actor;
    }

    /**
     * @return {@link #identifier} (External Ids for this item.)
     */
    public List<Identifier> getIdentifier() {
      if (this.identifier == null)
        this.identifier = new ArrayList<Identifier>();
      return this.identifier;
    }

    /**
     * @return Returns a reference to this for easy method chaining
     */
    public Schedule setIdentifier(List<Identifier> theIdentifier) {
      this.identifier = theIdentifier;
      return this;
    }

    public boolean hasIdentifier() {
      if (this.identifier == null)
        return false;
      for (Identifier item : this.identifier)
        if (!item.isEmpty())
          return true;
      return false;
    }

    public Identifier addIdentifier() { //3
      Identifier t = new Identifier();
      if (this.identifier == null)
        this.identifier = new ArrayList<Identifier>();
      this.identifier.add(t);
      return t;
    }

    public Schedule addIdentifier(Identifier t) { //3
      if (t == null)
        return this;
      if (this.identifier == null)
        this.identifier = new ArrayList<Identifier>();
      this.identifier.add(t);
      return this;
    }

    /**
     * @return The first repetition of repeating field {@link #identifier}, creating it if it does not already exist
     */
    public Identifier getIdentifierFirstRep() {
      if (getIdentifier().isEmpty()) {
        addIdentifier();
      }
      return getIdentifier().get(0);
    }

    /**
     * @return {@link #active} (Whether this schedule record is in active use, or should not be used (such as was entered in error).). This is the underlying object with id, value and extensions. The accessor "getActive" gives direct access to the value
     */
    public BooleanType getActiveElement() {
      if (this.active == null)
        if (Configuration.errorOnAutoCreate())
          throw new Error("Attempt to auto-create Schedule.active");
        else if (Configuration.doAutoCreate())
          this.active = new BooleanType(); // bb
      return this.active;
    }

    public boolean hasActiveElement() {
      return this.active != null && !this.active.isEmpty();
    }

    public boolean hasActive() {
      return this.active != null && !this.active.isEmpty();
    }

    /**
     * @param value {@link #active} (Whether this schedule record is in active use, or should not be used (such as was entered in error).). This is the underlying object with id, value and extensions. The accessor "getActive" gives direct access to the value
     */
    public Schedule setActiveElement(BooleanType value) {
      this.active = value;
      return this;
    }

    /**
     * @return Whether this schedule record is in active use, or should not be used (such as was entered in error).
     */
    public boolean getActive() {
      return this.active == null || this.active.isEmpty() ? false : this.active.getValue();
    }

    /**
     * @param value Whether this schedule record is in active use, or should not be used (such as was entered in error).
     */
    public Schedule setActive(boolean value) {
        if (this.active == null)
          this.active = new BooleanType();
        this.active.setValue(value);
      return this;
    }

    /**
     * @return {@link #serviceCategory} (A broad categorisation of the service that is to be performed during this appointment.)
     */
    public CodeableConcept getServiceCategory() {
      if (this.serviceCategory == null)
        if (Configuration.errorOnAutoCreate())
          throw new Error("Attempt to auto-create Schedule.serviceCategory");
        else if (Configuration.doAutoCreate())
          this.serviceCategory = new CodeableConcept(); // cc
      return this.serviceCategory;
    }

    public boolean hasServiceCategory() {
      return this.serviceCategory != null && !this.serviceCategory.isEmpty();
    }

    /**
     * @param value {@link #serviceCategory} (A broad categorisation of the service that is to be performed during this appointment.)
     */
    public Schedule setServiceCategory(CodeableConcept value) {
      this.serviceCategory = value;
      return this;
    }

    /**
     * @return {@link #serviceType} (The specific service that is to be performed during this appointment.)
     */
    public List<CodeableConcept> getServiceType() {
      if (this.serviceType == null)
        this.serviceType = new ArrayList<CodeableConcept>();
      return this.serviceType;
    }

    /**
     * @return Returns a reference to this for easy method chaining
     */
    public Schedule setServiceType(List<CodeableConcept> theServiceType) {
      this.serviceType = theServiceType;
      return this;
    }

    public boolean hasServiceType() {
      if (this.serviceType == null)
        return false;
      for (CodeableConcept item : this.serviceType)
        if (!item.isEmpty())
          return true;
      return false;
    }

    public CodeableConcept addServiceType() { //3
      CodeableConcept t = new CodeableConcept();
      if (this.serviceType == null)
        this.serviceType = new ArrayList<CodeableConcept>();
      this.serviceType.add(t);
      return t;
    }

    public Schedule addServiceType(CodeableConcept t) { //3
      if (t == null)
        return this;
      if (this.serviceType == null)
        this.serviceType = new ArrayList<CodeableConcept>();
      this.serviceType.add(t);
      return this;
    }

    /**
     * @return The first repetition of repeating field {@link #serviceType}, creating it if it does not already exist
     */
    public CodeableConcept getServiceTypeFirstRep() {
      if (getServiceType().isEmpty()) {
        addServiceType();
      }
      return getServiceType().get(0);
    }

    /**
     * @return {@link #specialty} (The specialty of a practitioner that would be required to perform the service requested in this appointment.)
     */
    public List<CodeableConcept> getSpecialty() {
      if (this.specialty == null)
        this.specialty = new ArrayList<CodeableConcept>();
      return this.specialty;
    }

    /**
     * @return Returns a reference to this for easy method chaining
     */
    public Schedule setSpecialty(List<CodeableConcept> theSpecialty) {
      this.specialty = theSpecialty;
      return this;
    }

    public boolean hasSpecialty() {
      if (this.specialty == null)
        return false;
      for (CodeableConcept item : this.specialty)
        if (!item.isEmpty())
          return true;
      return false;
    }

    public CodeableConcept addSpecialty() { //3
      CodeableConcept t = new CodeableConcept();
      if (this.specialty == null)
        this.specialty = new ArrayList<CodeableConcept>();
      this.specialty.add(t);
      return t;
    }

    public Schedule addSpecialty(CodeableConcept t) { //3
      if (t == null)
        return this;
      if (this.specialty == null)
        this.specialty = new ArrayList<CodeableConcept>();
      this.specialty.add(t);
      return this;
    }

    /**
     * @return The first repetition of repeating field {@link #specialty}, creating it if it does not already exist
     */
    public CodeableConcept getSpecialtyFirstRep() {
      if (getSpecialty().isEmpty()) {
        addSpecialty();
      }
      return getSpecialty().get(0);
    }

    /**
     * @return {@link #actor} (The resource this Schedule resource is providing availability information for. These are expected to usually be one of HealthcareService, Location, Practitioner, Device, Patient or RelatedPerson.)
     */
    public Reference getActor() {
      if (this.actor == null)
        if (Configuration.errorOnAutoCreate())
          throw new Error("Attempt to auto-create Schedule.actor");
        else if (Configuration.doAutoCreate())
          this.actor = new Reference(); // cc
      return this.actor;
    }

    public boolean hasActor() {
      return this.actor != null && !this.actor.isEmpty();
    }

    /**
     * @param value {@link #actor} (The resource this Schedule resource is providing availability information for. These are expected to usually be one of HealthcareService, Location, Practitioner, Device, Patient or RelatedPerson.)
     */
    public Schedule setActor(Reference value) {
      this.actor = value;
      return this;
    }

    /**
     * @return {@link #actor} The actual object that is the target of the reference. The reference library doesn't populate this, but you can use it to hold the resource if you resolve it. (The resource this Schedule resource is providing availability information for. These are expected to usually be one of HealthcareService, Location, Practitioner, Device, Patient or RelatedPerson.)
     */
    public Resource getActorTarget() {
      return this.actorTarget;
    }

    /**
     * @param value {@link #actor} The actual object that is the target of the reference. The reference library doesn't use these, but you can use it to hold the resource if you resolve it. (The resource this Schedule resource is providing availability information for. These are expected to usually be one of HealthcareService, Location, Practitioner, Device, Patient or RelatedPerson.)
     */
    public Schedule setActorTarget(Resource value) {
      this.actorTarget = value;
      return this;
    }

    /**
     * @return {@link #planningHorizon} (The period of time that the slots that are attached to this Schedule resource cover (even if none exist). These  cover the amount of time that an organization's planning horizon; the interval for which they are currently accepting appointments. This does not define a "template" for planning outside these dates.)
     */
    public Period getPlanningHorizon() {
      if (this.planningHorizon == null)
        if (Configuration.errorOnAutoCreate())
          throw new Error("Attempt to auto-create Schedule.planningHorizon");
        else if (Configuration.doAutoCreate())
          this.planningHorizon = new Period(); // cc
      return this.planningHorizon;
    }

    public boolean hasPlanningHorizon() {
      return this.planningHorizon != null && !this.planningHorizon.isEmpty();
    }

    /**
     * @param value {@link #planningHorizon} (The period of time that the slots that are attached to this Schedule resource cover (even if none exist). These  cover the amount of time that an organization's planning horizon; the interval for which they are currently accepting appointments. This does not define a "template" for planning outside these dates.)
     */
    public Schedule setPlanningHorizon(Period value) {
      this.planningHorizon = value;
      return this;
    }

    /**
     * @return {@link #comment} (Comments on the availability to describe any extended information. Such as custom constraints on the slot(s) that may be associated.). This is the underlying object with id, value and extensions. The accessor "getComment" gives direct access to the value
     */
    public StringType getCommentElement() {
      if (this.comment == null)
        if (Configuration.errorOnAutoCreate())
          throw new Error("Attempt to auto-create Schedule.comment");
        else if (Configuration.doAutoCreate())
          this.comment = new StringType(); // bb
      return this.comment;
    }

    public boolean hasCommentElement() {
      return this.comment != null && !this.comment.isEmpty();
    }

    public boolean hasComment() {
      return this.comment != null && !this.comment.isEmpty();
    }

    /**
     * @param value {@link #comment} (Comments on the availability to describe any extended information. Such as custom constraints on the slot(s) that may be associated.). This is the underlying object with id, value and extensions. The accessor "getComment" gives direct access to the value
     */
    public Schedule setCommentElement(StringType value) {
      this.comment = value;
      return this;
    }

    /**
     * @return Comments on the availability to describe any extended information. Such as custom constraints on the slot(s) that may be associated.
     */
    public String getComment() {
      return this.comment == null ? null : this.comment.getValue();
    }

    /**
     * @param value Comments on the availability to describe any extended information. Such as custom constraints on the slot(s) that may be associated.
     */
    public Schedule setComment(String value) {
      if (Utilities.noString(value))
        this.comment = null;
      else {
        if (this.comment == null)
          this.comment = new StringType();
        this.comment.setValue(value);
      }
      return this;
    }

      protected void listChildren(List<Property> childrenList) {
        super.listChildren(childrenList);
        childrenList.add(new Property("identifier", "Identifier", "External Ids for this item.", 0, java.lang.Integer.MAX_VALUE, identifier));
        childrenList.add(new Property("active", "boolean", "Whether this schedule record is in active use, or should not be used (such as was entered in error).", 0, java.lang.Integer.MAX_VALUE, active));
        childrenList.add(new Property("serviceCategory", "CodeableConcept", "A broad categorisation of the service that is to be performed during this appointment.", 0, java.lang.Integer.MAX_VALUE, serviceCategory));
        childrenList.add(new Property("serviceType", "CodeableConcept", "The specific service that is to be performed during this appointment.", 0, java.lang.Integer.MAX_VALUE, serviceType));
        childrenList.add(new Property("specialty", "CodeableConcept", "The specialty of a practitioner that would be required to perform the service requested in this appointment.", 0, java.lang.Integer.MAX_VALUE, specialty));
        childrenList.add(new Property("actor", "Reference(Patient|Practitioner|RelatedPerson|Device|HealthcareService|Location)", "The resource this Schedule resource is providing availability information for. These are expected to usually be one of HealthcareService, Location, Practitioner, Device, Patient or RelatedPerson.", 0, java.lang.Integer.MAX_VALUE, actor));
        childrenList.add(new Property("planningHorizon", "Period", "The period of time that the slots that are attached to this Schedule resource cover (even if none exist). These  cover the amount of time that an organization's planning horizon; the interval for which they are currently accepting appointments. This does not define a \"template\" for planning outside these dates.", 0, java.lang.Integer.MAX_VALUE, planningHorizon));
        childrenList.add(new Property("comment", "string", "Comments on the availability to describe any extended information. Such as custom constraints on the slot(s) that may be associated.", 0, java.lang.Integer.MAX_VALUE, comment));
      }

      @Override
      public Base[] getProperty(int hash, String name, boolean checkValid) throws FHIRException {
        switch (hash) {
        case -1618432855: /*identifier*/ return this.identifier == null ? new Base[0] : this.identifier.toArray(new Base[this.identifier.size()]); // Identifier
        case -1422950650: /*active*/ return this.active == null ? new Base[0] : new Base[] {this.active}; // BooleanType
        case 1281188563: /*serviceCategory*/ return this.serviceCategory == null ? new Base[0] : new Base[] {this.serviceCategory}; // CodeableConcept
        case -1928370289: /*serviceType*/ return this.serviceType == null ? new Base[0] : this.serviceType.toArray(new Base[this.serviceType.size()]); // CodeableConcept
        case -1694759682: /*specialty*/ return this.specialty == null ? new Base[0] : this.specialty.toArray(new Base[this.specialty.size()]); // CodeableConcept
        case 92645877: /*actor*/ return this.actor == null ? new Base[0] : new Base[] {this.actor}; // Reference
        case -1718507650: /*planningHorizon*/ return this.planningHorizon == null ? new Base[0] : new Base[] {this.planningHorizon}; // Period
        case 950398559: /*comment*/ return this.comment == null ? new Base[0] : new Base[] {this.comment}; // StringType
        default: return super.getProperty(hash, name, checkValid);
        }

      }

      @Override
      public void setProperty(int hash, String name, Base value) throws FHIRException {
        switch (hash) {
        case -1618432855: // identifier
          this.getIdentifier().add(castToIdentifier(value)); // Identifier
          break;
        case -1422950650: // active
          this.active = castToBoolean(value); // BooleanType
          break;
        case 1281188563: // serviceCategory
          this.serviceCategory = castToCodeableConcept(value); // CodeableConcept
          break;
        case -1928370289: // serviceType
          this.getServiceType().add(castToCodeableConcept(value)); // CodeableConcept
          break;
        case -1694759682: // specialty
          this.getSpecialty().add(castToCodeableConcept(value)); // CodeableConcept
          break;
        case 92645877: // actor
          this.actor = castToReference(value); // Reference
          break;
        case -1718507650: // planningHorizon
          this.planningHorizon = castToPeriod(value); // Period
          break;
        case 950398559: // comment
          this.comment = castToString(value); // StringType
          break;
        default: super.setProperty(hash, name, value);
        }

      }

      @Override
      public void setProperty(String name, Base value) throws FHIRException {
        if (name.equals("identifier"))
          this.getIdentifier().add(castToIdentifier(value));
        else if (name.equals("active"))
          this.active = castToBoolean(value); // BooleanType
        else if (name.equals("serviceCategory"))
          this.serviceCategory = castToCodeableConcept(value); // CodeableConcept
        else if (name.equals("serviceType"))
          this.getServiceType().add(castToCodeableConcept(value));
        else if (name.equals("specialty"))
          this.getSpecialty().add(castToCodeableConcept(value));
        else if (name.equals("actor"))
          this.actor = castToReference(value); // Reference
        else if (name.equals("planningHorizon"))
          this.planningHorizon = castToPeriod(value); // Period
        else if (name.equals("comment"))
          this.comment = castToString(value); // StringType
        else
          super.setProperty(name, value);
      }

      @Override
      public Base makeProperty(int hash, String name) throws FHIRException {
        switch (hash) {
        case -1618432855:  return addIdentifier(); // Identifier
        case -1422950650: throw new FHIRException("Cannot make property active as it is not a complex type"); // BooleanType
        case 1281188563:  return getServiceCategory(); // CodeableConcept
        case -1928370289:  return addServiceType(); // CodeableConcept
        case -1694759682:  return addSpecialty(); // CodeableConcept
        case 92645877:  return getActor(); // Reference
        case -1718507650:  return getPlanningHorizon(); // Period
        case 950398559: throw new FHIRException("Cannot make property comment as it is not a complex type"); // StringType
        default: return super.makeProperty(hash, name);
        }

      }

      @Override
      public Base addChild(String name) throws FHIRException {
        if (name.equals("identifier")) {
          return addIdentifier();
        }
        else if (name.equals("active")) {
          throw new FHIRException("Cannot call addChild on a primitive type Schedule.active");
        }
        else if (name.equals("serviceCategory")) {
          this.serviceCategory = new CodeableConcept();
          return this.serviceCategory;
        }
        else if (name.equals("serviceType")) {
          return addServiceType();
        }
        else if (name.equals("specialty")) {
          return addSpecialty();
        }
        else if (name.equals("actor")) {
          this.actor = new Reference();
          return this.actor;
        }
        else if (name.equals("planningHorizon")) {
          this.planningHorizon = new Period();
          return this.planningHorizon;
        }
        else if (name.equals("comment")) {
          throw new FHIRException("Cannot call addChild on a primitive type Schedule.comment");
        }
        else
          return super.addChild(name);
      }

  public String fhirType() {
    return "Schedule";

  }

      public Schedule copy() {
        Schedule dst = new Schedule();
        copyValues(dst);
        if (identifier != null) {
          dst.identifier = new ArrayList<Identifier>();
          for (Identifier i : identifier)
            dst.identifier.add(i.copy());
        };
        dst.active = active == null ? null : active.copy();
        dst.serviceCategory = serviceCategory == null ? null : serviceCategory.copy();
        if (serviceType != null) {
          dst.serviceType = new ArrayList<CodeableConcept>();
          for (CodeableConcept i : serviceType)
            dst.serviceType.add(i.copy());
        };
        if (specialty != null) {
          dst.specialty = new ArrayList<CodeableConcept>();
          for (CodeableConcept i : specialty)
            dst.specialty.add(i.copy());
        };
        dst.actor = actor == null ? null : actor.copy();
        dst.planningHorizon = planningHorizon == null ? null : planningHorizon.copy();
        dst.comment = comment == null ? null : comment.copy();
        return dst;
      }

      protected Schedule typedCopy() {
        return copy();
      }

      @Override
      public boolean equalsDeep(Base other) {
        if (!super.equalsDeep(other))
          return false;
        if (!(other instanceof Schedule))
          return false;
        Schedule o = (Schedule) other;
        return compareDeep(identifier, o.identifier, true) && compareDeep(active, o.active, true) && compareDeep(serviceCategory, o.serviceCategory, true)
           && compareDeep(serviceType, o.serviceType, true) && compareDeep(specialty, o.specialty, true) && compareDeep(actor, o.actor, true)
           && compareDeep(planningHorizon, o.planningHorizon, true) && compareDeep(comment, o.comment, true)
          ;
      }

      @Override
      public boolean equalsShallow(Base other) {
        if (!super.equalsShallow(other))
          return false;
        if (!(other instanceof Schedule))
          return false;
        Schedule o = (Schedule) other;
        return compareValues(active, o.active, true) && compareValues(comment, o.comment, true);
      }

      public boolean isEmpty() {
        return super.isEmpty() && ca.uhn.fhir.util.ElementUtil.isEmpty(identifier, active, serviceCategory
          , serviceType, specialty, actor, planningHorizon, comment);
      }

  @Override
  public ResourceType getResourceType() {
    return ResourceType.Schedule;
   }

 /**
   * Search parameter: actor
   *

   * Description: The individual(HealthcareService, Practitioner, Location, ...) to find a Schedule for

   * Type: reference

   * Path: Schedule.actor

   *

   */
  @SearchParamDefinition(name="actor", path="Schedule.actor", description="The individual(HealthcareService, Practitioner, Location, ...) to find a Schedule for", type="reference", providesMembershipIn={ @ca.uhn.fhir.model.api.annotation.Compartment(name="Device"), @ca.uhn.fhir.model.api.annotation.Compartment(name="Patient"), @ca.uhn.fhir.model.api.annotation.Compartment(name="Practitioner"), @ca.uhn.fhir.model.api.annotation.Compartment(name="RelatedPerson") }, target={Device.class, HealthcareService.class, Location.class, Patient.class, Practitioner.class, RelatedPerson.class } )
  public static final String SP_ACTOR = "actor";
 /**
   * Fluent Client search parameter constant for actor
   *

   * Description: The individual(HealthcareService, Practitioner, Location, ...) to find a Schedule for

   * Type: reference

   * Path: Schedule.actor

   *

   */
  public static final ca.uhn.fhir.rest.gclient.ReferenceClientParam ACTOR = new ca.uhn.fhir.rest.gclient.ReferenceClientParam(SP_ACTOR);

/**
   * Constant for fluent queries to be used to add include statements. Specifies
   * the path value of "Schedule:actor".
   */
  public static final ca.uhn.fhir.model.api.Include INCLUDE_ACTOR = new ca.uhn.fhir.model.api.Include("Schedule:actor").toLocked();

 /**
   * Search parameter: date
   *

   * Description: Search for Schedule resources that have a period that contains this date specified

   * Type: date

   * Path: Schedule.planningHorizon

   *

   */
  @SearchParamDefinition(name="date", path="Schedule.planningHorizon", description="Search for Schedule resources that have a period that contains this date specified", type="date" )
  public static final String SP_DATE = "date";
 /**
   * Fluent Client search parameter constant for date
   *

   * Description: Search for Schedule resources that have a period that contains this date specified

   * Type: date

   * Path: Schedule.planningHorizon

   *

   */
  public static final ca.uhn.fhir.rest.gclient.DateClientParam DATE = new ca.uhn.fhir.rest.gclient.DateClientParam(SP_DATE);

 /**
   * Search parameter: identifier
   *

   * Description: A Schedule Identifier

   * Type: token

   * Path: Schedule.identifier

   *

   */
  @SearchParamDefinition(name="identifier", path="Schedule.identifier", description="A Schedule Identifier", type="token" )
  public static final String SP_IDENTIFIER = "identifier";
 /**
   * Fluent Client search parameter constant for identifier
   *

   * Description: A Schedule Identifier

   * Type: token

   * Path: Schedule.identifier

   *

   */
  public static final ca.uhn.fhir.rest.gclient.TokenClientParam IDENTIFIER = new ca.uhn.fhir.rest.gclient.TokenClientParam(SP_IDENTIFIER);

 /**
   * Search parameter: active
   *

   * Description: Is the schedule in active use

   * Type: token

   * Path: Schedule.active

   *

   */
  @SearchParamDefinition(name="active", path="Schedule.active", description="Is the schedule in active use", type="token" )
  public static final String SP_ACTIVE = "active";
 /**
   * Fluent Client search parameter constant for active
   *

   * Description: Is the schedule in active use

   * Type: token

   * Path: Schedule.active

   *

   */
  public static final ca.uhn.fhir.rest.gclient.TokenClientParam ACTIVE = new ca.uhn.fhir.rest.gclient.TokenClientParam(SP_ACTIVE);

 /**
   * Search parameter: type
   *

   * Description: The type of appointments that can be booked into associated slot(s)

   * Type: token

   * Path: Schedule.serviceType

   *

   */
  @SearchParamDefinition(name="type", path="Schedule.serviceType", description="The type of appointments that can be booked into associated slot(s)", type="token" )
  public static final String SP_TYPE = "type";
 /**
   * Fluent Client search parameter constant for type
   *

   * Description: The type of appointments that can be booked into associated slot(s)

   * Type: token

   * Path: Schedule.serviceType

   *

   */
  public static final ca.uhn.fhir.rest.gclient.TokenClientParam TYPE = new ca.uhn.fhir.rest.gclient.TokenClientParam(SP_TYPE);

}


text:
package org.epics.graphene.rrdtool;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.epics.graphene.Point3DWithLabelDataset;
import org.epics.graphene.Point3DWithLabelDatasets;
import org.epics.util.time.Timestamp;
import org.epics.util.time.TimestampFormat;

/**
 *
 * @author carcassi
 */
public class RrdToolBubbleGraphMain {

    private static TimestampFormat format = new TimestampFormat("yyyyMMddHHmmss");

    public static void main(String[] args) throws Exception {
        List<String> signals = new ArrayList<>();
        Timestamp start = null;
        Timestamp end = null;
        String filename = null;
        for (int i = 0; i < args.length; i++) {
            String arg = args[i];
            if (arg.equals("-s")) {
                i++;
                start = format.parse(args[i]);
            } else if (arg.equals("-e")) {
                i++;
                end = format.parse(args[i]);
            } else if (arg.equals("-o")) {
                i++;
                filename = args[i];
            } else  {
                signals.add(arg);
            }
        }
        List<TimeSeries> data = RrdToolDB.fetchData(signals, start, end);
        Map<String, TimeSeries> series = new HashMap<>();
        for (int i = 0; i < signals.size(); i++) {
            series.put(signals.get(i), data.get(i));
        }
        TimeSeriesMulti correlated = TimeSeriesMulti.synchronizeSeries(series);
        final Point3DWithLabelDataset dataset = Point3DWithLabelDatasets.build(correlated.getValues().get(signals.get(0)),
                                                correlated.getValues().get(signals.get(1)),
                                                correlated.getValues().get(signals.get(2)),
                                                Collections.nCopies(correlated.getValues().get(signals.get(0)).size(), "label"));
        BubbleUtil.createBubblePlot(filename, dataset, "DATASETLABEL", "", "", "", "", Timestamp.now());
    }

}


text:
.. Copyright (c) 2016, Ruslan Baratov
.. All rights reserved.

Library with dependencies
-------------------------

.. admonition:: TODO

  ``find_dependency`` in ``Config.cmake.in``


text:
#include <string.h>

#include "extmod/vfs.h"
#include "py/mperrno.h"
#include "py/mphal.h"
#include "py/obj.h"
#include "py/runtime.h"
#include "shared-bindings/microcontroller/__init__.h"
#include "shared-bindings/os/__init__.h"
#include "shared-bindings/storage/__init__.h"
#include "supervisor/filesystem.h"
#include "supervisor/flash.h"
#include "supervisor/shared/translate/translate.h"
#include "supervisor/usb.h"

#if CIRCUITPY_USB_MSC
#include "tusb.h"

static const uint8_t usb_msc_descriptor_template[] = {
    // MSC Interface Descriptor
    0x09,        //  0 bLength
    0x04,        //  1 bDescriptorType (Interface)
    0xFF,        //  2 bInterfaceNumber [SET AT RUNTIME]
#define MSC_INTERFACE_INDEX (2)
    0x00,        //  3 bAlternateSetting
    0x02,        //  4 bNumEndpoints 2
    0x08,        //  5 bInterfaceClass: MSC
    0x06,        //  6 bInterfaceSubClass: TRANSPARENT
    0x50,        //  7 bInterfaceProtocol: BULK
    0xFF,        //  8 iInterface (String Index) [SET AT RUNTIME]
#define MSC_INTERFACE_STRING_INDEX (8)

    // MSC Endpoint IN Descriptor
    0x07,        //  9 bLength
    0x05,        // 10 bDescriptorType (Endpoint)
    0xFF,        // 11 bEndpointAddress (IN/D2H) [SET AT RUNTIME: 0x80 | number]
#define MSC_IN_ENDPOINT_INDEX (11)
    0x02,        // 12 bmAttributes (Bulk)
    #if USB_HIGHSPEED
    0x00, 0x02,  // 13,14 wMaxPacketSize 512
    #else
    0x40, 0x00,  // 13,14 wMaxPacketSize 64
    #endif
    0x00,        // 15 bInterval 0 (unit depends on device speed)

    // MSC Endpoint OUT Descriptor
    0x07,        // 16 bLength
    0x05,        // 17 bDescriptorType (Endpoint)
    0xFF,        // 18 bEndpointAddress (OUT/H2D) [SET AT RUNTIME]
#define MSC_OUT_ENDPOINT_INDEX (18)
    0x02,        // 19 bmAttributes (Bulk)
    #if USB_HIGHSPEED
    0x00, 0x02,  // 20,21 wMaxPacketSize 512
    #else
    0x40, 0x00,  // 20,21 wMaxPacketSize 64
    #endif
    0x00,        // 22 bInterval 0 (unit depends on device speed)
};

// Is the MSC device enabled?
bool storage_usb_is_enabled;

void storage_usb_set_defaults(void) {
    storage_usb_is_enabled = CIRCUITPY_USB_MSC_ENABLED_DEFAULT;
}

bool storage_usb_enabled(void) {
    return storage_usb_is_enabled;
}

size_t storage_usb_descriptor_length(void) {
    return sizeof(usb_msc_descriptor_template);
}

static const char storage_interface_name[] = USB_INTERFACE_NAME " Mass Storage";

size_t storage_usb_add_descriptor(uint8_t *descriptor_buf, descriptor_counts_t *descriptor_counts, uint8_t *current_interface_string) {
    memcpy(descriptor_buf, usb_msc_descriptor_template, sizeof(usb_msc_descriptor_template));
    descriptor_buf[MSC_INTERFACE_INDEX] = descriptor_counts->current_interface;
    descriptor_counts->current_interface++;

    descriptor_buf[MSC_IN_ENDPOINT_INDEX] =
        0x80 | (USB_MSC_EP_NUM_IN ? USB_MSC_EP_NUM_IN : descriptor_counts->current_endpoint);
    descriptor_counts->num_in_endpoints++;
    descriptor_buf[MSC_OUT_ENDPOINT_INDEX] =
        USB_MSC_EP_NUM_OUT ? USB_MSC_EP_NUM_OUT : descriptor_counts->current_endpoint;
    descriptor_counts->num_out_endpoints++;
    descriptor_counts->current_endpoint++;

    usb_add_interface_string(*current_interface_string, storage_interface_name);
    descriptor_buf[MSC_INTERFACE_STRING_INDEX] = *current_interface_string;
    (*current_interface_string)++;

    return sizeof(usb_msc_descriptor_template);
}

static bool usb_drive_set_enabled(bool enabled) {
    // We can't change the descriptors once we're connected.
    if (tud_connected()) {
        return false;
    }
    storage_usb_is_enabled = enabled;
    return true;
}

bool common_hal_storage_disable_usb_drive(void) {
    return usb_drive_set_enabled(false);
}

bool common_hal_storage_enable_usb_drive(void) {
    return usb_drive_set_enabled(true);
}
#else
bool common_hal_storage_disable_usb_drive(void) {
    return false;
}

bool common_hal_storage_enable_usb_drive(void) {
    return false;
}
#endif // CIRCUITPY_USB_MSC

STATIC mp_obj_t mp_vfs_proxy_call(mp_vfs_mount_t *vfs, qstr meth_name, size_t n_args, const mp_obj_t *args) {
    if (vfs == MP_VFS_NONE) {
        // mount point not found
        mp_raise_OSError(MP_ENODEV);
    }
    if (vfs == MP_VFS_ROOT) {
        // can't do operation on root dir
        mp_raise_OSError(MP_EPERM);
    }
    mp_obj_t meth[n_args + 2];
    mp_load_method(vfs->obj, meth_name, meth);
    if (args != NULL) {
        memcpy(meth + 2, args, n_args * sizeof(*args));
    }
    return mp_call_method_n_kw(n_args, 0, meth);
}

void common_hal_storage_mount(mp_obj_t vfs_obj, const char *mount_path, bool readonly) {
    // create new object
    mp_vfs_mount_t *vfs = m_new_obj(mp_vfs_mount_t);
    vfs->str = mount_path;
    vfs->len = strlen(mount_path);
    vfs->obj = vfs_obj;
    vfs->next = NULL;

    mp_obj_t args[2];
    args[0] = readonly ? mp_const_true : mp_const_false;
    args[1] = mp_const_false; // Don't make the file system automatically when mounting.

    // Check that there's no file or directory with the same name as the mount point.
    // But it's ok to mount '/' in any case.
    if (strcmp(vfs->str, "/") != 0) {
        nlr_buf_t nlr;
        if (nlr_push(&nlr) == 0) {
            common_hal_os_stat(mount_path);
            nlr_pop();
            // Something with the same name exists.
            mp_raise_OSError(MP_EEXIST);
        }
    }

    // check that the destination mount point is unused
    const char *path_out;
    mp_vfs_mount_t *existing_mount = mp_vfs_lookup_path(mount_path, &path_out);
    if (existing_mount != MP_VFS_NONE && existing_mount != MP_VFS_ROOT) {
        if (vfs->len != 1 && existing_mount->len == 1) {
            // if root dir is mounted, still allow to mount something within a subdir of root
        } else {
            // mount point in use
            mp_raise_OSError(MP_EPERM);
        }
    }

    // call the underlying object to do any mounting operation
    mp_vfs_proxy_call(vfs, MP_QSTR_mount, 2, (mp_obj_t *)&args);

    // Insert the vfs into the mount table by pushing it onto the front of the
    // mount table.
    mp_vfs_mount_t **vfsp = &MP_STATE_VM(vfs_mount_table);
    vfs->next = *vfsp;
    *vfsp = vfs;
}

void common_hal_storage_umount_object(mp_obj_t vfs_obj) {
    // remove vfs from the mount table
    mp_vfs_mount_t *vfs = NULL;
    for (mp_vfs_mount_t **vfsp = &MP_STATE_VM(vfs_mount_table); *vfsp != NULL; vfsp = &(*vfsp)->next) {
        if ((*vfsp)->obj == vfs_obj) {
            vfs = *vfsp;
            *vfsp = (*vfsp)->next;
            break;
        }
    }

    if (vfs == NULL) {
        mp_raise_OSError(MP_EINVAL);
    }

    // if we unmounted the current device then set current to root
    if (MP_STATE_VM(vfs_cur) == vfs) {
        MP_STATE_VM(vfs_cur) = MP_VFS_ROOT;
    }

    // call the underlying object to do any unmounting operation
    mp_vfs_proxy_call(vfs, MP_QSTR_umount, 0, NULL);
}

STATIC mp_obj_t storage_object_from_path(const char *mount_path) {
    for (mp_vfs_mount_t **vfsp = &MP_STATE_VM(vfs_mount_table); *vfsp != NULL; vfsp = &(*vfsp)->next) {
        if (strcmp(mount_path, (*vfsp)->str) == 0) {
            return (*vfsp)->obj;
        }
    }
    mp_raise_OSError(MP_EINVAL);
}

void common_hal_storage_umount_path(const char *mount_path) {
    common_hal_storage_umount_object(storage_object_from_path(mount_path));
}

mp_obj_t common_hal_storage_getmount(const char *mount_path) {
    return storage_object_from_path(mount_path);
}

void common_hal_storage_remount(const char *mount_path, bool readonly, bool disable_concurrent_write_protection) {
    if (strcmp(mount_path, "/") != 0) {
        mp_raise_OSError(MP_EINVAL);
    }

    #if CIRCUITPY_USB_MSC
    if (!usb_msc_ejected() && storage_usb_is_enabled) {
        mp_raise_RuntimeError(translate("Cannot remount '/' when visible via USB."));
    }
    #endif

    filesystem_set_internal_writable_by_usb(readonly);
    filesystem_set_internal_concurrent_write_protection(!disable_concurrent_write_protection);
}

void common_hal_storage_erase_filesystem(bool extended) {
    #if CIRCUITPY_USB
    usb_disconnect();
    #endif
    mp_hal_delay_ms(1000);
    #if CIRCUITPY_STORAGE_EXTEND
    supervisor_flash_set_extended(extended);
    #endif
    (void)filesystem_init(false, true);  // Force a re-format. Ignore failure.
    common_hal_mcu_reset();
    // We won't actually get here, since we're resetting.
}


text:
package fakes

import (
	bicloud "github.com/cloudfoundry/bosh-cli/cloud"
	bidisk "github.com/cloudfoundry/bosh-cli/deployment/disk"
)

type NewManagerInput struct {
	Cloud bicloud.Cloud
}

type FakeManagerFactory struct {
	NewManagerInputs  []NewManagerInput
	NewManagerManager bidisk.Manager
}

func NewFakeManagerFactory() *FakeManagerFactory {
	return &FakeManagerFactory{
		NewManagerInputs: []NewManagerInput{},
	}
}

func (f *FakeManagerFactory) NewManager(cloud bicloud.Cloud) bidisk.Manager {
	input := NewManagerInput{
		Cloud: cloud,
	}
	f.NewManagerInputs = append(f.NewManagerInputs, input)

	return f.NewManagerManager
}


text:
:note: When given multiple arguments, ``figura_print`` interprets all arguments which come after the first
    as override sets to be applied to the first. It is therefore useful for flexibly constructing configs, by
    combining the main config with one or more override sets.  Here, we make use of this flexibility.

Overlay vs. Overshadow
-----------------------------

Note the use of the ``__opaque_override__`` directive.  What does it do?

The Writer module may support new outputs in the future, which will cause new configs to be added
to the ``outputs`` container.
In offline mode, we know we only want one ("file").
The default semantic of override sets is to **overlay**, which means that if we had this::

    ...
    class outputs:
        class file:
            ...

other output types (e.g. ``db``) would not be affected. Only the container defining the ``file`` output
type will get new values.

Instead, when we do this::

    ...
    class outputs:
        __opaque_override__ = True
        class file:
            ...

we employ the **overshadow** semantics, which simply sets the value of ``outputs`` to the definitions
included, hiding existing definitions in the overridee.  This ensures we write to only one place.


text:
''' NEEDS TESTS '''

import operator
from functools import reduce

from registrasion.models import commerce
from registrasion.models import inventory

from collections import Iterable
from collections import namedtuple
from django.db.models import Case
from django.db.models import Q
from django.db.models import Sum
from django.db.models import When
from django.db.models import Value

_ProductAndQuantity = namedtuple("ProductAndQuantity", ["product", "quantity"])

class ProductAndQuantity(_ProductAndQuantity):
    ''' Class that holds a product and a quantity.

    Attributes:
        product (models.inventory.Product)

        quantity (int)

    '''
    pass

class ItemController(object):

    def __init__(self, user):
        self.user = user

    def _items(self, cart_status, category=None):
        ''' Aggregates the items that this user has purchased.

        Arguments:
            cart_status (int or Iterable(int)): etc
            category (Optional[models.inventory.Category]): the category
                of items to restrict to.

        Returns:
            [ProductAndQuantity, ...]: A list of product-quantity pairs,
                aggregating like products from across multiple invoices.

        '''

        if not isinstance(cart_status, Iterable):
            cart_status = [cart_status]

        status_query = (
            Q(productitem__cart__status=status) for status in cart_status
        )

        in_cart = Q(productitem__cart__user=self.user)
        in_cart = in_cart & reduce(operator.__or__, status_query)

        quantities_in_cart = When(
            in_cart,
            then="productitem__quantity",
        )

        quantities_or_zero = Case(
            quantities_in_cart,
            default=Value(0),
        )

        products = inventory.Product.objects

        if category:
            products = products.filter(category=category)

        products = products.select_related("category")
        products = products.annotate(quantity=Sum(quantities_or_zero))
        products = products.filter(quantity__gt=0)

        out = []
        for prod in products:
            out.append(ProductAndQuantity(prod, prod.quantity))
        return out

    def items_pending_or_purchased(self):
        ''' Returns the items that this user has purchased or has pending. '''
        status = [commerce.Cart.STATUS_PAID, commerce.Cart.STATUS_ACTIVE]
        return self._items(status)

    def items_purchased(self, category=None):
        ''' Aggregates the items that this user has purchased.

        Arguments:
            category (Optional[models.inventory.Category]): the category
                of items to restrict to.

        Returns:
            [ProductAndQuantity, ...]: A list of product-quantity pairs,
                aggregating like products from across multiple invoices.

        '''
        return self._items(commerce.Cart.STATUS_PAID, category=category)

    def items_pending(self):
        ''' Gets all of the items that the user has reserved, but has not yet
        paid for.

        Returns:
            [ProductAndQuantity, ...]: A list of product-quantity pairs for the
                items that the user has not yet paid for.

        '''

        return self._items(commerce.Cart.STATUS_ACTIVE)

    def items_released(self):
        ''' Gets all of the items that the user previously paid for, but has
        since refunded.

        Returns:
            [ProductAndQuantity, ...]: A list of product-quantity pairs for the
                items that the user has not yet paid for.

        '''

        return self._items(commerce.Cart.STATUS_RELEASED)