text:
steal('can/util', 'can/util/bind', 'can/util/batch', function (can, bind) {
	var stack = [];

	can.__read = function (func, self) {
		stack.push({});

		var value = func.call(self);

		return {
			value: value,
			observed: stack.pop()
		};
	};

	can.__reading = function (obj, event) {
		if (stack.length) {
			stack[stack.length-1][obj._cid + '|' + event] = {
				obj: obj,
				event: event + ""
			};
		}
	};

	can.__clearReading = function () {
		if (stack.length) {
			var ret = stack[stack.length-1];
			stack[stack.length-1] = {};
			return ret;
		}
	};

	can.__setReading = function (o) {
		if (stack.length) {
			stack[stack.length-1] = o;
		}
	};

	can.__addReading = function(o){
		if (stack.length) {
			can.simpleExtend(stack[stack.length-1], o);
		}
	};

	var getValueAndBind = function (func, context, oldObserved, onchanged) {
		// Call the function, get the value as well as the observed objects and events
		var info = can.__read(func, context),
			// The objects-event pairs that must be bound to
			newObserveSet = info.observed;
		// Go through what needs to be observed.
		bindNewSet(oldObserved, newObserveSet, onchanged);
		unbindOldSet(oldObserved, onchanged);

		return info;
	};

	// This will not be optimized.
	var bindNewSet = function(oldObserved, newObserveSet, onchanged){
		for(var name in newObserveSet ) {
			bindOrPreventUnbinding(oldObserved, newObserveSet, name, onchanged);
		}
	};

	// This will be optimized.
	var bindOrPreventUnbinding = function(oldObserved, newObserveSet, name, onchanged){
		if( oldObserved[name] ) {
			delete oldObserved[name];
		} else {
			var obEv = newObserveSet[name];
			obEv.obj.bind(obEv.event, onchanged);
		}
	};

	var unbindOldSet = function(oldObserved, onchanged){
		for (var name in oldObserved) {
			var obEv = oldObserved[name];
			obEv.obj.unbind(obEv.event, onchanged);
		}
	};

	var updateOnChange = function(compute, newValue, oldValue, batchNum){
		// Only trigger event when value has changed
		if (newValue !== oldValue) {
			can.batch.trigger(compute, batchNum ? {type: "change", batchNum: batchNum} : 'change', [
				newValue,
				oldValue
			]);
		}
	};

	var setupComputeHandlersOn = function() {
		this.readInfo = getValueAndBind(this._getterSetter, this._context, {}, this.onchanged);

		this.setCached(this.readInfo.value);
		this.hasDependencies = !can.isEmptyObject(this.readInfo.observed);
	};

	var setupComputeHandlersOff = function() {
		for (var name in this.readInfo.observed) {
			var ob = this.readInfo.observed[name];
			ob.obj.unbind(ob.event, this.onchanged);
		}
	};

	var setupComputeHandlers = function(compute, func, context) {
		var readInfo,
			onchanged,
			batchNum;

		return {
			// Set up handler for when the compute changes
			on: function(){
				var self = this;
				if(!onchanged) {
					onchanged = function(ev){
						if (compute.bound && (ev.batchNum === undefined || ev.batchNum !== batchNum) ) {
							// Keep the old value
							var oldValue = readInfo.value;
							// Get the new value
							readInfo = getValueAndBind(func, context, readInfo.observed, onchanged);
							// Call the updater with old and new values
							self.updater(readInfo.value, oldValue, ev.batchNum);
							batchNum = batchNum = ev.batchNum;
						}
					};
				}

				readInfo = getValueAndBind(func, context, {}, onchanged);

				compute.setCached(readInfo.value);
				compute.hasDependencies = !can.isEmptyObject(readInfo.observed);
			},
			// Remove handler for the compute
			off: function(updater){
				for (var name in readInfo.observed) {
					var ob = readInfo.observed[name];
					ob.obj.unbind(ob.event, onchanged);
				}
			}
		};
	};

	var setupSingleBindComputeHandlers = function(compute, func, context) {
		var readInfo,
			oldValue,
			onchanged,
			batchNum;

		return {
			// Set up handler for when the compute changes
			on: function(updater){
				if(!onchanged) {
					onchanged = function(ev){
						if (compute.bound && (ev.batchNum === undefined || ev.batchNum !== batchNum) ) {
							// Get the new value
							var reads = can.__clearReading();
							var newValue = func.call(context);
							can.__setReading(reads);
							// Call the updater with old and new values
							updater.call(compute, newValue, oldValue, ev.batchNum);
							oldValue = newValue;
							batchNum = batchNum = ev.batchNum;
						}
					};
				}

				readInfo = getValueAndBind(func, context, {}, onchanged);
				oldValue = readInfo.value;

				compute.setCached(readInfo.value);
				compute.hasDependencies = !can.isEmptyObject(readInfo.observed);
			},
			// Remove handler for the compute
			off: function(updater){
				for (var name in readInfo.observed) {
					var ob = readInfo.observed[name];
					ob.obj.unbind(ob.event, onchanged);
				}
			}
		};
	};

	var isObserve = function (obj) {
		return obj instanceof can.Map || obj && obj.__get;
	},
	// Instead of calculating whether anything is listening every time,
	// use a function to do nothing (which may be overwritten)
	k = function () {};

	var updater = function(newVal, oldVal, batchNum) {
		this.setCached(newVal);
		updateOnChange(this, newVal, oldVal, batchNum);
	},

	createAsyncAltUpdater = function(context, oldUpdater) {
		return function() {
			oldUpdater(context._get(), context.value);
		};
	},

	asyncGet = function(fn, context, lastSetValue) {
		return function() {
			return fn.call(context, lastSetValue.get());
		};
	},

	asyncUpdater = function(context, oldUpdater) {
		return function(newVal) {
			if(newVal !== undefined) {
				oldUpdater(newVal, context.value);
			}
		};
	};

	can.Compute = function(getterSetter, context, eventName, bindOnce) {
		var args = [];

		for(var i = 0, arglen = arguments.length; i < arglen; i++) {
			args[i] = arguments[i];
		}

		var contextType = typeof args[1];

		if (typeof args[0] === 'function') {
			this._setupGetterSetterFn(args[0], args[1], args[2], args[3]);
		} else if (args[1]) {
			if (contextType === 'string') {
				// `can.compute(object, propertyName[, eventName])`
				this._setupContextString(args[0], args[1], args[2]);
			} else if(contextType === 'function') {
				// `can.compute(initialValue, setter)`
				this._setupContextFunction(args[0], args[1], args[2]);
			} else {
				//`new can.Compute(initialValue, {})`
				if(args[1] && args[1].fn) {
					this._setupAsyncCompute(args[0], args[1]);
				} else {
					this._setupContextSettings(args[0], args[1]);
				}

			}
		} else {
			// `can.compute(initialValue)`
			this._setupInitialValue(args[0]);
		}

		this._args = args;

		this.isComputed = true;
		can.cid(this, 'compute');
	};

	can.simpleExtend(can.Compute.prototype, {
		//TODO: verify "this" is the instance of a compute
		_bindsetup: function () {
			this.bound = true;
			// Set up live-binding
			// While binding, this should not count as a read
			var oldReading = can.__clearReading();
			this._on(this.updater);
			// Restore "Observed" for reading
			can.__setReading(oldReading);
		},

		_bindteardown: function () {
			this._off(this.updater);
			this.bound = false;
		},

		bind: can.bindAndSetup,
		unbind: can.unbindAndTeardown,

		clone: function(context) {
			if(context && typeof this._args[0] === 'function') {
				this._args[1] = context;
			} else if(context) {
				this._args[2] = context;
			}

			return new can.Compute(this._args[0], this._args[1], this._args[2], this._args[3]);
		},

		_on: k,
		_off: k,

		get: function() {
			// Another compute may bind to this `computed`
			if(stack.length && this._canReadForChangeEvent !== false) {

				// Tell the compute to listen to change on this computed
				// Use `can.__reading` to allow other compute to listen
				// for a change on this `computed`
				can.__reading(this, 'change');
				// We are going to bind on this compute.
				// If we are not bound, we should bind so that
				// we don't have to re-read to get the value of this compute.
				if (!this.bound) {
					can.Compute.temporarilyBind(this);
				}
			}
			// If computed is bound, use the cached value
			if (this.bound) {
				return this.value;
			} else {
				return this._get();
			}
		},

		_get: function() {
			return this.value;
		},

		set: function(newVal) {
			// Save a reference to the old value
			var old = this.value;
			// Setter may return the value if setter
			// is for a value maintained exclusively by this compute.
			var setVal = this._set(newVal, old);

			// If the computed function has dependencies,
			// return the current value
			if (this.hasDependencies) {
				// If set can update the value,
				// just return the updated value.
				if(this._setUpdates) {
					return this.value;
				}

				return this._get();
			}
			// Setting may not fire a change event, in which case
			// the value must be read
			if (setVal === undefined) {
				this.value = this._get();
			} else {
				this.value = setVal;
			}
			// Fire the change
			updateOnChange(this, this.value, old);
			return this.value;
		},

		_set: function(newVal) {
			return this.value = newVal;
		},

		setCached: function(newVal) {
			this.value = newVal;
		},

		updater: updater,

		_computeFn: function(newVal) {
			if(arguments.length) {
				return this.set(newVal);
			}

			return this.get();
		},

		toFunction: function() {
			return can.proxy(this._computeFn, this);
		},

		_setupGetterSetterFn: function(getterSetter, context, eventName, bindOnce) {
			this._set = can.proxy(getterSetter, context);
			this._get = can.proxy(getterSetter, context);
			this._canReadForChangeEvent = eventName === false ? false : true;

			this._getterSetter = getterSetter;
			this._context = context;

			var handlers;
			if(bindOnce) {
				handlers = setupSingleBindComputeHandlers(this, getterSetter, context || this);
				this._on = handlers.on;
				this._off = handlers.off;
			}
			else {
				var self = this;
				this.onchanged = function(ev) {
					if (self.bound && (ev.batchNum === undefined || ev.batchNum !== self.batchNum)) {
						// Keep the old value
						var oldValue = self.readInfo.value;
						// Get the new value
						self.readInfo = getValueAndBind(getterSetter, context, self.readInfo.observed, self.onchanged);
						// Call the updater with old and new values
						self.updater(self.readInfo.value, oldValue, ev.batchNum);
						self.batchNum = ev.batchNum;
					}
				};
				this._on = setupComputeHandlersOn;
				this._off = setupComputeHandlersOff;
			}
		},

		_setupContextString: function(target, propertyName, eventName) {
			var isObserve = target instanceof can.Map,
			handler;
			this.updater = can.proxy(this.updater, this);

			if(isObserve) {
				this.hasDependencies = true;
				this._get = function() {
					return target.attr(propertyName);
				};
				this._set = function(val) {
					target.attr(propertyName, val);
				};
				this._on = function(update) {
					handler = function(ev, newVal,oldVal) {
						update(newVal, oldVal, ev.batchNum);
					};

					target.bind(eventName || propertyName, handler);
					// Set the cached value
					this.value = can.__read(this._get).value;
				};
				this._off = function() {
					return target.unbind(eventName || propertyName, handler);
				};
			} else {
				this._get = can.proxy(this._get, target);
				this._set = can.proxy(this._set, target);
			}
		},

		_setupContextFunction: function(initialValue, setter, eventName) {
			this.value = initialValue;
			this._set = setter;
			can.simpleExtend(this, eventName);
		},

		_setupContextSettings: function(initialValue, settings) {

			this.value = initialValue;
			var oldUpdater = can.proxy(this.updater, this);

			this._set = settings.set ? can.proxy(settings.set, settings) : this._set;
			this._get = settings.get ? can.proxy(settings.get, settings) : this._get;

			// This is a "hack" to allow async computes.
			this.updater = createAsyncAltUpdater(this, oldUpdater);

			this._on = settings.on ? settings.on : this._on;
			this._off = settings.off ? settings.off : this._off;
		},
		_setupAsyncCompute: function(initialValue, settings){

			this.value = initialValue;

			var oldUpdater = can.proxy(this.updater, this),
				self = this,
				fn = settings.fn,
				data;

			this.updater = oldUpdater;

			var lastSetValue = new can.Compute(initialValue);
			// expose this compute so it can be read
			this.lastSetValue = lastSetValue;
			this._setUpdates = true;
			this._set = function(newVal){
				// this is the value passed to the fn
				lastSetValue.set(newVal);
			};

			// make sure get is called with the newVal, but not setter
			this._get = asyncGet(fn, settings.context, lastSetValue);
			// Check the number of arguments the
			// async function takes.
			if(fn.length === 0) {
				// if it takes no arguments, it is calculated from other things.
				data = setupComputeHandlers(this, fn, settings.context);
			} else if(fn.length === 1) {
				// If it has a single argument, pass it the current value
				// or the value from define.set.
				data = setupComputeHandlers(this, function() {
					return fn.call(settings.context, lastSetValue.get() );
				}, settings);
			} else {
				// The updater function passed to on so that if called with
				// a single, non undefined value, works.
				this.updater = asyncUpdater(this, oldUpdater);

				// Finally, pass the function so it can decide the final value.
				data = setupComputeHandlers(this, function() {
					// Call fn, and get new value
					var res = fn.call(settings.context, lastSetValue.get(), function(newVal) {
						oldUpdater(newVal, self.value);
					});
					// If undefined is returned, don't update the value.
					return res !== undefined ? res : this.value;
				}, settings);
			}

			this._on = data.on;
			this._off = data.off;
		},
		_setupInitialValue: function(initialValue) {
			this.value = initialValue;
		}
	});

	// A list of temporarily bound computes
	var computes, unbindComputes = function () {
		for (var i = 0, len = computes.length; i < len; i++) {
			computes[i].unbind('change', k);
		}
		computes = null;
	};

	// Binds computes for a moment to retain their value and prevent caching
	can.Compute.temporarilyBind = function (compute) {
		compute.bind('change', k);
		if (!computes) {
			computes = [];
			setTimeout(unbindComputes, 10);
		}
		computes.push(compute);
	};

	can.Compute.async = function(initialValue, asyncComputer, context){
		return new can.Compute(initialValue, {
			fn: asyncComputer,
			context: context
		});
	};

	can.Compute.read = function (parent, reads, options) {
		options = options || {};
		// `cur` is the current value.
		var cur = parent,
			type,
			// `prev` is the object we are reading from.
			prev,
			// `foundObs` did we find an observable.
			foundObs;
		for (var i = 0, readLength = reads.length; i < readLength; i++) {
			// Update what we are reading from.
			prev = cur;
			// Read from the compute. We can't read a property yet.
			if (prev && prev.isComputed) {
				if (options.foundObservable) {
					options.foundObservable(prev, i);
				}
				prev = cur = prev instanceof can.Compute ? prev.get() : prev();
			}
			// Look to read a property from something.
			if (isObserve(prev)) {
				if (!foundObs && options.foundObservable) {
					options.foundObservable(prev, i);
				}
				foundObs = 1;
				// is it a method on the prototype?
				if (typeof prev[reads[i]] === 'function' && prev.constructor.prototype[reads[i]] === prev[reads[i]]) {
					// call that method
					if (options.returnObserveMethods) {
						cur = cur[reads[i]];
					} else if ( (reads[i] === 'constructor' && prev instanceof can.Construct) ||
						(prev[reads[i]].prototype instanceof can.Construct)) {
						cur = prev[reads[i]];
					} else {
						cur = prev[reads[i]].apply(prev, options.args || []);
					}
				} else {
					// use attr to get that value
					cur = cur.attr(reads[i]);
				}
			} else {
				// just do the dot operator
				if(cur == null) {
					cur = undefined;
				} else {
					cur = prev[reads[i]];
				}

			}
			type = typeof cur;
			// If it's a compute, get the compute's value
			// unless we are at the end of the
			if (cur && cur.isComputed && (!options.isArgument && i < readLength - 1)) {
				if (!foundObs && options.foundObservable) {
					options.foundObservable(prev, i + 1);
				}
				cur = cur();
			}
			// If it's an anonymous function, execute as requested
			else if (i < reads.length - 1 && type === 'function' && options.executeAnonymousFunctions && !(can.Construct && cur.prototype instanceof can.Construct)) {
				cur = cur();
			}
			// if there are properties left to read, and we don't have an object, early exit
			if (i < reads.length - 1 && (cur === null || type !== 'function' && type !== 'object')) {
				if (options.earlyExit) {
					options.earlyExit(prev, i, cur);
				}
				// return undefined so we know this isn't the right value
				return {
					value: undefined,
					parent: prev
				};
			}
		}
		// handle an ending function
		// unless it is a can.Construct-derived constructor
		if (typeof cur === 'function' && !(can.Construct && cur.prototype instanceof can.Construct) && !(can.route && cur === can.route)) {
			if (options.isArgument) {
				if (!cur.isComputed && options.proxyMethods !== false) {
					cur = can.proxy(cur, prev);
				}
			} else {
				if (cur.isComputed && !foundObs && options.foundObservable) {
					options.foundObservable(cur, i);
				}
				cur = cur.call(prev);
			}
		}
		// if we don't have a value, exit early.
		if (cur === undefined) {
			if (options.earlyExit) {
				options.earlyExit(prev, i - 1);
			}
		}
		return {
			value: cur,
			parent: prev
		};
	};
	can.Compute.truthy = function(compute) {
		return new can.Compute(function() {
			var res = compute.get();
			if(typeof res === 'function') {
				res = res.get();
			}
			return !!res;
		});
	};

	can.Compute.set = function(parent, key, value) {
		if(isObserve(parent)) {
			return parent.attr(key, value);
		}

		if(parent[key] && parent[key].isComputed) {
			return parent[key](value);
		}

		if(typeof parent === 'object') {
			parent[key] = value;
		}
	};

	return can.Compute;
});


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>Keeping It Real(Time) | that.guru</title>
  <meta name="description" content="">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <link rel="shortcut icon" href="https://that.guru/img/favicon.ico">
  <link rel="manifest" href="site.webmanifest">
  <link rel="apple-touch-icon" href="icon.png">

  <link rel="stylesheet" href="https://that.guru/css/normalize.css">
  <link rel="stylesheet" href="https://that.guru/css/main.css">
  <link rel="preload" href="https://that.guru/css/syntax.css" as="style" onload="this.onload=null;this.rel='stylesheet'">
  <link rel="stylesheet" href="https://that.guru/css/syntax.css"/>
  <link rel="preload" href="https://that.guru/css/fontawesome.css" as="style" onload="this.onload=null;this.rel='stylesheet'">
  <link rel="stylesheet" href="https://that.guru/css/fontawesome.css"/>
  <link rel="preload" href="https://that.guru/css/solid.css" as="style" onload="this.onload=null;this.rel='stylesheet'">
  <link rel="stylesheet" href="https://that.guru/css/solid.css"/>
  <link rel="preload" href="https://that.guru/css/brands.css" as="style" onload="this.onload=null;this.rel='stylesheet'">
  <link rel="stylesheet" href="https://that.guru/css/brands.css"/>

Keeping It Real(Time)

Blog

Talks

About

        <address class="author">Stephen Finucane</address></address>

        Presented <time datetime='2018-02-03T00:00:00Z'>Feb 3, 2018</time>

This talk was an expanded version of the talk I had given previously at the
Sydney OpenStack Summit and, as then, I once again discussed the real-time
capabilities of OpenStack Nova. It was delivered at FOSDEM 2018 to a crowd
of Virtualization and IaaS enthusiasts.

Real-time in OpenStack is a thing now. Let’s explore what this actually looks
like to a user, and (in brief) how it works under the hood.

Since Juno, OpenStack projects like nova have been on a steady march towards
adding the features and capabilities that users with NFV and HPC workloads
really need from their cloud. The latest of these nova features builds upon
earlier work to finally make real-time workloads in an OpenStack cloud a
reality. In this talk, we take a peek under the nova hood to see how this
feature works and how it ties into earlier work in this area (hint: KVM +
libvirt do most of the heavy lifting). We then demonstrate why this matters
and how you can use this feature and others like it in your own applications.

More information is available on the FOSDEM website.

(note: I can’t find the original cover photo, sadly. If anyone locates the
source, please let me know)

Please enable JavaScript to view the comments powered by Disqus.
comments powered by Disqus

    #openstack

© 2022 Stephen Finucane

redpajama_set_name: RedPajamaGithub


text:
/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/

"use strict";

const { ConcatSource } = require("webpack-sources");
const { UsageState } = require("../ExportsInfo");
const propertyAccess = require("../util/propertyAccess");
const { getEntryRuntime } = require("../util/runtime");
const AbstractLibraryPlugin = require("./AbstractLibraryPlugin");

/** @typedef {import("webpack-sources").Source} Source */
/** @typedef {import("../../declarations/WebpackOptions").LibraryOptions} LibraryOptions */
/** @typedef {import("../../declarations/WebpackOptions").LibraryType} LibraryType */
/** @typedef {import("../Compiler")} Compiler */
/** @typedef {import("../Module")} Module */
/** @typedef {import("../javascript/JavascriptModulesPlugin").RenderContext} RenderContext */
/** @template T @typedef {import("./AbstractLibraryPlugin").LibraryContext<T>} LibraryContext<T> */

/**
 * @typedef {Object} ExportPropertyLibraryPluginParsed
 * @property {string | string[]} export
 */

/**
 * @typedef {Object} ExportPropertyLibraryPluginOptions
 * @property {LibraryType} type
 * @property {boolean} nsObjectUsed the namespace object is used
 */
/**
 * @typedef {ExportPropertyLibraryPluginParsed} T
 * @extends {AbstractLibraryPlugin<ExportPropertyLibraryPluginParsed>}
 */
class ExportPropertyLibraryPlugin extends AbstractLibraryPlugin {
	/**
	 * @param {ExportPropertyLibraryPluginOptions} options options
	 */
	constructor({ type, nsObjectUsed }) {
		super({
			pluginName: "ExportPropertyLibraryPlugin",
			type
		});
		this.nsObjectUsed = nsObjectUsed;
	}

	/**
	 * @param {LibraryOptions} library normalized library option
	 * @returns {T | false} preprocess as needed by overriding
	 */
	parseOptions(library) {
		return {
			export: library.export
		};
	}

	/**
	 * @param {Module} module the exporting entry module
	 * @param {string} entryName the name of the entrypoint
	 * @param {LibraryContext<T>} libraryContext context
	 * @returns {void}
	 */
	finishEntryModule(
		module,
		entryName,
		{ options, compilation, compilation: { moduleGraph } }
	) {
		const runtime = getEntryRuntime(compilation, entryName);
		if (options.export) {
			const exportsInfo = moduleGraph.getExportInfo(
				module,
				Array.isArray(options.export) ? options.export[0] : options.export
			);
			exportsInfo.setUsed(UsageState.Used, runtime);
			exportsInfo.canMangleUse = false;
		} else {
			const exportsInfo = moduleGraph.getExportsInfo(module);
			if (this.nsObjectUsed) {
				exportsInfo.setUsedInUnknownWay(runtime);
			} else {
				exportsInfo.setAllKnownExportsUsed(runtime);
			}
		}
		moduleGraph.addExtraReason(module, "used as library export");
	}
	/**
	 * @param {Source} source source
	 * @param {RenderContext} renderContext render context
	 * @param {LibraryContext<T>} libraryContext context
	 * @returns {Source} source with library export
	 */
	render(source, renderContext, { options }) {
		if (!options.export) return source;
		const postfix = propertyAccess(
			Array.isArray(options.export) ? options.export : [options.export]
		);
		return new ConcatSource(source, postfix);
	}
}

module.exports = ExportPropertyLibraryPlugin;


text:
package com.siyeh.ig.threading;

import com.intellij.codeInspection.InspectionProfileEntry;
import com.siyeh.ig.LightInspectionTestCase;

/**
 * @author Bas Leijdekkers
 */
public class SharedThreadLocalRandomInspectionTest extends LightInspectionTestCase {
  @Override
  protected InspectionProfileEntry getInspection() {
    return new SharedThreadLocalRandomInspection();
  }

  @Override
  protected String[] getEnvironmentClasses() {
    return new String[] {
      "package java.util.concurrent;\n" +
      "import java.util.Random;" +
      "public class ThreadLocalRandom extends Random {" +
      "  public static ThreadLocalRandom current() {" +
      "    return null;" +
      "  }" +
      "}"
    };
  }

  public void testNoWarn() {
    doStatementTest("System.out.println(java.util.concurrent.ThreadLocalRandom.current().nextInt());");
  }

  public void testArgument() {
    doStatementTest("System.out.println(java.util.concurrent.ThreadLocalRandom./*'ThreadLocalRandom' instance might be shared between threads*/current/**/());");
  }

  public void testNoWarn2() {
    doMemberTest("void m() {" +
                 "  java.util.concurrent.ThreadLocalRandom r = java.util.concurrent.ThreadLocalRandom.current();" +
                 "}");
  }

  public void testNestedClass() {
    doMemberTest("void m() {" +
                 "  java.util.concurrent.ThreadLocalRandom r = java.util.concurrent.ThreadLocalRandom./*'ThreadLocalRandom' instance might be shared between threads*/current/**/();" +
                 "  class Z extends Thread {" +
                 "    public void run() {" +
                 "      System.out.println(r.nextInt(1));" +
                 "    }" +
                 "  }" +
                 "}");
  }

  public void testAssignmentToField() {
    doTest("import java.util.concurrent.ThreadLocalRandom;" +
           "class A {" +
           "  private ThreadLocalRandom r;" +
           "  void m() {" +
           "    r = ThreadLocalRandom./*'ThreadLocalRandom' instance might be shared between threads*/current/**/();" +
           "  }" +
           "}");
  }
}


text:
class NameGroup < ActiveRecord::Base
  self.table_name = "name_group"
  self.primary_key = "id"
  self.sequence_name = "nsl_global_seq"

  # attr_accessible :name

  has_many :name_ranks
  has_many :name_types
end


text:
from evergreen.futures._base import (FIRST_COMPLETED,
                                     FIRST_EXCEPTION,
                                     ALL_COMPLETED,
                                     CancelledError,
                                     TimeoutError,
                                     Future,
                                     Executor,
                                     wait,
                                     as_completed)
from evergreen.futures._task import TaskPoolExecutor
from evergreen.futures._thread import ThreadPoolExecutor
from evergreen.futures._process import ProcessPoolExecutor

__all__ =  ('FIRST_COMPLETED',
            'FIRST_EXCEPTION',
            'ALL_COMPLETED',
            'CancelledError',
            'TimeoutError',
            'Future',
            'Executor',
            'wait',
            'as_completed',
            'TaskPoolExecutor',
            'ThreadPoolExecutor',
            'ProcessPoolExecutor')


text:
#include "selxTypeList.h"

#include "selxDisplacementFieldMeshWarperComponent.h"

namespace selx
{
using ModuleDisplacementFieldMeshWarperComponents = selx::TypeList<
  ItkDisplacementFieldMeshWarperComponent< 2, float, float >,
  ItkDisplacementFieldMeshWarperComponent< 3, float, float >
>;
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Biologia, Lahore 17(1): 9 (1971)

#### Original name
Diplodina daemiae S. Ahmad

### Remarks
null


text:
            {% for nav in site.data.personal.navigation %}

                    {% assign navlink = nav.permalink | prepend: site.baseurl %}
                    {% if nav.permalink == page.permalink or (nav.permalink == "/" and page.permalink == null) %}
                        {% assign current = true %}
                    {% endif %}
                    {{ nav.text }}
                    {% assign current = false %}

            {% endfor %}


text:
package com.amazonaws.services.s3.model;
import java.io.Serializable;

/**
 * Container for redirect information. You can redirect requests to another
 * host, to another page, or with another protocol. In the event of an error,
 * you can can specify a different error code to return.
 */
public class RedirectRule implements Serializable {
    /** The protocol to use in the redirect request */
    private String protocol;

    /** The host name to use in the redirect request */
    private String hostName;

    /** The object prefix key to use in the redirect request */
    private String replaceKeyPrefixWith;

    /** The specific key to use in the redirect request */
    private String replaceKeyWith;

    /** The HTTP code to use in the redirect response */
    private String httpRedirectCode;

    /**
     * Set the protocol to use in the redirect request.
     */
    public void setProtocol(String protocol) {
        this.protocol = protocol;
    }

    /**
     * Return the protocol to use in the redirect request.
     */
    public String getprotocol() {
        return protocol;
    }

    /**
     * Set the protocol to use in the redirect request and and returns a
     * reference to this object(RoutingRuleRedirect) for method chaining.
     */
    public RedirectRule withProtocol(String protocol) {
        setProtocol(protocol);
        return this;
    }

    /**
     * Set the host name to use in the redirect request.
     */
    public void setHostName(String hostName) {
        this.hostName = hostName;
    }

    /**
     * Return the host name to use in the redirect request.
     */
    public String getHostName() {
        return hostName;
    }

    /**
     * Set the host name to use in the redirect request and returns a reference
     * to this object(RoutingRuleRedirect) for method chaining.
     */
    public RedirectRule withHostName(String hostName) {
        setHostName(hostName);
        return this;
    }

    /**
     * Set the object prefix key to use in the redirect request.
     */
    public void setReplaceKeyPrefixWith(String replaceKeyPrefixWith) {
        this.replaceKeyPrefixWith = replaceKeyPrefixWith;
    }

    /**
     * Return the object prefix key to use in the redirect request.
     */
    public String getReplaceKeyPrefixWith() {
        return replaceKeyPrefixWith;
    }

    /**
     * Set the object prefix key to use in the redirect request and returns a
     * reference to this object(RoutingRuleRedirect) for method chaining.
     */
    public RedirectRule withReplaceKeyPrefixWith(String replaceKeyPrefixWith) {
        setReplaceKeyPrefixWith(replaceKeyPrefixWith);
        return this;
    }

    /**
     * Set the specific key to use in the redirect request.
     */
    public void setReplaceKeyWith(String replaceKeyWith) {
        this.replaceKeyWith = replaceKeyWith;
    }

    /**
     * Return the specific key to use in the redirect request.
     */
    public String getReplaceKeyWith() {
        return replaceKeyWith;
    }

    /**
     * Set the specific key to use in the redirect request and returns a
     * reference to this object(RoutingRuleRedirect) for method chaining.
     */
    public RedirectRule withReplaceKeyWith(String replaceKeyWith) {
        setReplaceKeyWith(replaceKeyWith);
        return this;
    }

    /**
     * Set the HTTP code to use in the redirect response.
     */
    public void setHttpRedirectCode(String httpRedirectCode) {
        this.httpRedirectCode = httpRedirectCode;
    }

    /**
     * Return the HTTP code to use in the redirect response.
     */
    public String getHttpRedirectCode() {
        return httpRedirectCode;
    }

    /**
     * Set the HTTP code to use in the redirect response and returns a reference
     * to this object(RoutingRuleRedirect) for method chaining.
     */
    public RedirectRule withHttpRedirectCode(String httpRedirectCode) {
        this.httpRedirectCode = httpRedirectCode;
        return this;
    }
}


text:
<?php

/**
 * Class FunctionCtypePunctTest
 * @link http://php.net/manual/en/function.ctype-punct.php
 */
class FunctionCtypePunctTest extends PHPUnit_Framework_TestCase
{
    public function testFunctioCtypePunct()
    {
        $strings = array('ABasdk!@!$#', '!@ # $', '*&$()');
        $this->assertFalse(ctype_punct($strings[0]));
        $this->assertFalse(ctype_punct($strings[1]));
        $this->assertTrue(ctype_punct($strings[2]));
    }
}


text:
;(function(){

	"use strict";

	var __sk__ = '__bjStore__';

	var contextStorage = {
		store : {},
		setItem : function(key, val){
			this.store[key] = val;
		},
		getItem : function(key){
			return this.store[key] || null;
		},
		removeItem : function(key){
			if(!!this.store[key]){
				this.store[key] = null;
				delete this.store[key];
			}
		},
		clear : function(){
			this.store = {};
		}
	}

	function select(type){
		var db = null;
		if(type=='session' || type===2){
			db = !!window['localStorage']?window.localStorage:null;
		}
		else if(type=='local' || type===1){
			db = !!window['sessionStorage']?window.sessionStorage:null;
		}
		if(!db){
			db = contextStorage;
		}
		return db;
	}

	var S = bj.storage = {
		select : function(type){
			return select(type);
		}
	}
})();


text:
package main.java.framework.api;

/**
 * Common Visitor interface for framework metrics
 * @author Tomas
 */
public interface ICommonVisitor {

	/**
	 * @return {@link Language} enum
	 */
	Language getLanguage();

	/**
	 * @return the associated metric key
	 */
	public abstract String getKey();

	/**
	 * @return {@link Scope} enum
	 */
	public abstract Scope getScope();

	/**
	 * @return result of computation
	 */
	public abstract int getResult();

}


text:
import argparse
from pyspark.sql import SparkSession, Row
from pyspark.sql.functions import col, collect_list, sort_array, struct
import pyspark.sql.functions as f

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='Recode series',
                                     formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument('seriesPath', metavar='<series path>', help='series path')
    parser.add_argument('inputPath', metavar='<input path>', help='input path')
    parser.add_argument('outputPath', metavar='<output path>', help='output path')

    config = parser.parse_args()

    spark = SparkSession.builder.appName('Recode series').getOrCreate()

    series = spark.read.json(config.seriesPath
                ).groupBy('series2', 'series'
                ).agg(f.min('start').alias('start'), f.max('end').alias('end'))

    spark.read.load(config.inputPath).withColumnRenamed('series', 'series2'
        ).join(series, ['series2'], 'left_outer'
        ).filter( (col('start').isNull() | (col('start') <= col('date'))) &
                  (col('end').isNull() | (col('date') <= col('end')))
        ).withColumn('series', f.coalesce('series', 'series2')
        ).drop('series2', 'start', 'end'
        ).write.save(config.outputPath, mode='overwrite')

    spark.stop()


text:
CREATE TABLE PARTY_DIM(
        ID BIGINT GENERATED BY DEFAULT AS IDENTITY(START WITH 1) NOT NULL,
        NAME VARCHAR(50),
	PRIORITY INTEGER,
	SCOPE_ID VARCHAR(50),
        CONSTRAINT PK_PARTY_DIM PRIMARY KEY(ID)
);


text:
The presentation of the actor is a definition of every external user
to the system while the system just look like a black boxe , it's
a definition for the later step for building a Use Case Model

### Actors

Drop down of all the actor with a description of what they can do
on the different part of the system. First the user is the basic
configuration for offline ( without an account on a league server )

### User

When use the client without a account to a league server you
can use all the part of the client describe in Def_sys but
the data can only be stored locally on your system like the
video witch can be stored in the pi depending on the conf.
The user can share those file with external storage. First,
export to universal format for the text data and video.

### Player

A player is a type of account on a server league. He must
be link to a Team for a specific season. When he is connect
if allowed by the trainer he can share is data with the client
to the remote server after the game as file or with a live stream

### Trainer

Like the player but also can managed specific tools for scripting
reports and is haved full right on the team for the season he's
linked to. Like adding player account , remove player from team ,
alow player account to add data / stream from their client ,
Can sent praticing schedule to calender and set the training
program for the team

### League administrator

The big administrator of the league server. He add all the base
information in the database from the WebSite portal. He can monitor
and valid information send from various trainer and players. Control
the calendar and etc ...

### Guest

Guess is a user of the website who is not login , he can see public
information about league and watch live stream that the gotten from
shared URL

### Fan

The fan is basically a guest user but with a register account to allow
him to follow public team or player.

### Scoot

Like a fan account but also can be allowed by player to see footage
or stat from player.

![Shema Actor](Actor_Shema.png)


text:
import skbio

from q2_types.multiplexed_sequences import (
    MultiplexedFastaQualDirFmt, MultiplexedSingleEndBarcodeInSequenceDirFmt
)

from qiime2.plugin.testing import TestPluginBase

class TestMultiplexedSequencesTransformers(TestPluginBase):
    package = 'q2_types.multiplexed_sequences.tests'

    def test_fasta_qual_to_fastq(self):
        _, obs = self.transform_format(
            MultiplexedFastaQualDirFmt,
            target=MultiplexedSingleEndBarcodeInSequenceDirFmt,
            filenames=('reads.fasta', 'reads.qual'))

        sequences = skbio.io.read('%s/forward.fastq.gz' % str(obs),
                                  format='fastq',
                                  variant='illumina1.8')
        sequences = list(sequences)

        self.assertEqual(len(sequences), 3)

        self.assertTrue(str(sequences[0]).startswith('ACAGAGTCGGCTCA'))
        self.assertTrue(str(sequences[0]).endswith('ATGGGCTAGG'))
        self.assertTrue(str(sequences[1]).startswith('ACAGAGTCGGCTCA'))
        self.assertTrue(str(sequences[1]).endswith('CCGGTCGCCA'))
        self.assertTrue(str(sequences[2]).startswith('AGCACGAGCCTACA'))
        self.assertTrue(str(sequences[2]).endswith('GTCTCTTGGG'))

        self.assertEqual(sequences[0].metadata['id'], 'FLP3FBN01ELBSX')
        self.assertEqual(sequences[1].metadata['id'], 'FLP3FBN01EG8AX')
        self.assertEqual(sequences[2].metadata['id'], 'FLP3FBN01EEWKD')

        self.assertEqual(
            list(sequences[0].positional_metadata['quality'][:5]),
            [37, 37, 37, 37, 37])
        self.assertEqual(
            list(sequences[0].positional_metadata['quality'][-5:]),
            [21, 15, 15, 13, 13])
        self.assertEqual(
            list(sequences[1].positional_metadata['quality'][:5]),
            [37, 37, 37, 37, 37])
        self.assertEqual(
            list(sequences[1].positional_metadata['quality'][-5:]),
            [25, 25, 25, 25, 28])
        self.assertEqual(
            list(sequences[2].positional_metadata['quality'][:5]),
            [36, 37, 37, 37, 37])
        self.assertEqual(
            list(sequences[2].positional_metadata['quality'][-5:]),
            [36, 36, 36, 36, 36])


text:
assuming jruby is used via rbenv, rvm, etc

## setup

it needs to install/lockdown the gems and the jars in with two commands

### install/lockdown the gems

```
bundle install
```

which is important since it will create a file lib/gem-name_jars.rb
and installs the jar dependencies into a local cache (local maven repository)

### install/lockdown the jars

since there is Jarfile the jar dependencies from there only get installed with

```
lock_jars
```

## use it

```
rackup
```


text:
Melanie Simmons

Resourcing Director, NetDev Sys

simmons.melanie@ndsys.com | 0759765

Connect with Melanie

on LinkedIN


text:
package clair

import (
	"testing"

	digest "github.com/opencontainers/go-digest"
	"github.com/stretchr/testify/assert"
)

const (
	testHostname                = "clair.example.com"
	testHostnameWithProtocol    = "http://clair.example.com"
	testDigest                  = "sha256:cb749360c5198a55859a7f335de3cf4e2f64b60886a2098684a2f9c7ffca81f2"
	testNewLayerURI             = "https://" + testHostname + "/v1/layers"
	testGetLayerURI             = "https://" + testHostname + "/v1/layers/" + testDigest + "?vulnerabilities"
	testNewLayerURIWithProtocol = testHostnameWithProtocol + "/v1/layers"
)

func TestGetURIs(t *testing.T) {
	assert.Equal(t, testNewLayerURI, GetNewLayerURI(testHostname))
	assert.Equal(t, testGetLayerURI, GetLayerURI(testHostname, digest.Digest(testDigest)))
	assert.Equal(t, testNewLayerURIWithProtocol, GetNewLayerURI(testHostnameWithProtocol))
}


text:
  <md-content md-theme="docs-dark" layout-padding layout="row" layout-sm="column">
    <md-input-container>
      Title
      <input ng-model="user.title">
    </md-input-container>
    <md-input-container>
      Email
      <input ng-model="user.email" type="email">
    </md-input-container>
  </md-content>

  <md-content layout-padding>
    <form name="userForm">

        <md-input-container flex>
          Company (Disabled)
          <input ng-model="user.company" disabled>
        </md-input-container>

        <md-datepicker ng-model="user.submissionDate" md-placeholder="Enter date"></md-datepicker>

        <md-input-container flex>
          First name
          <input ng-model="user.firstName">
        </md-input-container>
        <md-input-container flex>
          Last Name
          <input ng-model="theMax">
        </md-input-container>

      <md-input-container class="md-block">
        Address
        <input ng-model="user.address">
      </md-input-container>

      <md-input-container md-no-float class="md-block">
        <input ng-model="user.address2" placeholder="Address 2">
      </md-input-container>

        <md-input-container flex>
          City
          <input ng-model="user.city">
        </md-input-container>

        <md-input-container flex>
          State
          <md-select ng-model="user.state">
            <md-option ng-repeat="state in states" value="{{state.abbrev}}">
              {{state.abbrev}}
            </md-option>
          </md-select>
        </md-input-container>

        <md-input-container flex>
          Postal Code
          <input name="postalCode" ng-model="user.postalCode" placeholder="12345"
                 required ng-pattern="/^[0-9]{5}$/" md-maxlength="5">

You must supply a postal code.

That doesn't look like a valid postal
              code.

              Don't use the long version silly...we don't need to be that specific...

        </md-input-container>

      <md-input-container class="md-block">
        Biography
        <textarea ng-model="user.biography" columns="1" md-maxlength="150"></textarea>
      </md-input-container>

    </form>
  </md-content>


text:
package io.debezium.transforms;

import java.util.HashMap;
import java.util.Map;

import org.apache.kafka.common.config.ConfigDef;
import org.apache.kafka.connect.connector.ConnectRecord;
import org.apache.kafka.connect.errors.ConnectException;
import org.apache.kafka.connect.transforms.ExtractField;
import org.apache.kafka.connect.transforms.Transformation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.debezium.config.Configuration;
import io.debezium.config.Field;

/**
 * Debezium generates CDC (Envelope) records that are struct of values containing values
 * before and after change. Sink connectors usually are not able to work
 * with a complex structure so a user use this SMT to extract after value and send it down
 * unwrapped in Envelope.
 *

 * The functionality is similar to ExtractField SMT but has a special semantics for handling
 * delete events; when delete event is emitted by database then Debezium emits two messages: a delete
 * message and a tombstone message that serves as a signal to Kafka compaction process.
 *

 * The SMT by default drops the tombstone message created by Debezium and converts the delete message into
 * a tombstone message that can be dropped, too, if required.
 *
 * @param <R> the subtype of {@link ConnectRecord} on which this transformation will operate
 * @author Jiri Pechanec
 */
public class UnwrapFromEnvelope<R extends ConnectRecord<R>> implements Transformation<R> {

    private static final String ENVELOPE_SCHEMA_NAME_SUFFIX = ".Envelope";
    private final Logger logger = LoggerFactory.getLogger(getClass());
    private static final Field DROP_TOMBSTONES = Field.create("drop.tombstones")
            .withDisplayName("Drop tombstones")
            .withType(ConfigDef.Type.BOOLEAN)
            .withWidth(ConfigDef.Width.SHORT)
            .withImportance(ConfigDef.Importance.LOW)
            .withDefault(true)
            .withDescription("Debezium by default generates a tombstone record to enable Kafka compaction after "
                    + "a delete record was generated. This record is usually filtered out to avoid duplicates "
                    + "as a delete record is converted to a tombstone record, too");

    private static final Field DROP_DELETES = Field.create("drop.deletes")
            .withDisplayName("Drop outgoing tombstones")
            .withType(ConfigDef.Type.BOOLEAN)
            .withWidth(ConfigDef.Width.SHORT)
            .withImportance(ConfigDef.Importance.MEDIUM)
            .withDefault(true)
            .withDescription("Drop delete records converted to tombstones records if a processing connector "
                    + "cannot process them or a compaction is undesirable.");

    private boolean dropTombstones;
    private boolean dropDeletes;
    private final ExtractField<R> delegate = new ExtractField.Value<R>();

    @Override
    public void configure(final Map<String, ?> configs) {
        final Configuration config = Configuration.from(configs);
        final Field.Set configFields = Field.setOf(DROP_TOMBSTONES, DROP_DELETES);
        if (!config.validateAndRecord(configFields, logger::error)) {
            throw new ConnectException("Unable to validate config.");
        }

        dropTombstones = config.getBoolean(DROP_TOMBSTONES);
        dropDeletes = config.getBoolean(DROP_DELETES);

        final Map<String, String> delegateConfig = new HashMap<>();
        delegateConfig.put("field", "after");
        delegate.configure(delegateConfig);
    }

    @Override
    public R apply(final R record) {
        if (record.value() == null) {
            if (dropTombstones) {
                logger.trace("Tombstone {} arrived and requested to be dropped", record.key());
                return null;
            }
            return record;
        }
        if (record.valueSchema() == null ||
                record.valueSchema().name() == null ||
                !record.valueSchema().name().endsWith(ENVELOPE_SCHEMA_NAME_SUFFIX)) {
            logger.warn("Expected Envelope for transformation, passing it unchanged");
            return record;
        }
        final R newRecord = delegate.apply(record);
        if (newRecord.value() == null && dropDeletes) {
            logger.trace("Delete message {} requested to be dropped", record.key());
            return null;
        }
        return newRecord;
    }

    @Override
    public ConfigDef config() {
        final ConfigDef config = new ConfigDef();
        Field.group(config, null, DROP_TOMBSTONES, DROP_DELETES);
        return config;
    }

    @Override
    public void close() {
        delegate.close();
    }

}


text:
@font-face {
  font-family: 'Lato';
  font-style: normal;
  font-weight: 300;
  src: local('Lato Light'), local('Lato-Light'), url(../fonts/lato/Lato-Light.woff) format('woff'), url(../fonts/lato/Lato-Light.ttf) format('truetype'), url(../fonts/lato/Lato-Light.woff2) format('woff2');
}

@font-face {
  font-family: 'Lato';
  font-style: normal;
  font-weight: 400;
  src: url(../fonts/lato/Lato-Regular.eot);
  src: local('Lato Regular'), local('Lato-Regular'), local('Lato'), url(../fonts/lato/Lato-Regular.woff) format('woff'), url(../fonts/lato/Lato-Regular.eot?#iefix) format('embedded-opentype'), url(../fonts/lato/Lato-Regular.ttf) format('truetype'), url(../fonts/lato/Lato-Regular.woff2) format('woff2'), url(../fonts/lato/Lato-Regular.svg#Lato) format('svg');
}

@font-face {
  font-family: 'Lato';
  font-style: normal;
  font-weight: 700;
  src: local('Lato Bold'), local('Lato-Bold'), url(../fonts/lato/Lato-Bold.woff) format('woff'), url(../fonts/lato/Lato-Bold.ttf) format('truetype'), url(../fonts/lato/Lato-Bold.woff2) format('woff2');
}

@font-face {
  font-family: 'Lato';
  font-style: normal;
  font-weight: 900;
  src: local('Lato Black'), local('Lato-Black'), url(../fonts/lato/Lato-Black.woff) format('woff'), url(../fonts/lato/Lato-Black.ttf) format('truetype'), url(../fonts/lato/Lato-Black.woff2) format('woff2');
}


text:
<!doctype html>

    <meta charset="utf-8">
    <title>{{'TITLE_SHORT' | translate}}: Prototyp</title>

                    {{'TITLE_SHORT' | translate}}

                {{ 'TITLE' | translate}}


text:
echo "vocabularyStats"
echo
echo "Analyzes generated PreMOn RDF and computes statistics on vocabulary usage, identifying these errors:"
echo "* classes and properties used (in ABox) but not declared (in TBox)"
echo "* object properties (in TBox) used as datatype properties (in ABox)"
echo "* datatype properties (in TBox) used as object properties (in ABox)"
echo "* functional properties (in TBox) used in a non-functional way (in ABox)"
echo "* inverse functional properties (in TBox) used in a non-inverse functional way (in ABox)"
echo
echo "The script must be run (without parameters) in the folder where the PreMOn RDF files generated by"
echo "Premonitor are located. The first run has to compute specific statistics (file vocabularyStats.tql.gz"
echo "from the all-inf dataset and this may take a while (2 minutes); these statistics are cached and reused"
echo "if the script is run echo again. Identified class and property errors are reported on stdout. Two files"
echo "vocabularyStats.classes.tsv and vocabularyStats.properties.tsv are generated with complete statistics"
echo "and validation status (OK, ERROR) for each class and property used in PreMOn ABox. This script requires"
echo "rdfpro installed and available on system PATH, and enough space on system /tmp folder"
echo

set -e

statistics_file=vocabularyStats.tql.gz
properties_file=vocabularyStats.properties.tsv
classes_file=vocabularyStats.classes.tsv

if [ ! -f $statistics_file ]; then
    echo "Generating statistics $statistics_file ..."
    rdfpro @read *-all-inf.tql.gz @transform "=c <sesame:nil>" @stats @read *-tbox-inf.tql.gz @write $statistics_file
fi

echo "Generating report $classes_file ..."
rdfpro @read $statistics_file @tsv -q '
    SELECT ?class ?entities ?triples ?typeTriples ?avgProps ?definedAs ?valid
    WHERE {
        [] void:class ?class;
           void:entities ?entities;
           void:triples ?triples;
           <http://rdfpro.fbk.eu/ontologies/voidx#typeTriples> ?typeTriples;
           <http://rdfpro.fbk.eu/ontologies/voidx#averageProperties> ?avgProps.
        BIND (IF(EXISTS { ?class a owl:Class }, "C", "-") AS ?definedAs )
        BIND (IF(?definedAs = "C", "OK", "ERROR") AS ?valid)
    }
    ORDER BY ?class' .temp.tsv
echo $'?class\t?entities\t?triples\t?typeTriples\t?avgProps\t?definedAs\t?valid' > $classes_file
cat .temp.tsv >> $classes_file
rm .temp.tsv

echo "Generating report $properties_file ..."
rdfpro @read $statistics_file @tsv -q '
    SELECT ?property ?triples ?subjects ?objects ?definedAs ?usedAs ?definedFunc ?usedFunc ?definedInvFunc ?usedInvFunc ?valid
    WHERE {
        [] void:property ?property;
           void:triples ?triples;
           void:distinctSubjects ?subjects;
           void:distinctObjects ?objects.
        BIND (IF(EXISTS { ?property a owl:DatatypeProperty }, "DP",
              IF(EXISTS { ?property a owl:ObjectProperty }, "OP",
              IF(EXISTS { ?property a owl:AnnotationProperty }, "AP",
              IF(EXISTS { ?property a rdf:Property }, "P", "-")))) AS ?definedAs)
        BIND (IF(EXISTS { ?property <http://rdfpro.fbk.eu/ontologies/voidx#type> owl:DatatypeProperty }, "DP",
              IF(EXISTS { ?property <http://rdfpro.fbk.eu/ontologies/voidx#type> owl:ObjectProperty }, "OP",
              IF(EXISTS { ?property <http://rdfpro.fbk.eu/ontologies/voidx#type> owl:AnnotationProperty }, "AP",
              IF(EXISTS { ?property <http://rdfpro.fbk.eu/ontologies/voidx#type> rdf:Property }, "AP", "-")))) AS ?usedAs)
        BIND (IF(EXISTS { ?property a owl:FunctionalProperty }, "F", "-") AS ?definedFunc)
        BIND (IF(EXISTS { ?property <http://rdfpro.fbk.eu/ontologies/voidx#type> owl:FunctionalProperty }, "F", "-") AS ?usedFunc)
        BIND (IF(EXISTS { ?property a owl:InverseFunctionalProperty }, "I", "-") AS ?definedInvFunc)
        BIND (IF(EXISTS { ?property <http://rdfpro.fbk.eu/ontologies/voidx#type> owl:InverseFunctionalProperty }, "I", "-") AS ?usedInvFunc)
        BIND (IF((?definedAs = "P" || ?definedAs = "AP" || ?definedAs = ?usedAs)
                 && (?definedFunc = "-" || ?definedFunc = ?usedFunc)
                 && (?definedInvFunc = "-" || ?definedInvFunc = ?usedInvFunc), "OK", "ERROR") AS ?valid)
    }
    ORDER BY ?property' .temp.tsv
echo $'?property\t?triples\t?subjects\t?objects\t?definedAs\t?usedAs\t?definedFunc\t?usedFunc\t?definedInvFunc\t?usedInvFunc\t?valid' > $properties_file
cat .temp.tsv >> $properties_file
rm .temp.tsv

if [[ $(grep 'ERROR$' $classes_file) ]]; then
    echo "Class errors: "
    sed '1p;/ERROR$/!d' $classes_file | column -t
    echo
fi

if [[ $(grep 'ERROR$' $properties_file) ]]; then
    echo "Property errors:"
    sed '1p;/ERROR$/!d' $properties_file | column -t
    echo
fi


text:
from __future__ import unicode_literals

from django.db import models, migrations
import djgeojson.fields

class Migration(migrations.Migration):

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='Location',
            fields=[
                ('wmoid', models.IntegerField(serialize=False, primary_key=True)),
                ('name', models.CharField(max_length=256)),
                ('geom', djgeojson.fields.PointField()),
            ],
            options={
            },
            bases=(models.Model,),
        ),
    ]


text:
from twilio.rest import Client

# put your own credentials here
account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
auth_token = "your_auth_token"

fax_sid = "FXaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"

client = Client(account_sid, auth_token)

fax = client.fax.v1.faxes(sid=fax_sid).fetch()

print(fax.sid)


text:
package tbx2rdf.service;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.logging.Logger;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//APACHE COMMONS
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;

/**
 * @author Víctor, mostly inspired from here: https://developers.google.com/appengine/kb/java?hl=en#fileforms
 * @version 1.0
 */
public class FileUploadServlet extends HttpServlet {

    private static final long serialVersionUID = 8367618333138027430L;

    private static final Logger log = Logger.getLogger(FileUploadServlet.class.getName());

    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        PrintWriter out = resp.getWriter();
        out.print("
Error: The request method " + req.getMethod() + " is inappropriate for the URL " + req.getRequestURI() + "
");
        out.close();
    }

    public void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException {
        try {
            ServletFileUpload upload = new ServletFileUpload();
            res.setContentType("text/html");
            res.setCharacterEncoding("UTF-8");
            FileItemIterator iterator = upload.getItemIterator(req);
            while (iterator.hasNext()) {
                FileItemStream item = iterator.next();
                InputStream stream = item.openStream();
                if (item.isFormField()) {
                    log.warning("Got a form field: " + item.getFieldName());
                } else {
                    log.warning("Got an uploaded file: " + item.getFieldName()+ ", name = " + item.getName());

                    // You now have the filename (item.getName() and the
                    // contents (which you can read from stream). Here we just
                    // print them back out to the servlet output stream, but you
                    // will probably want to do something more interesting (for
                    // example, wrap them in a Blob and commit them to the
                    // datastore).
/*                    int len;
                    byte[] buffer = new byte[8192];
                    while ((len = stream.read(buffer, 0, buffer.length)) != -1) {
                        res.getOutputStream().write(buffer, 0, len);
                    }*/
                    String content = IOUtils.toString(stream, "UTF-8");
                    tbx2rdfServlet.formatOutput(res,content);

                }
            }
        } catch (Exception ex) {
            //throw new ServletException(ex);
        }
    }
}


text:
using LinqToTwitter.Common;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json.Serialization;

namespace LinqToTwitter
{
    public record TwitterUserQuery
    {
        //
        // Query input fields
        //

        /// <summary>
        /// type of search, included for compatibility
        /// with other APIs
        /// </summary>
        public UserType Type { get; init; }

        /// <summary>
        /// Required for id queries - Up to 100 comma-separated IDs to search for
        /// </summary>
        public string? Ids { get; init; }

        /// <summary>
        /// Required for username queries - Up to 100 comma-separated usernames to search for
        /// </summary>
        public string? Usernames { get; init; }

        /// <summary>
        /// Comma-separated list of expansion fields
        /// </summary>
        public string? Expansions { get; init; }

        /// <summary>
        /// User ID for following/follower queries
        /// </summary>
        public string? ID { get; init; }

        /// <summary>
        /// ID for queries that need users associated with a list
        /// </summary>
        public string? ListID { get; set; }

        /// <summary>
        /// Max number of tweets to return per requrest - default 100 - possible 1000
        /// </summary>
        public int MaxResults { get; init; }

        /// <summary>
        /// Comma-separated list of fields to return in the media object - <see cref="MediaField"/>
        /// </summary>
        public string? MediaFields { get; set; }

        /// <summary>
        /// If set, with token from previous response metadata, pages forward or backward
        /// </summary>
        public string? PaginationToken { get; set; }

        /// <summary>
        /// Comma-separated list of fields to return in the place object - <see cref="PlaceField"/>
        /// </summary>
        public string? PlaceFields { get; set; }

        /// <summary>
        /// Comma-separated list of fields to return in the poll object - <see cref="PollField"/>
        /// </summary>
        public string? PollFields { get; set; }

        /// <summary>
        /// ID of space to query for users
        /// </summary>
        public string? SpaceID { get; set; }

        /// <summary>
        /// Comma-separated list of fields to return in the Tweet object
        /// </summary>
        public string? TweetFields { get; init; }

        /// <summary>
        /// ID of tweet that users are associated with. e.g. users who liked a tweet
        /// </summary>
        public string? TweetID { get; set; }

        /// <summary>
        /// Comma-separated list of fields to return in the User object
        /// </summary>
        public string? UserFields { get; init; }

        //
        // Output results
        //

        /// <summary>
        /// Tweet data returned from the search
        /// </summary>
        [JsonPropertyName("data")]
        public List<TwitterUser>? Users { get; init; }

        /// <summary>
        /// If any errors occur, they'll show up here
        /// </summary>
        [JsonPropertyName("errors")]
        public List<TwitterError>? Errors { get; init; }

        /// <summary>
        /// Were there errors?
        /// </summary>
        public bool HasErrors { get => Errors?.Any() ?? false; }

        /// <summary>
        /// Populated when query includes expansion fields
        /// </summary>
        [JsonPropertyName("includes")]
        public TwitterInclude? Includes { get; init; }
    }
}


text:
.lifeline-title {
    fill: #000000;
    text-anchor: middle;
    cursor: text;
}

.lifeline-line {
    stroke: #000000;
    stroke-width: 1px;
}

.outer-dashed {
    stroke-dasharray: 3, 2;
}

.lifeline-tool-line {
    stroke: #000000;
    stroke-width: 1px;
}

.lifeline-tool-rect {
    fill: #FFFFFF;
    fill-opacity: 1;
}

.tool > line {
    stroke-width: 1px;
}

.tool > rect {
    fill-opacity: 1;
}

.tool-group-header-collapse {
    background-color: #f3f3f3;
}

.resource > line {
    stroke: #000000;
}

.headingRect {
    fill: #FFFFFF;
    stroke-width: 1;
    stroke: #000000;

}

.headingRectIcon {
    fill: url(#resourceIcon);
}

.actionHeadingRectIcon {
    fill: url(#connectorActionIcon);
}
.resourceHeadingIconHolder{
    fill:#000000;
}

.connectorActionHeadingIconHolder{
    fill:#000000;
}

.headingCollapsedIcon {
    cursor: pointer;
    opacity: 0.4;
    fill: url(#collapsedIcon);
}

.headingCollapsedIcon:hover {
    opacity: 1;
}

.headingExpandIcon {
    cursor: pointer;
    opacity: 0.4;
    fill: url(#expandIcon);
}

.headingExpandIcon:hover {
    opacity: 1;
}

.headingDeleteIcon {
    cursor: pointer;
    fill: url(#deleteIcon);
 }

/*Resolves the issue of not showing the css referred svg images not showing in firefox*/
svg use svg {
    fill: inherit;
}

.headingDeleteIcon:hover {
    opacity: 1;
}

.httpMethodRect {
    fill: #f3f3f3;
}

.httpMethodText {
    fill: #000000;
}

.resourcePathPrefix {
    stroke-width: 0.5;
    stroke: #000000;

}

.resource > rect {
    fill: #ffffff;
}

.worker > line {
    stroke: #000000;
}

.worker > rect {
    fill: #ffffff;
}

.resource-content {
    fill: #008000;
    fill-opacity: 0;
    stroke-width: 1;
    stroke: #000000;
}

.connector-action-content {
    fill: #008000;
    fill-opacity: 0;
    stroke-width: 1;
    stroke: #000000;
}

.client rect {
    /*fill: #ffffff;*/
}

.client polygon {
    stroke: #000000;
    fill: #FFFFFF;
}

.client .lifeline-title {
    fill: #000000;
}

.client line {
    stroke: #000000;
}

.client text {
    fill: #000000;
}

.endpoint > line {
    stroke: #000000;
}

.endpoint > rect {
    fill: #ffffff;
}

.lifeline-polygon {
    fill: #ffffff;
}

.try-block-mediator-tool > rect {
    fill-opacity: 1;
    fill: #ffffff;
}

.try-block-mediator-tool > text {
    fill-opacity: 1;
    fill: #ffffff;
}

.switch-mediator-tool > rect {
    fill-opacity: 1;
    fill: #ffffff;
}

.switch-mediator-tool > text {
    fill-opacity: 1;
    fill: #ffffff;
}

.payload-factory-tool > rect {
    fill-opacity: 1;
    fill: #27ae60;
}

.payload-factory-tool > text {
    fill-opacity: 1;
    fill: #ffffff;
}

.log-mediator-tool > rect {
    fill-opacity: 1;
    fill: #2980b9;
}

.log-mediator-tool > text {
    fill-opacity: 1;
    fill: #ffffff;
}

.message {
    stroke: #000000;
    stroke-width: 1px;
}

.message:hover {
    cursor: pointer;
}

.lifeline {
}

.lifeline:hover {
    cursor: pointer;
}

.marker {
    fill: #000000;
}

.mediator-title {
    text-anchor: middle;
    alignment-baseline: central;
}

.input-output-text {
    font-size: 10px;
}

.source > polygon {
    fill: #FFFFFF;
    stroke-width: 1;
    stroke: #000000;
}

.action-rect{
    fill: #FFFFFF;
    stroke-width: 1;
    stroke: #333333;
}

.action-text{
text-anchor: start;
    fill:#333333;
}

.action-line{
    stroke: #9d9d9d;
}
.action-dash-line{
    stroke: #9d9d9d;
    stroke-dasharray: 5,5;

}
.action-arrow{
   stroke: #9d99d;
    fill: #000000;
}

.property-pane-action-button-edit {
    opacity: 0.3;
    fill: url(#editIcon);
}

.property-pane-action-button-edit:hover {
    cursor: pointer;
    opacity: 1;
    fill: url(#editIcon);
}

.property-pane-action-button-disable {
    opacity: 0.3;
    fill: url(#disableIcon);
}

.property-pane-action-button-disable:hover {
    cursor: pointer;
    opacity: 1;
    fill: url(#disableIcon);
}

.property-pane-action-button-delete {
    opacity: 0.3;
    fill: url(#deleteIcon);
}

.property-pane-action-button-delete:hover {
    cursor: pointer;
    opacity: 1;
    fill: url(#deleteIcon);
}

.property-pane-action-button-breakpoint {
    opacity: 0.3;
    fill: url(#addBreakpointIcon);
}

.property-pane-action-button-breakpoint:hover {
    cursor: pointer;
    opacity: 1;
    fill: url(#addBreakpointIcon);
}
.property-pane-action-button-breakpoint.active:hover {
    cursor: pointer;
    opacity: 1;
    fill: url(#debugRemoveIcon);
}
.statement-view-breakpoint-indicator {
    opacity: 0.8;
    fill: url(#debugIcon);
}

.statement-view-breakpoint-indicator:hover {
    cursor: pointer;
    opacity: 1;
    fill: url(#debugRemoveIcon);
}

.annotation-icon-background-circle {
    opacity: 0.4;
    cursor: pointer;
}

.variable-icon-background-circle {
    opacity: 0.4;
}

.annotation-icon-background-circle:hover {
    opacity: 1;
    cursor: pointer;
}

.annotation-icon-rect {
    cursor: pointer;
    fill: url(#annotationIcon);
}

.variable-icon-rect {
    fill: url(#variableIcon);
}

.if-else-svg-group{
    cursor: pointer;
}

.service-annotation-header-pane {
    fill: #eaeaea
}

.client-life-line{
    cursor: pointer;
}

.client-life-line text{
    cursor: pointer;
    font-weight: 400;
}

.client-life-line polygon{
    stroke: #333;
    fill: #FFFFFF;
}

.client-life-line line{
    stroke: #333;
}

.default-worker-life-line{
    cursor: pointer;
}
.default-worker-life-line text{
    cursor: pointer;
    font-weight: 300;
    font-size: 14px;
}

.default-worker-life-line rect{
    stroke: #000;
    fill: #e2e2e2;
    stroke-width: 2px;
}

.default-worker-life-line line{
    stroke: #000;
    stroke-width: 2px;
}

.connector-life-line {
    cursor: pointer;
}

.connector-life-line text {
    cursor: pointer;
}

.connector-life-line-top-polygon {
    fill: white;
    stroke: black;
}

.connector-life-line-bottom-polygon {
    fill: white;
    stroke: black;
}

.connector-life-line line{
    stroke: #000000;
}

.worker-life-line {
    cursor: pointer;
}

.worker-life-line text {
    cursor: pointer;
}

.worker-life-line-top-polygon {
    fill: white;
    stroke: black;
}

.worker-life-line-bottom-polygon {
    fill: white;
    stroke: black;
}

.worker-life-line line{
    stroke: #000000;
}

.start-action{
    stroke: #000000;
    fill: #FFFFFF;
}

.start-action text{
    fill: black;
    stroke-opacity: 0;
    font-weight: 300;
}

.statement-container .main-drop-zone{
    fill-opacity: 0;
    fill: #008000;
    stroke-width: 0;
}

.statement-container .main-drop-zone-hover{
    fill-opacity: 0.2;
}

.statement-container .inner-drop-zone{
    fill-opacity: 0;
    fill: #008000;
    stroke-width: 0;
}

.statement-container .inner-drop-zone-hover{
    fill-opacity: 0.4;
}

.operations-separator {
    stroke: #e8e8e8;
}

.heading-icon-wrapper {
    cursor: pointer;
    fill: #FFF;
}

.headingAnnotationIcon {
    cursor: pointer;
    opacity: 1;
    fill: url(#annotationIcon);
}

.headingAnnotationBlackIcon {
    cursor: pointer;
    fill: url(#annotationBlackIcon);
}

.headingAnnotationBlackIcon:hover {
    opacity: 1;
}

.headingAnnotationIcon:hover {
    opacity: 1;
}

.deleteRedIcon {
    cursor: pointer;
    fill: url(#deleteRedIcon);
}

.heading-icon-annotation-wrapper-clicked {
    stroke: #000;
    fill: #000;
}

.headingArgumentsIcon {
    cursor: pointer;
    opacity: 1;
    fill: url(#argumentsIcon);
}

.headingArgumentsBlackIcon {
    cursor: pointer;
    fill: url(#argumentsBlackIcon);
}

.headingArgumentsBlackIcon:hover {
    opacity: 2;
}

.headingReturnTypeIcon {
    cursor: pointer;
    opacity: 1;
    fill: url(#returnTypeIcon);
}

.headingReturnTypeBlackIcon {
    cursor: pointer;
    fill: url(#returnTypeBlackIcon);
}

.headingReturnTypeBlackIcon:hover {
    opacity: 1;
}

.heading-icon-arguments-wrapper-clicked {
    stroke: #000;
    fill: #000;
}

.heading-icon-return-type-wrapper-clicked {
    stroke: #000;
    fill: #000;
}

.worker-lifeline-grayed {
    fill: #e2e2e2;
    stroke: #000000;
    stroke-width: 2px;
}


text:
author: slowe
comments: true
date: 2014-07-31 09:00:00+00:00
layout: post
slug: installing-the-docker-plugin-for-heat
title: Installing the Docker Plugin for Heat
wordpress_id: 3480
categories: Tutorial
tags:
- Automation
- Docker
- OpenStack
- Linux
- Virtualization
---

In this post, I'll share with you how I installed the Docker plugin for OpenStack Heat, so that Heat is able to orchestrate the creation of Docker containers in an OpenStack environment. I'm publishing this because I found [the default instructions](https://github.com/openstack/heat/tree/stable/icehouse/contrib/docker/docker) to be a bit too vague to be helpful. By sharing my experience, I hope that others interested in using Docker in their OpenStack environment will benefit.

Here are the steps I used to make the Docker plugin work with Heat. These steps assume you are using Ubuntu and already have OpenStack Heat installed and working correctly:

1. If you are using the packaged version of Heat (in other words, you are installing Heat via a method like `apt-get install` on Ubuntu), then you'll want to use the "stable/icehouse" branch that contains the Docker container. In this case, you _don't_ want to use master---it won't work (either the plugin won't load or the Heat engine service won't start). Download a ZIP copy of the correct branch of Heat from GitHub (for "stable/icehouse", see [here](https://github.com/openstack/heat/tree/stable/icehouse)).

2. Extract the `contrib/docker` folder from the downloaded ZIP copy of Heat.

3. Delete the `contrib/docker/docker/tests` directory; in my testing, the plugin failed to load if you leave this directory present in the plugin.

4. Copy the `contrib/docker` folder to your OpenStack controller somewhere. On my controller, I chose to put it into an existing `/var/lib/heat` directory. When you're done, you should have a `docker` directory in your chosen destination, and that directory should container another subdirectory named `docker`. For example, on my system, the full path to the plugin was `/var/lib/heat/docker/docker`. Make note of the full path.

5. In the top-level `docker` folder, run `pip install -r requirements.txt`. Note that you might need to do an `apt-get install python-pip` first. This will install the docker-py Python module, which is required by the Docker plugin.

6. Modify your Heat configuration file (typically found at `/etc/heat/heat.conf`) and add the full path of the Docker plugin to the `plugin_dirs` setting. If you used `/var/lib/heat` as the base directory for the plugin, then the full path should be `/var/lib/heat/docker/docker`.

7. Restart the Heat engine (via something like `sudo service heat-engine restart` or similar).

8. Run `heat resource-type-list` and verify that DockerInc::Docker::Container is listed in the results. If not, verify that you have the correct path to the plugin specified in the Heat configuration file, and verify that you used the correct branch of the Docker plugin ("stable/icehouse" if you are using packaged versions of OpenStack). Review the Heat log files for any errors if the resource type still isn't listed.

Assuming you were successful, then you are ready to start deploying Docker containers via Heat. Stay tuned for an example Heat template that shows how to deploy a Docker container. Until then, feel free to share any corrections, clarifications, or questions in the comments below.


text:
@interface ProgressViewController : UIViewController

@end


text:
<?php

namespace Itkg\Core\Command;

use Itkg\Core\Command\DatabaseList\FinderInterface;
use Itkg\Core\Command\DatabaseUpdate\LocatorInterface;
use Itkg\Core\Command\DatabaseUpdate\ReleaseChecker;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

/**
 * Class DatabaseListCommand
 *
 * Symfony command to list migrations release (database update) script
 *
 * @author Pascal DENIS <pascal.denis@businessdecision.com>
 */
class DatabaseListCommand extends Command
{
    /**
     * @var LocatorInterface
     */
    private $locator;

    /**
     * @var FinderInterface
     */
    private $finder;

    /**
     * @var DatabaseUpdate\ReleaseChecker
     */
    private $checker;

    /**
     * @param LocatorInterface $locator
     * @param DatabaseList\FinderInterface $finder
     * @param DatabaseUpdate\ReleaseChecker $checker
     * @param null $name
     */
    public function __construct(
        LocatorInterface $locator,
        FinderInterface $finder,
        ReleaseChecker $checker,
        $name = null
    ) {
        parent::__construct($name);

        $this->locator = $locator;
        $this->checker = $checker;
        $this->finder  = $finder;
    }

    /**
     * Configure command
     */
    protected function configure()
    {
        $this
            ->setDescription('List releases SQL scripts & rollbacks')
            ->addOption(
                'path',
                null,
                InputOption::VALUE_REQUIRED,
                'Override default script path'
            );

    }

    /**
     * Execute command
     *
     * @param InputInterface $input
     * @param OutputInterface $output
     * @throws \RuntimeException
     * @throws \LogicException
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $this->configureOptions($input);

        $rows = $failed = array();
        foreach ($this->finder->findAll() as $release) {
            $this->locator->setParams(array('release' => $release));
            $scripts = $rollbacks = array();
            $status  = '<fg=green>OK</fg=green>';

            try {
                $scripts   = $this->locator->findScripts();
                $rollbacks = $this->locator->findRollbackScripts();
                $this->checker->check($scripts, $rollbacks);
            } catch (\Exception $e) {
                $status   = sprintf('<fg=red>%s</fg=red>', $e->getMessage());
                $failed[] = $release;
            }

            $rows[] = array($release, count($scripts), count($rollbacks), $status);
        }

        $this->display($output, $rows, $failed);
    }

    /**
     * Configure input options
     *
     * @param InputInterface $input
     */
    protected function configureOptions(InputInterface $input)
    {
        if ($input->getOption('path')) {
            $this->finder->setPath($input->getOption('path'));
            $this->locator->setParams(array('path' => $input->getOption('path')));
        }
    }

    /**
     * Display result as a table
     *
     * @param OutputInterface $output
     * @param array $rows
     */
    protected function display(OutputInterface $output, array $rows = array(), array $failed = array())
    {
        $this->getApplication()->getHelperSet()->get('table')
            ->setHeaders(array('Name', 'Scripts', 'Rollbacks', 'Status'))
            ->setRows($rows)
            ->render($output);

        if (!empty($failed)) {
            $output->writeln(sprintf('<fg=red>Check failed for release(s) %s</fg=red>', implode(', ', $failed)));
        }
    }
}


text:
require "chef"
require "spec_helper"

describe Chef::Provider::DscResource do
  let (:events) { Chef::EventDispatch::Dispatcher.new }
  let (:run_context) { Chef::RunContext.new(node, {}, events) }
  let (:resource) { Chef::Resource::DscResource.new("dscresource", run_context) }
  let (:provider) do
    Chef::Provider::DscResource.new(resource, run_context)
  end

  context "when Powershell does not support Invoke-DscResource" do
    let (:node) do
      node = Chef::Node.new
      node.automatic[:languages][:powershell][:version] = "4.0"
      node
    end
    it "raises a ProviderNotFound exception" do
      expect(provider).not_to receive(:meta_configuration)
      expect { provider.run_action(:run) }.to raise_error(
              Chef::Exceptions::ProviderNotFound, /5\.0\.10018\.0/)
    end
  end

  context "when Powershell supports Invoke-DscResource" do

    context "when RefreshMode is not set to Disabled" do
      context "and the WMF 5 is a preview release" do
        let (:node) do
          node = Chef::Node.new
          node.automatic[:languages][:powershell][:version] = "5.0.10018.0"
          node
        end
        it "raises an exception" do
          expect(provider).to receive(:dsc_refresh_mode_disabled?).and_return(false)
          expect { provider.run_action(:run) }.to raise_error(
            Chef::Exceptions::ProviderNotFound, /Disabled/)
        end
      end
      context "and the WMF is 5 RTM or newer" do
        let (:node) do
          node = Chef::Node.new
          node.automatic[:languages][:powershell][:version] = "5.0.10586.0"
          node
        end
        it "does not raises an exception" do
          expect(provider).to receive(:test_resource)
          expect(provider).to receive(:set_resource)
          expect(provider).to receive(:reboot_if_required)
          expect { provider.run_action(:run) }.to_not raise_error
        end
      end
    end
  end

  context "when the LCM supports Invoke-DscResource" do
    let (:node) do
      node = Chef::Node.new
      node.automatic[:languages][:powershell][:version] = "5.0.10018.0"
      node
    end
    let (:resource_result) { double("CmdletResult", return_value: { "InDesiredState" => true }, stream: "description") }
    let (:invoke_dsc_resource) { double("cmdlet", run!: resource_result) }
    let (:store) { double("ResourceStore", find: resource_records) }
    let (:resource_records) { [] }

    before do
      allow(Chef::Util::DSC::ResourceStore).to receive(:instance).and_return(store)
      allow(Chef::Util::Powershell::Cmdlet).to receive(:new).and_return(invoke_dsc_resource)
      allow(provider).to receive(:dsc_refresh_mode_disabled?).and_return(true)
    end

    it "does not update the resource if it is up to date" do
      expect(provider).to receive(:test_resource).and_return(true)
      provider.run_action(:run)
      expect(resource).not_to be_updated
    end

    it "converges the resource if it is not up to date" do
      expect(provider).to receive(:test_resource).and_return(false)
      expect(provider).to receive(:set_resource)
      provider.run_action(:run)
      expect(resource).to be_updated
    end

    it "flags the resource as reboot required when required" do
      expect(provider).to receive(:test_resource).and_return(false)
      expect(provider).to receive(:invoke_resource).
        and_return(double(:stdout => "", :return_value => nil))
      expect(provider).to receive(:add_dsc_verbose_log)
      expect(provider).to receive(:return_dsc_resource_result).and_return(true)
      expect(provider).to receive(:create_reboot_resource)
      provider.run_action(:run)
    end

    it "does not flag the resource as reboot required when not required" do
      expect(provider).to receive(:test_resource).and_return(false)
      expect(provider).to receive(:invoke_resource).
        and_return(double(:stdout => "", :return_value => nil))
      expect(provider).to receive(:add_dsc_verbose_log)
      expect(provider).to receive(:return_dsc_resource_result).and_return(false)
      expect(provider).to_not receive(:create_reboot_resource)
      provider.run_action(:run)
    end

    context "resource name cannot be found" do
      let (:resource_records) { [] }

      it "raises ResourceNotFound" do
        expect { provider.run_action(:run) }.to raise_error(Chef::Exceptions::ResourceNotFound)
      end
    end

    context "resource name is found" do
      context "no module name for resource found" do
        let (:resource_records) { [{}] }

        it "returns the default dsc resource module" do
          expect(Chef::Util::Powershell::Cmdlet).to receive(:new) do |node, cmdlet, format|
            expect(cmdlet).to match(/Module PSDesiredStateConfiguration /)
          end.and_return(invoke_dsc_resource)
          provider.run_action(:run)
        end
      end

      context "a module name for resource is found" do
        let (:resource_records) { [{ "Module" => { "Name" => "ModuleName" } }] }

        it "returns the default dsc resource module" do
          expect(Chef::Util::Powershell::Cmdlet).to receive(:new) do |node, cmdlet, format|
            expect(cmdlet).to match(/Module ModuleName /)
          end.and_return(invoke_dsc_resource)
          provider.run_action(:run)
        end
      end

      context "multiple resource are found" do
        let (:resource_records) do
          [
          { "Module" => { "Name" => "ModuleName1" } },
          { "Module" => { "Name" => "ModuleName2" } },
        ] end

        it "raises MultipleDscResourcesFound" do
          expect { provider.run_action(:run) }.to raise_error(Chef::Exceptions::MultipleDscResourcesFound)
        end
      end
    end
  end

  describe "define_resource_requirements" do
    let (:node) do
      set_node_object
    end

    context "module usage is valid" do
      before do
        allow(provider).to receive(:module_usage_valid?).and_return(true)
        allow(provider).to receive(:action_run)
      end

      [:run].each do |action|
        context "action #{action}" do
          it "does not raise the exception" do
            expect { provider.run_action(action) }.not_to raise_error
          end
        end
      end
    end

    context "module usage is invalid" do
      before do
        allow(provider).to receive(:module_usage_valid?).and_return(false)
        allow(provider).to receive(:action_run)
      end

      [:run].each do |action|
        context "action #{action}" do
          it "raises the exception" do
            expect { provider.run_action(action) }.to raise_error(
              Chef::Exceptions::DSCModuleNameMissing
            )
          end
        end
      end
    end
  end

  describe "module_usage_valid?" do
    let (:node) do
      set_node_object
    end

    context "module_name and module_version both are not provided" do
      before do
        provider.instance_variable_set(:@module_name, nil)
        provider.instance_variable_set(:@module_version, nil)
      end

      it "returns true" do
        response = provider.send(:module_usage_valid?)
        expect(response).to be == true
      end
    end

    context "module_name and module_version both are provided" do
      before do
        provider.instance_variable_set(:@module_name, "my_module")
        provider.instance_variable_set(:@module_version, "1.3")
      end

      it "returns true" do
        response = provider.send(:module_usage_valid?)
        expect(response).to be == true
      end
    end

    context "module_name is given but module_version is not given" do
      before do
        provider.instance_variable_set(:@module_name, "my_module")
        provider.instance_variable_set(:@module_version, nil)
      end

      it "returns true" do
        response = provider.send(:module_usage_valid?)
        expect(response).to be == true
      end
    end

    context "module_name is not given but module_version is given" do
      before do
        provider.instance_variable_set(:@module_name, nil)
        provider.instance_variable_set(:@module_version, "1.4.0.1")
      end

      it "returns false" do
        response = provider.send(:module_usage_valid?)
        expect(response).to be == false
      end
    end
  end

  describe "module_info_object" do
    let (:node) do
      set_node_object
    end

    context "module_version is not given" do
      before do
        provider.instance_variable_set(:@module_version, nil)
        allow(provider).to receive(:module_name).and_return("my_module")
      end

      it "returns only name of the module" do
        response = provider.send(:module_info_object)
        expect(response).to be == "my_module"
      end
    end

    context "module_version is given" do
      before do
        provider.instance_variable_set(:@module_version, "1.3.1")
        allow(provider).to receive(:module_name).and_return("my_module")
      end

      it "returns the module info object" do
        response = provider.send(:module_info_object)
        expect(response).to be == "@{ModuleName='my_module';ModuleVersion='1.3.1'}"
      end
    end
  end

  describe "invoke_resource" do
    let (:node) do
      set_node_object
    end

    let(:cmdlet) { double(:run! => nil) }

    before(:each) do
      allow(provider).to receive(:translate_type).and_return("my_properties")
      provider.instance_variable_set(:@new_resource, double(
        :properties => "my_properties", :resource => "my_resource", :timeout => 123
      ))
    end

    context "when module_version is not given" do
      before do
        allow(provider).to receive(:module_info_object).and_return("my_module")
      end

      it "invokes Invoke-DscResource command with module name" do
        expect(Chef::Util::Powershell::Cmdlet).to receive(:new).with(
          node,
          "Invoke-DscResource -Method my_method -Name my_resource -Property my_properties -Module my_module -Verbose",
          "my_output_format"
        ).and_return(cmdlet)
        provider.send(:invoke_resource, "my_method", "my_output_format")
      end
    end

    context "when module_version is given" do
      before do
        allow(provider).to receive(:module_info_object).and_return(
          "@{ModuleName='my_module';ModuleVersion='my_module_version'}"
        )
      end

      it "invokes Invoke-DscResource command with module info object" do
        expect(Chef::Util::Powershell::Cmdlet).to receive(:new).with(
          node,
          "Invoke-DscResource -Method my_method -Name my_resource -Property my_properties -Module @{ModuleName='my_module';ModuleVersion='my_module_version'} -Verbose",
          "my_output_format"
        ).and_return(cmdlet)
        provider.send(:invoke_resource, "my_method", "my_output_format")
      end
    end
  end
end

def set_node_object
  node = Chef::Node.new
  node.automatic[:languages][:powershell][:version] = "5.0.10586.0"
  node
end


text:
module TinyORM
  module Association
    def self.included(base)
      base.send(:extend, ClassMethods)
    end

    module ClassMethods
      def associations(name = nil)
        name ? @associations[name] : @associations
      end

      %w(has_many has_one belongs_to).each do |method|
        define_method method do |target, options = {}|
          #TODO association.define_methods
          @associations ||= {}
          @associations[target] = "TinyORM::Association::#{method.camelize}".constantize.new(self, target, options)
        end
      end
    end
  end
end


text:
typedef NS_ENUM(NSInteger, LSPeripheralConnectionState) {
    LSPeripheralConnectionStateNotConnected = 0,
    LSPeripheralConnectionStateScanning,
    LSPeripheralConnectionStateConnected,
};

@protocol LSBluetoothPeripheralDelegate <NSObject>
- (void)didRecieveString:(NSString*)string;
- (void)connectionStateChanged:(LSPeripheralConnectionState)connectionState;
@end

@interface LSBluetoothPeripheral : NSObject
@property (nonatomic, assign) LSPeripheralConnectionState connectionState;
@property (nonatomic, weak) id<LSBluetoothPeripheralDelegate> delegate;

- (void)scanForPeripherals;
- (void)disconnect;

- (void)sendString:(NSString*)string
           success:(void (^)(NSString*response))success
           failure:(void (^)(NSString*error))failure
           finally:(void (^)())finally;

- (void)sendStringArray:(NSArray*)stringArray
                success:(void (^)(NSString*response))success
                failure:(void (^)(NSString*error))failure
                finally:(void (^)())finally;

@end


text:
//jQuery time
var current_fs, next_fs, previous_fs; //fieldsets
var left, opacity, scale; //fieldset properties which we will animate
var animating; //flag to prevent quick multi-click glitches

$(".next").click(function(){
	if(animating) return false;
	animating = true;

	current_fs = $(this).parent();
	next_fs = $(this).parent().next();

	//activate next step on progressbar using the index of next_fs
	$("#progressbar li").eq($("fieldset").index(next_fs)).addClass("active");

	//show the next fieldset
	next_fs.show();
	//hide the current fieldset with style
	current_fs.animate({opacity: 0}, {
		step: function(now, mx) {
			//as the opacity of current_fs reduces to 0 - stored in "now"
			//1. scale current_fs down to 80%
			scale = 1 - (1 - now) * 0.2;
			//2. bring next_fs from the right(50%)
			left = (now * 50)+"%";
			//3. increase opacity of next_fs to 1 as it moves in
			opacity = 1 - now;
			current_fs.css({
        'transform': 'scale('+scale+')',
        'position': 'absolute'
      });
			next_fs.css({'left': left, 'opacity': opacity});
		},
		duration: 800,
		complete: function(){
			current_fs.hide();
			animating = false;
		},
		//this comes from the custom easing plugin
		easing: 'easeInOutBack'
	});
});

$(".previous").click(function(){
	if(animating) return false;
	animating = true;

	current_fs = $(this).parent();
	previous_fs = $(this).parent().prev();

	//de-activate current step on progressbar
	$("#progressbar li").eq($("fieldset").index(current_fs)).removeClass("active");

	//show the previous fieldset
	previous_fs.show();
	//hide the current fieldset with style
	current_fs.animate({opacity: 0}, {
		step: function(now, mx) {
			//as the opacity of current_fs reduces to 0 - stored in "now"
			//1. scale previous_fs from 80% to 100%
			scale = 0.8 + (1 - now) * 0.2;
			//2. take current_fs to the right(50%) - from 0%
			left = ((1-now) * 50)+"%";
			//3. increase opacity of previous_fs to 1 as it moves in
			opacity = 1 - now;
			current_fs.css({'left': left});
			previous_fs.css({'transform': 'scale('+scale+')', 'opacity': opacity});
		},
		duration: 800,
		complete: function(){
			current_fs.hide();
			animating = false;
		},
		//this comes from the custom easing plugin
		easing: 'easeInOutBack'
	});
});

$(".submit").click(function(){
	return false;
})


text:
<DOMSymbolItem xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://ns.adobe.com/xfl/2008/" name="CycleGroup" itemID="5294b89d-000002b1" linkageExportForAS="true" linkageClassName="CycleGroup" lastModified="1385564651">
  <timeline>
    <DOMTimeline name="CycleGroup">
      <layers>
        <DOMLayer name="Layer 1" color="#4FFF4F" current="true" isSelected="true">
          <frames>
            <DOMFrame index="0" keyMode="9728">
              <elements/>
            </DOMFrame>
          </frames>
        </DOMLayer>
      </layers>
    </DOMTimeline>
  </timeline>
</DOMSymbolItem>


text:
/**
 * @file
 * Declaration of a random replacement tag store.
 * The RandomRepl tags first try to evict an invalid
 * block. If no invalid blocks are found, a candidate
 * for eviction is found at random.
 */

#ifndef __MEM_CACHE_TAGS_RANDOM_REPL_HH__
#define __MEM_CACHE_TAGS_RANDOM_REPL_HH__

#include "mem/cache/tags/base_set_assoc.hh"
#include "params/RandomRepl.hh"

class RandomRepl : public BaseSetAssoc
{
  public:
    /** Convenience typedef. */
    typedef RandomReplParams Params;

    /**
     * Construct and initiliaze this tag store.
     */
    RandomRepl(const Params *p);

    /**
     * Destructor
     */
    ~RandomRepl() {}

    BlkType* accessBlock(Addr addr, bool is_secure, Cycles &lat,
                         int context_src);
    BlkType* findVictim(Addr addr) const;
    void insertBlock(PacketPtr pkt, BlkType *blk);
    void invalidate(BlkType *blk);
};

#endif // __MEM_CACHE_TAGS_RANDOM_REPL_HH__


text:
package com.flextrade.jfixture.behaviours.tracing;

import java.io.IOException;
import java.lang.reflect.Member;

public class MemberOnlyResponseStrategy implements TracingStrategy {

    @Override
    public void writeRequest(Appendable appendable, Object request) throws IOException {
        // Do nothing
    }

    @Override
    public void writeCreated(Appendable appendable, Object request, Object specimen) throws IOException {
        if (!(request instanceof Member)) return;

        Member member = (Member) request;
        appendable.append(String.format("%s = %s", member.getName(), specimen));
        appendable.append("\n");
    }

    @Override
    public void writeError(Appendable appendable, Exception exception) throws IOException {
        // Do nothing
    }
}


text:
#ifndef SkOTTable_OS_2_V0_DEFINED
#define SkOTTable_OS_2_V0_DEFINED

#include "SkEndian.h"
#include "SkIBMFamilyClass.h"
#include "SkOTTableTypes.h"
#include "SkPanose.h"
#include "SkTypedEnum.h"

#pragma pack(push, 1)

struct SkOTTableOS2_V0 {
    SK_OT_USHORT version;
    //SkOTTableOS2_VA::VERSION and SkOTTableOS2_V0::VERSION are both 0.
    //The only way to differentiate these two versions is by the size of the table.
    static const SK_OT_USHORT VERSION = SkTEndian_SwapBE16(0);

    SK_OT_SHORT xAvgCharWidth;
    struct WeightClass {
        SK_TYPED_ENUM(Value, SK_OT_USHORT,
            ((Thin, SkTEndian_SwapBE16(100)))
            ((ExtraLight, SkTEndian_SwapBE16(200)))
            ((Light, SkTEndian_SwapBE16(300)))
            ((Normal, SkTEndian_SwapBE16(400)))
            ((Medium, SkTEndian_SwapBE16(500)))
            ((SemiBold, SkTEndian_SwapBE16(600)))
            ((Bold, SkTEndian_SwapBE16(700)))
            ((ExtraBold, SkTEndian_SwapBE16(800)))
            ((Black, SkTEndian_SwapBE16(900)))
            SK_SEQ_END,
        SK_SEQ_END)
        SK_OT_USHORT value;
    } usWeightClass;
    struct WidthClass {
        SK_TYPED_ENUM(Value, SK_OT_USHORT,
            ((UltraCondensed, SkTEndian_SwapBE16(1)))
            ((ExtraCondensed, SkTEndian_SwapBE16(2)))
            ((Condensed, SkTEndian_SwapBE16(3)))
            ((SemiCondensed, SkTEndian_SwapBE16(4)))
            ((Medium, SkTEndian_SwapBE16(5)))
            ((SemiExpanded, SkTEndian_SwapBE16(6)))
            ((Expanded, SkTEndian_SwapBE16(7)))
            ((ExtraExpanded, SkTEndian_SwapBE16(8)))
            ((UltraExpanded, SkTEndian_SwapBE16(9)))
            SK_SEQ_END,
        (value)SK_SEQ_END)
    } usWidthClass;
    union Type {
        struct Field {
            //8-15
            SK_OT_BYTE_BITFIELD(
                Reserved08,
                Reserved09,
                Reserved10,
                Reserved11,
                Reserved12,
                Reserved13,
                Reserved14,
                Reserved15)
            //0-7
            SK_OT_BYTE_BITFIELD(
                Reserved00,
                Restricted,
                PreviewPrint,
                Editable,
                Reserved04,
                Reserved05,
                Reserved06,
                Reserved07)
        } field;
        struct Raw {
            static const SK_OT_USHORT Installable = 0;
            static const SK_OT_USHORT RestrictedMask = SkOTSetUSHORTBit<1>::value;
            static const SK_OT_USHORT PreviewPrintMask = SkOTSetUSHORTBit<2>::value;
            static const SK_OT_USHORT EditableMask = SkOTSetUSHORTBit<3>::value;
            SK_OT_USHORT value;
        } raw;
    } fsType;
    SK_OT_SHORT ySubscriptXSize;
    SK_OT_SHORT ySubscriptYSize;
    SK_OT_SHORT ySubscriptXOffset;
    SK_OT_SHORT ySubscriptYOffset;
    SK_OT_SHORT ySuperscriptXSize;
    SK_OT_SHORT ySuperscriptYSize;
    SK_OT_SHORT ySuperscriptXOffset;
    SK_OT_SHORT ySuperscriptYOffset;
    SK_OT_SHORT yStrikeoutSize;
    SK_OT_SHORT yStrikeoutPosition;
    SkIBMFamilyClass sFamilyClass;
    SkPanose panose;
    SK_OT_ULONG ulCharRange[4];
    SK_OT_CHAR achVendID[4];
    union Selection {
        struct Field {
            //8-15
            SK_OT_BYTE_BITFIELD(
                Reserved08,
                Reserved09,
                Reserved10,
                Reserved11,
                Reserved12,
                Reserved13,
                Reserved14,
                Reserved15)
            //0-7
            SK_OT_BYTE_BITFIELD(
                Italic,
                Underscore,
                Negative,
                Outlined,
                Strikeout,
                Bold,
                Regular,
                Reserved07)
        } field;
        struct Raw {
            static const SK_OT_USHORT ItalicMask = SkOTSetUSHORTBit<0>::value;
            static const SK_OT_USHORT UnderscoreMask = SkOTSetUSHORTBit<1>::value;
            static const SK_OT_USHORT NegativeMask = SkOTSetUSHORTBit<2>::value;
            static const SK_OT_USHORT OutlinedMask = SkOTSetUSHORTBit<3>::value;
            static const SK_OT_USHORT StrikeoutMask = SkOTSetUSHORTBit<4>::value;
            static const SK_OT_USHORT BoldMask = SkOTSetUSHORTBit<5>::value;
            static const SK_OT_USHORT RegularMask = SkOTSetUSHORTBit<6>::value;
            SK_OT_USHORT value;
        } raw;
    } fsSelection;
    SK_OT_USHORT usFirstCharIndex;
    SK_OT_USHORT usLastCharIndex;
    //version0
    SK_OT_SHORT sTypoAscender;
    SK_OT_SHORT sTypoDescender;
    SK_OT_SHORT sTypoLineGap;
    SK_OT_USHORT usWinAscent;
    SK_OT_USHORT usWinDescent;
};

#pragma pack(pop)

static_assert(sizeof(SkOTTableOS2_V0) == 78, "sizeof_SkOTTableOS2_V0_not_78");

#endif