text:
import { DEFAULT_PARAMS, OBJECTS, MANDATORY_OBJECTS, OBJECT_PARAMETERS } from "./lib/objectList.js";
import { ResourceController } from "./lib/resource.js";
import { EventEmitter } from "events";
import pick from "lodash.pick";
import uniq from "lodash.uniq";
import XebraCommunicator from "xebra-communicator";

import { getInstanceForObjectType, ObjectNode, ParamNode } from "./nodes/index.js";

function isString(v) {
	return typeof v === "string" || v instanceof String;
}

const RESOURCE_REQUEST_DOMAIN = Object.freeze({
	INFO: "info",
	DATA: "data"
});

/**
 * List of objects available for synchronization in Xebra. Use this or a subset of this when setting the
 * supported_objects option in Xebra.State.
 *
 * @static
 * @constant
 * @memberof Xebra
 * @type {string[]}
 */
const SUPPORTED_OBJECTS = Object.freeze(Array.from(Object.values(OBJECTS)));

/**
 * @namespace Xebra
 */

// /////////////////////
// Type Definitions   //
// /////////////////////

/**
 * A string or number based id
 * @typedef {number|string} NodeId
 * @memberof Xebra
 */

/**
 * @typedef {number[]} PatchingRect
 * @memberof Xebra
 * @desc Patching Rectangle attribute consisting of 4 Numbers (x, y, width, height)
 */

/**
 * @typedef {number|string|string[]|number[]|object} ParamValueType
 * @memberof Xebra
 * @desc Generic parameter value type
 */

/**
 * @typedef {number[]} Color
 * @memberof Xebra
 * @desc Color attribute consisting of 4 Numbers in the format of [r, g, b, a]
 */

// /////////////////////

/**
 * @desc State instances wrap the state sync and connection with the Max backend.
 * @class
 */
class State extends EventEmitter {

	/**
	 * @param  {Object} options
	 * @param  {Boolean} options.auto_connect=true - Whether to autoconnect on startup
	 * @param  {String} options.hostname - The host of the Xebra backend
	 * @param  {Number} options.port - The port of the Xebra backend
	 * @param  {Boolean} options.secure=false - Whether to use a secure WS connection or not (ws vs wss)
	 * @param  {Boolean} options.reconnect=true - Whether to try auto-reconnecting after the connection closed
	 * @param  {Number} options.reconnect_attempts=5 - The amount of retries before considering it a failure
	 * @param  {Number} options.reconnect_timeout=1000 - Timeout between reconnects in ms
	 * @param  {string[]} options.supported_objects - List of objects to include in the state
	 */
	constructor(options) {
		super();

		const commOptions = pick(options, ["auto_connect", "hostname", "port", "secure", "reconnect", "reconnect_attempts", "reconnect_timeout"]);
		if (!options.supported_objects) options.supported_objects = SUPPORTED_OBJECTS;

		commOptions.supported_objects = Object.assign({}, MANDATORY_OBJECTS);
		options.supported_objects.forEach((objDetails) => {
			if (isString(objDetails)) {
				const params = OBJECT_PARAMETERS[objDetails];
				if (params) {
					commOptions.supported_objects[objDetails] = params;
					return;
				}

				if (!MANDATORY_OBJECTS.hasOwnProperty(objDetails)) {
					console.log(`WARN: Unsupported or unknown object ${objDetails}. Please use the { name : ""<obj_name>", parameters: ["param_1", "param_2"] } syntax for non built-in objects.`);
					return;
				}
			} else if (typeof objDetails === "object") {
				if (!objDetails.name || !isString(objDetails.name) || !objDetails.parameters || !Array.isArray(objDetails.parameters)) {
					console.log(`WARN: Skipping object defintion '${JSON.stringify(objDetails)}' Please declare objects using their name or the { name : ""<obj_name>", parameters: ["param_1", "param_2"] } syntax.`);
					return;
				}

				// make sure that all required parameters are in place
				let params = DEFAULT_PARAMS.concat(objDetails.parameters);
				params = uniq(params);
				commOptions.supported_objects[objDetails.name] = params;

				return;
			}

			console.log(`WARN: Skipping object defintion '${objDetails}' Please declare objects using their name or the { name : ""<obj_name>", parameters: ["param_1", "param_2"] } syntax.`);
			return;
		});

		this._communicator = new XebraCommunicator(commOptions);
		this._communicator.on(XebraCommunicator.XEBRA_MESSAGES.CONNECTION_CHANGE, this._onConnectionChange);

		this._communicator.on(XebraCommunicator.XEBRA_MESSAGES.ADD_NODE, this._addNode);
		this._communicator.on(XebraCommunicator.XEBRA_MESSAGES.ADD_PARAM, this._addParam);
		this._communicator.on(XebraCommunicator.XEBRA_MESSAGES.CHANNEL_MESSAGE, this._channelMessage);
		this._communicator.on(XebraCommunicator.XEBRA_MESSAGES.DELETE_NODE, this._deleteNode);
		this._communicator.on(XebraCommunicator.XEBRA_MESSAGES.HANDLE_RESOURCE_DATA, this._handleResourceData);
		this._communicator.on(XebraCommunicator.XEBRA_MESSAGES.HANDLE_RESOURCE_INFO, this._handleResourceInfo);
		this._communicator.on(XebraCommunicator.XEBRA_MESSAGES.INIT_NODE, this._modifyNode);
		this._communicator.on(XebraCommunicator.XEBRA_MESSAGES.MODIFY_NODE, this._modifyNode);
		this._communicator.on(XebraCommunicator.XEBRA_MESSAGES.STATEDUMP, this._statedump);
		this._communicator.on(XebraCommunicator.XEBRA_MESSAGES.CLIENT_param_changed, this._clientParamChange);

		this._resourceRequests = {
			info: {
				sequence: 0,
				resourceToSequence: {},
				sequenceToResource: {}
			},
			data: {
				sequence: 0,
				resourceToSequence: {},
				sequenceToResource: {}
			}
		};

		this._isStateLoaded = false;
		this._rootNode = null;
		this._state = new Map();
		this._patchers = new Map();
		this._motionNodes = new Map();
		this._resourceController = new ResourceController();
		this._resourceController.on("get_resource_info", this._onGetResourceInfo);
	}

	/**
	 * Returns whether motion tracking is currently enabled/disabled.
	 * @type {boolean}
	 * @readonly
	 */
	get isMotionEnabled() {
		return this._motionNodes.size > 0;
	}

	/**
	 * Returns the current connection state.
	 * @type {number}
	 * @readonly
	 * @see {Xebra.CONNECTION_STATES}
	 */
	get connectionState() {
		return this._communicator.connectionState;
	}

	/**
	 * Name of the current xebra connection. For some Max objects, like mira.motion and mira.multitouch, multiple xebra
	 * clients (connected via Xebra.js or the Mira iOS app) can send events to the same object. This name property will
	 * be appended to these events, so that the events can be routed in Max.
	 * @type {string}
	 */
	get name() {
		return this._communicator.name;
	}

	set name(name) {
		this._communicator.name = name;
	}

	/**
	 * Hostname of the Max WebSocket.
	 * @type {string}
	 * @readonly
	 */
	get hostname() {
		return this._communicator.host;
	}

	/**
	 * Returns whether the initial state has been received from Max and loaded.
	 * @type {boolean}
	 * @readonly
	 */
	get isStateLoaded() {
		return this._isStateLoaded;
	}

	/**
	 * Returns the port number of the Max WebSocket.
	 * @type {number}
	 * @readonly
	 */
	get port() {
		return this._communicator.port;
	}

	/**
	 * WebSocket connection URL.
	 * @type {string}
	 * @readonly
	 */
	get wsUrl() {
		return this._communicator.wsUrl;
	}

	/**
	 * UUID associated with this state.
	 * @type {string}
	 * @readonly
	 */
	get uuid() {
		return this._communicator.uuid;
	}

	/**
	 * UID assigned to this state by Max, after connection.
	 * @private
	 * @readonly
	 */
	get xebraUuid() {
		return this._communicator.xebraUuid;
	}

	/* Connection related events */

	/**
	 * @private
	 * @throws throws an Error when the RESOURCE_REQUEST_DOMAIN is invalid
	 */
	_makeResourceRequest(context, resource, domain) {
		if (domain !== RESOURCE_REQUEST_DOMAIN.INFO && domain !== RESOURCE_REQUEST_DOMAIN.DATA) {
			throw new Error(`Resource request domain must be one of: ${RESOURCE_REQUEST_DOMAIN.DATA}, ${RESOURCE_REQUEST_DOMAIN.INFO}`);
		}

		// If there was a previous request from this resource, remove it
		if (this._resourceRequests[domain].resourceToSequence.hasOwnProperty(resource.id)) {
			const oldSequence = this._resourceRequests[domain].resourceToSequence[resource.id];
			delete this._resourceRequests[domain].sequenceToResource[oldSequence];
		}

		const sequence = ++this._resourceRequests[domain].sequence;
		this._resourceRequests[domain].resourceToSequence[resource.id] = sequence;
		this._resourceRequests[domain].sequenceToResource[sequence] = resource;
		const payload = {
			context: context,
			name: resource.filename,
			width: resource.dimensions.width,
			height: resource.dimensions.height,
			sequence: sequence,
			as_png: 1 // This asks Max to render SVG surfaces to PNG instead of raw bytes
		};

		if (domain === RESOURCE_REQUEST_DOMAIN.INFO) {
			this._communicator.getResourceInfo(payload);
		} else if (domain === RESOURCE_REQUEST_DOMAIN.DATA) {
			this._communicator.getResourceData(payload);
		}
	}

	/**
	 * @private
	 */
	_onConnectionChange = (status) => {
		/**
		 * This event is emitted when the state of the web socket connection to the Max patch (ConnectionState) changes.
		 * @event State.connection_changed
		 */
		this.emit("connection_changed", status);
	}

	/**
	 * @private
	 */
	_onGetResourceInfo = (resource) => {
		this._makeResourceRequest(resource.objectContext, resource, "info");
	}

	/**
	 * @private
	 * @fires State.frame_changed
	 * @fires State.object_changed
	 * @fires State.patcher_changed
	 */
	_onNodeChange = (object, param) => {
		if (object.type === OBJECTS.MIRA_FRAME) {
			/**
			 * This event is emitted when a parameter of a frame is changed. This change can come from Max or when the value
			 * of the parameter is set directly.
			 * @event State.frame_changed
			 * @param {FrameNode}				frame     The changed frame
			 * @param {ParamNode}		param      The parameter node
			 */
			if (object.isReady) this.emit("frame_changed", object, param);
		}
		if (object.type === OBJECTS.PATCHER) {
			/**
			 * This event is emitted when a parameter of a patcher is changed. This change can come from Max or when the
			 * value of the parameter is set directly.
			 * @event State.patcher_changed
			 * @param {PatcherNode}    patcher    The changed patcher
			 * @param {ParamNode}  param      The parameter node
			 */
			if (object.isReady) this.emit("patcher_changed", object, param);
		}

		/**
		 * This event is emitted when a parameter of an object is changed. This change can come from Max or when the value
		 * of the parameter is set directly.
		 * @event State.object_changed
		 * @param {ObjectNode} object     The changed object
		 * @param {ParamNode}  param      The parameter node
		 */
		if (object.isReady) this.emit("object_changed", object, param);
	}

	/**
	 * @private
	 */
	_onNodeInitialized = (object) => {
		this.emit("object_added", object);
	}

	/**
	 * @private
	 */
	_onFrameInitialized = (frame) => {
		this.emit("frame_added", frame);
	}

	/**
	 * @private
	 */
	_onPatcherInitialized = (patcher) => {
		this.emit("patcher_added", patcher);
	}

	/**
	 * @private
	 */
	_onModifiyNodeChange = (object, param) => {
		let val = param.value;
		if (!Array.isArray(val)) val = [val];

		this._communicator.sendModifyMessage({
			id: param.id,
			sequence: param.sequence,
			creation_sequence: param.creationSequence,
			values: val,
			types: param.types
		});
	}

	/**
	 * @private
	 */
	_addMotion(node) {
		this._motionNodes.set(node.id, node);

		if (this._motionNodes.size === 1) {
			/**
			 * This event is emitted when there is at least one mira.motion object in Max.
			 * @event State.motion_enabled
			 */
			this.emit("motion_enabled");
		}
	}

	/**
	 * @private
	 */
	_getMotion(id) {
		return this._motionNodes.get(id) || null;
	}

	/**
	 * @private
	 */
	_removeMotion(node) {
		this._motionNodes.delete(node.id);
		if (this._motionNodes.size === 0) {
			/**
			 * This event is emitted when the last mira.motion object is removed from Max. This event is not emitted when
			 * xebra first connects to Max, and there are no mira.motion objects in Max.
			 * @event State.motion_disabled
			 */
			this.emit("motion_disabled");
		}
	}

	/**
	 * @private
	 */
	_addPatcher(node) {
		this._patchers.set(node.id, node);
	}

	/**
	 * @private
	 */
	_getPatcher(id) {
		return this._patchers.get(id) || null;
	}

	/**
	 * @private
	 */
	_removePatcher(node) {
		this._patchers.delete(node.id);
	}

	/**
	 * @private
	 *
	 * @listens ObjectNode.param_changed
	 * @listens ObjectNode#param_set
	 * @fires State.frame_added
	 * @fires State.object_added
	 * @fires State.patcher_added
	 */
	_addNode = (data) => {

		const node = getInstanceForObjectType(data.id, data.type, data.sequence, data.parent_id);

		// patchers and frames are handled differently as we have to put them into the correct
		// list other than just adding them to the statetree.
		if (node.type === OBJECTS.PATCHER) {
			this._addPatcher(node);

			/**
			 * This event is emitted when a patcher is added in Max.
			 * @event State.patcher_added
			 * @param {PatcherNode} object The added patcher
			 */
			if (node.isReady) {
				this.emit("patcher_added", node);
			} else {
				node.once("initialized", this._onPatcherInitialized);
			}

		} else if (data.type === OBJECTS.MIRA_FRAME) {
			const parentPatcher = this._getPatcher(data.parent_id);
			parentPatcher.addFrame(node);

			/**
			 * This event is emitted when a frame is added in Max.
			 * @event State.frame_added
			 * @param {FrameNode} object The added frame
			 */
			if (node.isReady) {
				this.emit("frame_added", node);
			} else {
				node.once("initialized", this._onFrameInitialized);
			}

		} else { // object node
			const parentPatcher = this._getPatcher(data.parent_id);
			parentPatcher.addObject(node);

			if (node.type === OBJECTS.MIRA_MOTION) this._addMotion(node);
		}

		this._doInsertNode(node);

		/**
		 * This event is emitted when an object is added in Max.
		 * @event State.object_added
		 * @param {ObjectNode} object The added object
		 */
		if (node.isReady) {
			this.emit("object_added", node);
		} else {
			node.once("initialized", this._onNodeInitialized);
		}
	}

	/**
	 * @private
	 */
	_doInsertNode(node) {
		this._state.set(node.id, node);
		node.on("param_changed", this._onNodeChange);
		node.on("param_set", this._onModifiyNodeChange);
		if (node.resourceController) node.resourceController.on("get_resource_info", this._onGetResourceInfo);
	}

	/**
	 * @private
	 */
	_addParam = (data) => {
		const parent = this._state.get(data.parent_id);
		const param = new ParamNode(data.id, data.type, data.sequence);

		this._state.set(param.id, param);

		parent.addParam(param);
	}

	/**
	 * @private
	 */
	_channelMessage = (channel, message) => {
		/**
		 * This event is emitted when a message is sent to a mira.channel object
		 * @event State.channel_message_received
		 * @param {String} channel The name of the channel where the message was received
		 * @param {Number|String|Array<Number|String>|Object} message The message received from Max
		 */
		this.emit("channel_message_received", channel, message);
	}

	/**
	 * @private
	 */
	_clientParamChange = (key, value) => {
		/**
		 * Client param change event
		 * @private
		 * @event State#client_param_changed
		 * @param {String} key
		 * @param {String} value
		 */
		this.emit("client_param_changed", key, value);
	}

	/**
	 * @private
	 * @fires State.frame_removed
	 * @fires State.object_removed
	 * @fires State.patcher_removed
	 */
	_deleteNode = (data) => {
		const node = this._state.get(data.id);
		if (!node) return;

		const parentPatcher = this._getPatcher(node.patcherId);

		// remove frame from parent patcher
		if (node.type === OBJECTS.MIRA_FRAME) {
			if (parentPatcher) parentPatcher.removeFrame(node.id);

			/**
			 * This event is emitted when a frame is removed from Max.
			 * @event State.frame_removed
			 * @param {FrameNode} object The removed frame
			 */
			if (node.isReady) this.emit("frame_removed", node);
		} else if (node.type === OBJECTS.PATCHER) {

			/**
			 * This event is emitted when a patcher is removed from Max.
			 * @event State.patcher_removed
			 * @param {PatcherNode} object The removed patcher
			 */
			if (node.isReady) this.emit("patcher_removed", node);
		} else {
			if (parentPatcher) parentPatcher.removeObject(node.id);
		}

		if (node.type === OBJECTS.MIRA_MOTION) this._removeMotion(node);

		this._destroyNode(node);

		/**
		 * This event is emitted when an object is removed from Max.
		 * @event State.object_removed
		 * @param {ObjectNode} object The removed object
		 */
		if (node.isReady) this.emit("object_removed", node);
	}

	_destroyNode(node) {
		node.destroy();

		node.forEachChild((child) => {
			if (child instanceof ParamNode) this._destroyNode(child);
		}, this);

		this._state.delete(node.id);
	}

	/**
	 * private
	 */

	_handleResourceData = (data) => {
		if (data.request) {
			const sequence = data.request.sequence;
			const resource = this._resourceRequests.data.sequenceToResource[sequence];
			if (resource) {
				resource.handleData(data);
				delete this._resourceRequests.data.resourceToSequence[resource.id];
				delete this._resourceRequests.data.sequenceToResource[sequence];
			}

		}
	}

	_handleResourceInfo = (data) => {
		if (data.request) {
			const sequence = data.request.sequence;
			const resource = this._resourceRequests.info.sequenceToResource[sequence];
			if (resource) {
				this._makeResourceRequest(data.request.context, resource, "data");
				delete this._resourceRequests.info.resourceToSequence[resource.id];
				delete this._resourceRequests.info.sequenceToResource[sequence];
			}
		} else {
			console.log("Could not handle badly formatted resource info response", data);
		}
	}

	/**
	 * @private
	 */
	_modifyNode = (data) => {
		const node = this._state.get(data.id);
		if (node) node.modify(data.values, data.types, data.sequence);
	}

	/**
	 * @private
	 */
	_statedump = (data) => {
		/**
		 * This event is emitted when the web socket connection is persistently interrupted to the point that the xebra
		 * state and Max state fall out of sync. In this case, xebra will attempt to reset and rebuild the state, which
		 * fires this event. This should happen very infrequently. A state#loaded event will fire when this event fires.
		 * @event State.reset
		 */
		if (this._state) {
			this.emit("reset");
		}

		this._resetState();

		for (let i = 0, il = data.messages.length; i < il; i++) {
			const msg = data.messages[i];
			if (msg.message === XebraCommunicator.XEBRA_MESSAGES.ADD_NODE) {
				this._addNode(msg.payload);
			} else if (msg.message === XebraCommunicator.XEBRA_MESSAGES.ADD_PARAM) {
				this._addParam(msg.payload);
			} else if (msg.message === XebraCommunicator.XEBRA_MESSAGES.MODIFY_NODE) {
				this._modifyNode(msg.payload, true);
			}
		}

		/**
		 * This event is emitted when the entire Max state has been loaded. At this point, all `frame_added`,
		 * `object_added`, and `patcher_added` events will have fired, and all of their parameters will have been
		 * loaded. This is analogous to $(document).ready() in jQuery.
		 * @event State.loaded
		 */
		this._isStateLoaded = true;
		this.emit("loaded");
	}

	/**
	 * @private
	 */
	_resetState() {
		// destroy all old nodes
		if (this._state) {
			this._state.forEach((node) => {
				node.destroy();
			});
			this._state.clear();
		}

		this._isStateLoaded = false;
		this._state = new Map();
		this._patchers = new Map();

		// reset motion
		this._motionNodes = new Map();
		this.emit("motion_disabled");

		this._rootNode = new ObjectNode(0, "root");
		this._doInsertNode(this._rootNode);
	}

	/**
	 * Closes the Xebra connection and resets the state.
	 */
	close() {
		this._communicator.close();
		this._resetState();
	}

	/**
	 * Connects to the Xebra server. If `auto_connect : true` is passed to State on.
	 */
	connect() {
		this._communicator.connect();
	}

	/**
	 * Create a {@link Resource}, which can be used to retrieve image data from the Max search path.
	 * @return {Resource}
	 */
	createResource() {
		return this._resourceController.createResource();
	}

	/**
	 * Send an arbitrary message to the named channel. The type of the message will be coerced to
	 * a Max type in the Max application by mira.channel
	 * @param {String} channel - The name of the mira.channel objects that should receive this message
	 * @param {Number|String|Array<Number|String>|Object} message - the message to send
	 */
	sendMessageToChannel(channel, message) {
		this._communicator.sendChannelMessage(channel, message);
	}

	/**
	 * Send mira.motion updates to parameters on the root node.
	 * @see Xebra.MOTION_TYPES
	 * @param {string} motionType - The type of motion
	 * @param {number} motionX
	 * @param {number} motionY
	 * @param {number} motionZ
	 * @param {number} timestamp
	 * @throws Will throw an error when motion is currently disabled on the instance of State.
	 */
	sendMotionData(motionType, motionX, motionY, motionZ, timestamp) {
		const xuuid = this.xebraUuid;
		if (!xuuid) return;

		if (!this.isMotionEnabled) throw new Error("Can't send motion data when motion is disabled");

		this._rootNode.setParamValue(motionType, [
			xuuid,
			xuuid,
			motionX,
			motionY,
			motionZ,
			timestamp
		]);
	}

	/**
	 * Returns a list of the names of all mira.channel objects in all patchers
	 * @return {string[]}
	 */
	getChannelNames() {
		const names = new Set();
		this._patchers.forEach((patcher) => {
			patcher.getChannelNames().forEach((name) => {
				names.add(name);
			});
		});
		return Array.from(names);
	}

	/**
	 * Returns a list of available patchers.
	 * @return {PatcherNode[]}
	 */
	getPatchers() {
		return Array.from(this._patchers.values());
	}

	/**
	 * Returns a list of node objects with the given scripting name (the Max attribute 'varname').
	 * @return {ObjectNode[]}
	 */
	getObjectsByScriptingName(scriptingName) {
		const retVal = [];
		this._patchers.forEach((patcher, id) => {
			const obj = patcher.getObjectByScriptingName(scriptingName);
			if (obj) retVal.push(obj);
		});
		return retVal;
	}
	/**
		 * Returns the object speficied by the given id.
		 * @param {Xebra.NodeId} id - The id of the object
		 * @return {ObjectNode|null} the object or null if not known
		*/
	getObjectById(id) {
		const node = this._state.get(id);
		if (!node || !(node instanceof ObjectNode)) return null;
		return node;
	}

	/**
	 * Returns the patcher speficied by the given id.
	 * @param {Xebra.NodeId} id - The id of the patcher
	 * @return {PatcherNode|null} the patcher or null if not known
	*/
	getPatcherById(id) {
		return this._patchers.get(id) || null;
	}
}

export { State };

// constants

/**
 * Connection States
 * @static
 * @constant
 * @memberof Xebra
 * @type {object}
 * @property {number} INIT - The connection hasn't been set up yet, it's still waiting for a call to connect (unless
 *     auto_connect is set to true)
 * @property {number} CONNECTING - The connection is being established
 * @property {number} CONNECTED - The connection is established and alive
 * @property {number} CONNECTION_FAIL - The connection could NEVER be established
 * @property {number} RECONNECTING - The connection was lost and attempts to reconnect are made (based on reconnect,
 *     reconnect_attempts and reconnect_timeout options)
 * @property {number} DISCONNECTED - The connection was lost and all attempts to reconnect failed
 */
const CONNECTION_STATES = XebraCommunicator.CONNECTION_STATES;
const VERSION = XebraCommunicator.XEBRA_VERSION;

export * from "./lib/constants.js";
export {
	CONNECTION_STATES,
	SUPPORTED_OBJECTS,
	VERSION
};


text:
' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.

Imports System.Runtime.CompilerServices
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax

Namespace Microsoft.CodeAnalysis.VisualBasic.Extensions
    Partial Friend Module MemberAccessExpressionSyntaxExtensions
        <Extension()>
        Public Function IsConstructorInitializer(memberAccess As MemberAccessExpressionSyntax) As Boolean
            Return memberAccess.IsThisConstructorInitializer() OrElse memberAccess.IsBaseConstructorInitializer()
        End Function

        <Extension()>
        Public Function IsThisConstructorInitializer(memberAccess As MemberAccessExpressionSyntax) As Boolean
            If memberAccess IsNot Nothing Then
                If IsFirstStatementInConstructor(memberAccess) Then
                    If memberAccess.Expression.IsKind(SyntaxKind.MeExpression) OrElse
                       memberAccess.Expression.IsKind(SyntaxKind.MyClassExpression) Then
                        If memberAccess.Name.IsKind(SyntaxKind.IdentifierName) Then
                            Return memberAccess.Name.Identifier.HasMatchingText(SyntaxKind.NewKeyword)
                        End If
                    End If
                End If
            End If

            Return False
        End Function

        <Extension()>
        Public Function IsBaseConstructorInitializer(memberAccess As MemberAccessExpressionSyntax) As Boolean
            If memberAccess IsNot Nothing Then
                If IsFirstStatementInConstructor(memberAccess) Then
                    If memberAccess.Expression.IsKind(SyntaxKind.MyBaseExpression) Then
                        If memberAccess.Name.IsKind(SyntaxKind.IdentifierName) Then
                            Return memberAccess.Name.Identifier.HasMatchingText(SyntaxKind.NewKeyword)
                        End If
                    End If
                End If
            End If

            Return False
        End Function

        Private Function IsFirstStatementInConstructor(memberAccess As MemberAccessExpressionSyntax) As Boolean
            Dim isCall As Boolean
            Dim statement As SyntaxNode
            If TypeOf memberAccess.Parent Is InvocationExpressionSyntax Then
                statement = memberAccess.Parent.Parent
                isCall = statement IsNot Nothing AndAlso (statement.Kind = SyntaxKind.CallStatement OrElse statement.Kind = SyntaxKind.ExpressionStatement)
            Else
                statement = memberAccess.Parent
                isCall = statement.IsKind(SyntaxKind.CallStatement)
            End If

            If isCall Then
                Return statement.IsParentKind(SyntaxKind.ConstructorBlock) AndAlso
                    DirectCast(statement.Parent, ConstructorBlockSyntax).Statements.First() Is statement
            End If

            Return False
        End Function

        <Extension>
        Public Function GetExpressionOfMemberAccessExpression(
                memberAccessExpression As MemberAccessExpressionSyntax,
                Optional allowImplicitTarget As Boolean = False) As ExpressionSyntax
            If memberAccessExpression Is Nothing Then
                Return Nothing
            End If

            If memberAccessExpression.Expression IsNot Nothing Then
                Return memberAccessExpression.Expression
            End If

            ' we have a member access expression with a null expression, this may be one of the
            ' following forms:
            '
            ' 1) new With { .a = 1, .b = .a     <-- .a refers to the anonymous type
            ' 2) With obj : .m                  <-- .m refers to the obj type
            ' 3) new T() With { .a = 1, .b = .a <-- 'a refers to the T type

            If allowImplicitTarget Then
                Dim conditional = memberAccessExpression.GetRootConditionalAccessExpression()
                If conditional IsNot Nothing Then
                    If conditional.Expression Is Nothing Then

                        ' No expression, maybe we're in a with block
                        Dim withBlock = conditional.GetAncestor(Of WithBlockSyntax)()
                        If withBlock IsNot Nothing Then
                            Return withBlock.WithStatement.Expression
                        End If
                    End If

                    Return conditional.Expression
                End If

                Dim current As SyntaxNode = memberAccessExpression

                While current IsNot Nothing
                    If TypeOf current Is AnonymousObjectCreationExpressionSyntax Then
                        Return DirectCast(current, ExpressionSyntax)
                    ElseIf TypeOf current Is WithBlockSyntax Then
                        Dim withBlock = DirectCast(current, WithBlockSyntax)
                        If memberAccessExpression IsNot withBlock.WithStatement.Expression Then
                            Return withBlock.WithStatement.Expression
                        End If
                    ElseIf TypeOf current Is ObjectMemberInitializerSyntax AndAlso
                           TypeOf current.Parent Is ObjectCreationExpressionSyntax Then
                        Return DirectCast(current.Parent, ExpressionSyntax)
                    End If

                    current = current.Parent
                End While
            End If

            Return Nothing
        End Function
    End Module
End Namespace

redpajama_set_name: RedPajamaGithub


text:
package org.apache.cassandra.db;

import java.net.InetAddress;
import java.util.Collection;

import org.junit.AfterClass;
import org.junit.Test;

import org.apache.cassandra.SchemaLoader;
import org.apache.cassandra.Util;
import org.apache.cassandra.db.compaction.CompactionManager;
import org.apache.cassandra.dht.BytesToken;
import org.apache.cassandra.locator.TokenMetadata;
import org.apache.cassandra.service.CacheService;
import org.apache.cassandra.service.StorageService;
import org.apache.cassandra.utils.ByteBufferUtil;
import static org.junit.Assert.assertEquals;

public class RowCacheTest extends SchemaLoader
{
    private String KEYSPACE = "RowCacheSpace";
    private String COLUMN_FAMILY = "CachedCF";

    @AfterClass
    public static void cleanup()
    {
        cleanupSavedCaches();
    }

    @Test
    public void testRowCache() throws Exception
    {
        CompactionManager.instance.disableAutoCompaction();

        Keyspace keyspace = Keyspace.open(KEYSPACE);
        ColumnFamilyStore cachedStore  = keyspace.getColumnFamilyStore(COLUMN_FAMILY);

        // empty the row cache
        CacheService.instance.invalidateRowCache();

        // set global row cache size to 1 MB
        CacheService.instance.setRowCacheCapacityInMB(1);

        // inserting 100 rows into both column families
        insertData(KEYSPACE, COLUMN_FAMILY, 0, 100);

        // now reading rows one by one and checking if row change grows
        for (int i = 0; i < 100; i++)
        {
            DecoratedKey key = Util.dk("key" + i);

            cachedStore.getColumnFamily(key,
                                        ByteBufferUtil.EMPTY_BYTE_BUFFER,
                                        ByteBufferUtil.EMPTY_BYTE_BUFFER,
                                        false,
                                        1,
                                        System.currentTimeMillis());
            assert CacheService.instance.rowCache.size() == i + 1;
            assert cachedStore.containsCachedRow(key); // current key should be stored in the cache

            // checking if column is read correctly after cache
            ColumnFamily cf = cachedStore.getColumnFamily(key,
                                                          ByteBufferUtil.EMPTY_BYTE_BUFFER,
                                                          ByteBufferUtil.EMPTY_BYTE_BUFFER,
                                                          false,
                                                          1,
                                                          System.currentTimeMillis());
            Collection<Column> columns = cf.getSortedColumns();

            Column column = columns.iterator().next();

            assert columns.size() == 1;
            assert column.name().equals(ByteBufferUtil.bytes("col" + i));
            assert column.value().equals(ByteBufferUtil.bytes("val" + i));
        }

        // insert 10 more keys
        insertData(KEYSPACE, COLUMN_FAMILY, 100, 10);

        for (int i = 100; i < 110; i++)
        {
            DecoratedKey key = Util.dk("key" + i);

            cachedStore.getColumnFamily(key,
                                        ByteBufferUtil.EMPTY_BYTE_BUFFER,
                                        ByteBufferUtil.EMPTY_BYTE_BUFFER,
                                        false,
                                        1,
                                        System.currentTimeMillis());
            assert cachedStore.containsCachedRow(key); // cache should be populated with the latest rows read (old ones should be popped)

            // checking if column is read correctly after cache
            ColumnFamily cf = cachedStore.getColumnFamily(key,
                                                          ByteBufferUtil.EMPTY_BYTE_BUFFER,
                                                          ByteBufferUtil.EMPTY_BYTE_BUFFER,
                                                          false,
                                                          1,
                                                          System.currentTimeMillis());
            Collection<Column> columns = cf.getSortedColumns();

            Column column = columns.iterator().next();

            assert columns.size() == 1;
            assert column.name().equals(ByteBufferUtil.bytes("col" + i));
            assert column.value().equals(ByteBufferUtil.bytes("val" + i));
        }

        // clear 100 rows from the cache
        int keysLeft = 109;
        for (int i = 109; i >= 10; i--)
        {
            cachedStore.invalidateCachedRow(Util.dk("key" + i));
            assert CacheService.instance.rowCache.size() == keysLeft;
            keysLeft--;
        }

        CacheService.instance.setRowCacheCapacityInMB(0);
    }

    @Test
    public void testRowCacheLoad() throws Exception
    {
        CacheService.instance.setRowCacheCapacityInMB(1);
        rowCacheLoad(100, Integer.MAX_VALUE, 0);
        CacheService.instance.setRowCacheCapacityInMB(0);
    }

    @Test
    public void testRowCacheCleanup() throws Exception
    {
        StorageService.instance.initServer(0);
        CacheService.instance.setRowCacheCapacityInMB(1);
        rowCacheLoad(100, Integer.MAX_VALUE, 1000);

        ColumnFamilyStore store = Keyspace.open(KEYSPACE).getColumnFamilyStore(COLUMN_FAMILY);
        assertEquals(CacheService.instance.rowCache.getKeySet().size(), 100);
        store.cleanupCache();
        assertEquals(CacheService.instance.rowCache.getKeySet().size(), 100);
        TokenMetadata tmd = StorageService.instance.getTokenMetadata();
        byte[] tk1, tk2;
        tk1 = "key1000".getBytes();
        tk2 = "key1050".getBytes();
        tmd.updateNormalToken(new BytesToken(tk1), InetAddress.getByName("127.0.0.1"));
        tmd.updateNormalToken(new BytesToken(tk2), InetAddress.getByName("127.0.0.2"));
        store.cleanupCache();
        assertEquals(CacheService.instance.rowCache.getKeySet().size(), 50);
        CacheService.instance.setRowCacheCapacityInMB(0);
    }

    @Test
    public void testRowCachePartialLoad() throws Exception
    {
        CacheService.instance.setRowCacheCapacityInMB(1);
        rowCacheLoad(100, 50, 0);
        CacheService.instance.setRowCacheCapacityInMB(0);
    }

    public void rowCacheLoad(int totalKeys, int keysToSave, int offset) throws Exception
    {
        CompactionManager.instance.disableAutoCompaction();

        ColumnFamilyStore store = Keyspace.open(KEYSPACE).getColumnFamilyStore(COLUMN_FAMILY);

        // empty the cache
        CacheService.instance.invalidateRowCache();
        assert CacheService.instance.rowCache.size() == 0;

        // insert data and fill the cache
        insertData(KEYSPACE, COLUMN_FAMILY, offset, totalKeys);
        readData(KEYSPACE, COLUMN_FAMILY, offset, totalKeys);
        assert CacheService.instance.rowCache.size() == totalKeys;

        // force the cache to disk
        CacheService.instance.rowCache.submitWrite(keysToSave).get();

        // empty the cache again to make sure values came from disk
        CacheService.instance.invalidateRowCache();
        assert CacheService.instance.rowCache.size() == 0;
        assert CacheService.instance.rowCache.loadSaved(store) == (keysToSave == Integer.MAX_VALUE ? totalKeys : keysToSave);
    }
}


text:
 game.HeroDeathManager = Object.extend({
    init: function(x, y, settings) {

    },
    // this allows the Hero to respawn in the case of his death
    update: function() {
        if (game.data.player.dead) {
            me.game.world.removeChild(game.data.player);
            me.state.current().resetPlayer(10, 0);
        }

        return true;
    }
});


text:
Tic-tac-toe is played by two players `A` and `B` on a `3 x 3` grid.

Here are the rules of Tic-Tac-Toe:

- Players take turns placing characters into empty squares (" ").
- The first player A always places "X" characters, while the second player B always places "O" characters.
- "X" and "O" characters are always placed into empty squares, never on filled ones.
- The game ends when there are 3 of the same (non-empty) character filling any row, column, or diagonal.
- The game also ends if all squares are non-empty.
- No more moves can be played if the game is over.

Given an array moves where each element is another array of size 2 corresponding to the row and column of the grid where they mark their respective character in the order in which A and B play.

Return the winner of the game if it exists (A or B), in case the game ends in a draw return "Draw", if there are still movements to play return "Pending".

You can assume that moves is valid (It follows the rules of Tic-Tac-Toe), the grid is initially empty and A will play first.

### Example 1:

```
Input: moves = [[0,0],[2,0],[1,1],[2,1],[2,2]]
Output: "A"
Explanation: "A" wins, he always plays first.
"X  "    "X  "    "X  "    "X  "    "X  "
"   " -> "   " -> " X " -> " X " -> " X "
"   "    "O  "    "O  "    "OO "    "OOX"
```

### Example 2:

```
Input: moves = [[0,0],[1,1],[0,1],[0,2],[1,0],[2,0]]
Output: "B"
Explanation: "B" wins.
"X  "    "X  "    "XX "    "XXO"    "XXO"    "XXO"
"   " -> " O " -> " O " -> " O " -> "XO " -> "XO "
"   "    "   "    "   "    "   "    "   "    "O  "
```

### Example 3:

```
Input: moves = [[0,0],[1,1],[2,0],[1,0],[1,2],[2,1],[0,1],[0,2],[2,2]]
Output: "Draw"
Explanation: The game ends in a draw since there are no moves to make.
"XXO"
"OOX"
"XOX"
```

### Example 4:

```
Input: moves = [[0,0],[1,1]]
Output: "Pending"
Explanation: The game has not finished yet.
"X  "
" O "
"   "
```

### Constraints:

- `1 <= moves.length <= 9`
- `moves[i].length == 2`
- `0 <= moves[i][j] <= 2`
- There are no repeated elements on `moves`.
- `moves` follow the rules of tic tac toe.

## Solution

It has been reported that the question was asked in Amazon interview in a generic size n instead of 3.

#Array #Hash Table #Matrix #Simulation

#AMZN


text:
<resources>
    <string name="title_activity_settings">Settings</string>

    <!-- Strings related to Settings -->

    <string name="key_insurance_number">insuranceNumber</string>
    <string name="key_insurance_start_message">insuranceStartMessage</string>
    <string name="key_insurance_stop_message">insuranceStopMessage</string>
</resources>


text:
from twisted.trial import unittest
from twisted.protocols import loopback
from twisted.protocols import basic
from twisted.internet import protocol, abstract

import StringIO

class BufferingServer(protocol.Protocol):
    buffer = ''
    def dataReceived(self, data):
        self.buffer += data

class FileSendingClient(protocol.Protocol):
    def __init__(self, f):
        self.f = f

    def connectionMade(self):
        s = basic.FileSender()
        d = s.beginFileTransfer(self.f, self.transport, lambda x: x)
        d.addCallback(lambda r: self.transport.loseConnection())

class FileSenderTestCase(unittest.TestCase):
    def testSendingFile(self):
        testStr = 'xyz' * 100 + 'abc' * 100 + '123' * 100
        s = BufferingServer()
        c = FileSendingClient(StringIO.StringIO(testStr))

        d = loopback.loopbackTCP(s, c)
        d.addCallback(lambda x : self.assertEqual(s.buffer, testStr))
        return d

    def testSendingEmptyFile(self):
        fileSender = basic.FileSender()
        consumer = abstract.FileDescriptor()
        consumer.connected = 1
        emptyFile = StringIO.StringIO('')

        d = fileSender.beginFileTransfer(emptyFile, consumer, lambda x: x)

        # The producer will be immediately exhausted, and so immediately
        # unregistered
        self.assertEqual(consumer.producer, None)

        # Which means the Deferred from FileSender should have been called
        self.failUnless(d.called,
                        'producer unregistered with deferred being called')


text:
'use strict';

import {TPromise} from 'vs/base/common/winjs.base';
import {Registry} from 'vs/platform/platform';
import {isBinaryMime} from 'vs/base/common/mime';
import objects = require('vs/base/common/objects');
import {IEditorRegistry, Extensions} from 'vs/workbench/browser/parts/editor/baseEditor';
import {EditorModel, EditorInput} from 'vs/workbench/common/editor';
import {TextResourceEditorModel, BinaryResourceEditorModel} from 'vs/workbench/browser/parts/editor/resourceEditorModel';
import URI from 'vs/base/common/uri';
import {IInstantiationService} from 'vs/platform/instantiation/common/instantiation';

const TEXT_EDITOR_ID = 'workbench.editors.stringEditor';
const BINARY_EDITOR_ID = 'workbench.editors.binaryResourceEditor';

/**
 * A read-only editor input whos contents are just a mime and url to display either in a text editor or in a binary viewer. The
 * decision of using a binary or text editor is made by checking the provided mime type for common textual and binary mime types
 * (image, audio, video, application/octet-stream).
 */
export class ResourceEditorInput extends EditorInput {

	public static ID: string = 'workbench.editors.resourceEditorInput';

	private name: string;
	private description: string;
	private url: string;
	private mime: string;
	private method: string;
	private headers: any;
	private isMimeEnforced: boolean;
	private singleton: boolean;
	private cachedModel: EditorModel;

	constructor(
		name: string,
		description: string,
		url: string,
		mime: string,
		method: string,
		headers: any,
		singleton: boolean,
		@IInstantiationService private instantiationService: IInstantiationService
	) {
		super();

		this.name = name;
		this.description = description;
		this.url = url;
		this.mime = mime;
		this.method = method;
		this.headers = headers;
		this.singleton = singleton;
	}

	public getId(): string {
		return ResourceEditorInput.ID;
	}

	public getName(): string {
		return this.name;
	}

	public getDescription(): string {
		return this.description;
	}

	public getUrl(): string {
		return this.url;
	}

	public getMethod(): string {
		return this.method;
	}

	public getHeaders(): any {
		return this.headers;
	}

	public getMime(): string {
		return this.mime;
	}

	/**
	 * Will cause this editor input and the associated model to use the mime that was given in to the constructor and will
	 * ignore any mime that is returned from downloading the resource from the net. This is useful to enforce a certain mime
	 * to be used for this resource even though it might be served differently.
	 */
	public setMimeEnforced(): void {
		this.isMimeEnforced = true;
	}

	protected getResource(): URI {
		// Subclasses can implement to associate a resource URL with the input
		return null;
	}

	public getPreferredEditorId(candidates: string[]): string {

		// Find the right editor for the given isBinary/isText state
		let isBinary = isBinaryMime(this.mime);

		return !isBinary ? TEXT_EDITOR_ID : BINARY_EDITOR_ID;
	}

	public resolve(refresh?: boolean): TPromise<EditorModel> {
		let modelPromise: TPromise<EditorModel>;

		// Use Cached Model
		if (this.cachedModel && !refresh) {
			modelPromise = TPromise.as<EditorModel>(this.cachedModel);
		}

		// Refresh Cached Model
		else if (this.cachedModel && refresh) {
			modelPromise = this.cachedModel.load();
		}

		// Create Model and Load
		else {
			modelPromise = this.createModel().load();
		}

		return modelPromise.then((resolvedModel: EditorModel) => {
			this.cachedModel = resolvedModel;

			return this.cachedModel;
		});
	}

	private createModel(): EditorModel {
		let descriptor = (<IEditorRegistry>Registry.as(Extensions.Editors)).getEditor(this);
		if (!descriptor) {
			throw new Error('Unable to find an editor in the registry for this input.');
		}

		// Binary model if editor is binary editor
		let model: EditorModel;
		if (descriptor.getId() === BINARY_EDITOR_ID) {
			model = new BinaryResourceEditorModel(this.name, this.url);
		}

		// Otherwise use text model
		else {
			model = this.instantiationService.createInstance(TextResourceEditorModel, this.url, this.mime, this.method, this.headers, this.getResource());
			if (this.isMimeEnforced) {
				(<TextResourceEditorModel>model).setMimeEnforced();
			}
		}

		return model;
	}

	public matches(otherInput: any): boolean {
		if (super.matches(otherInput) === true) {
			return true;
		}

		if (otherInput instanceof ResourceEditorInput) {
			let otherResourceEditorInput = <ResourceEditorInput>otherInput;

			// If both inputs are singletons, check on the mime for equalness
			if (otherResourceEditorInput.singleton && this.singleton && otherResourceEditorInput.mime === this.mime) {
				return true;
			}

			// Otherwise compare by properties
			return otherResourceEditorInput.url === this.url &&
				otherResourceEditorInput.mime === this.mime &&
				otherResourceEditorInput.name === this.name &&
				otherResourceEditorInput.description === this.description &&
				otherResourceEditorInput.method === this.method &&
				objects.equals(otherResourceEditorInput.headers, this.headers);
		}

		return false;
	}

	public dispose(): void {
		if (this.cachedModel) {
			this.cachedModel.dispose();
			this.cachedModel = null;
		}

		super.dispose();
	}
}


text:
require 'beaker-puppet'
require 'beaker-pe'
require 'spec_helper_acceptance'

describe 'basic tests:' do
  it 'make sure we have copied the module across' do
    # No point diagnosing any more if the module wasn't copied properly
    shell('ls /etc/puppetlabs/code/modules/puppetdb') do |r|
      r.exit_code.should be_zero
      r.stdout.should =~ %r{metadata\.json}
      r.stderr.should == ''
    end
  end

  describe 'single node setup' do
    pp = <<-EOS
      # Single node setup
      class { 'puppetdb': disable_ssl => true, } ->
      class { 'puppetdb::master::config': puppetdb_port => '8080', puppetdb_server => 'localhost' }
    EOS

    it 'make sure it runs without error' do
      apply_manifest(pp, catch_errors: true)
      apply_manifest(pp, catch_changes: true)
    end
  end

  describe 'single node with ssl' do
    ssl_config = <<-EOS
      class { 'puppetdb': postgresql_ssl_on => true,
               database_listen_address => '0.0.0.0',
               database_host => $facts['fqdn'],}
    EOS

    it 'make sure it runs without error' do
      apply_manifest(ssl_config, catch_errors: true)
      apply_manifest(ssl_config, catch_changes: true)
    end

    change_password = <<-EOS
      ini_setting { "puppetdb password":
        ensure  => present,
        path    => '/etc/puppetlabs/puppetdb/conf.d/database.ini',
        section => 'database',
        setting => 'password',
        value   => 'random_password',
        notify  => Service[puppetdb]
      }

      service { 'puppetdb':
        ensure => 'running',
      }
    EOS
    it 'make sure it starts with wrong password' do
      apply_manifest(change_password, catch_errors: true)
      apply_manifest(change_password, catch_changes: true)
    end
  end

  describe 'enabling report processor' do
    pp = <<-EOS
      class { 'puppetdb': disable_ssl => true, } ->
      class { 'puppetdb::master::config':
        puppetdb_port => '8080',
        manage_report_processor => true,
        enable_reports => true,
        puppetdb_server => 'localhost'
      }
    EOS

    it 'adds the puppetdb report processor to puppet.conf' do
      apply_manifest(pp, catch_errors: true)
      apply_manifest(pp, catch_changes: true)

      shell('cat /etc/puppetlabs/puppet/puppet.conf') do |r|
        expect(r.stdout).to match(%r{^reports\s*=\s*([^,]+,)*puppetdb(,[^,]+)*$})
      end
    end
  end

  describe 'read only user' do
    pp = <<-EOS
      class { 'puppetdb': disable_ssl => true, } ->
      class { 'puppetdb::master::config':
        puppetdb_port => '8080',
        puppetdb_server => 'localhost'
      }
    EOS

    it 'can not create tables' do
      apply_manifest(pp, catch_errors: true)
      apply_manifest(pp, catch_changes: true)

      shell('psql "postgresql://puppetdb-read:puppetdb-read@localhost/puppetdb" -c "create table tables(id int)" || true') do |r|
        expect(r.stderr).to match(%r{^ERROR:  permission denied for schema public.*})
      end
    end
  end
end


text:
Sprint 2 Planning Meeting
-------------------------

**Rob was absent, so the team elected Jen as the interim PO**

**Sprint Goals:**

- Research of a private message/ticketing/support systems
- Select a support system to implement based on evaluation criteria
- Create a paper prototype of the integrated support system once selected
- Make remaining technical decisions and initialize installation of system once the support system is selected
- Progress to the point of getting something that users can review by sprint 3
- Get github training for those who need it

**Assumptions:**
We assume that caseworkers will be overwhelmed by realtime communications (like txting) and choose to focus our evaluation on delayed "inbox" style messaging. We will confirm this assumption with caseworker interviews.

**Further plans:**

 - See Waffle for specific tickets. Waffle is open to other ticket additions. Please do so!
 - We will run all of these decisions/goals and any work in progress by Rob on Monday to confirm we're on the right track.

**Associated user stories (in order of importance):**

 - As a foster parent I would like to private message my case worker, and indicate the priority / urgency of the message.
 - As a foster parent I would like to be able to archive messages so that I have a paper trail in case I need to go to court.
 - As a foster parent I want my profile and facility lookup experience to be seamlessly integrated with my messaging experience.
 - Additional stories were captured at bottom of
 https://docs.google.com/document/d/1csq4ndL_YuYmlKHHJobWSGa3fFQEfRrcgWmAek61E0w/edit


text:
package idv.chatea.gldemo;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.opengl.GLES20;
import android.opengl.GLSurfaceView;
import android.opengl.Matrix;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

import idv.chatea.gldemo.gles20.RectangleTexture;

public class GLES2_Texture_Activity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        GLSurfaceView glSurfaceView = new GLSurfaceView(this);
        glSurfaceView.setEGLContextClientVersion(2);
        glSurfaceView.setRenderer(new MyRenderer());
        glSurfaceView.setRenderMode(GLSurfaceView.RENDERMODE_CONTINUOUSLY);
        setContentView(glSurfaceView);
    }

    private class MyRenderer implements GLSurfaceView.Renderer {
        private float[] mProjectMatrix = new float[16];
        private float[] mViewMatrix = new float[16];

        private RectangleTexture mTexture;

        @Override
        public void onSurfaceCreated(GL10 unused, EGLConfig config) {
            GLES20.glClearColor(0.4f, 0.4f, 0.4f, 1.0f);

            Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.android_logo);
            mTexture = new RectangleTexture(bitmap);
            bitmap.recycle();
        }

        @Override
        public void onSurfaceChanged(GL10 unused, int width, int height) {
            GLES20.glViewport(0, 0, width, height);

            float ratio = (float) width / height;
            Matrix.frustumM(mProjectMatrix, 0, -ratio, ratio, -1, 1, 1.5f, 10);
        }

        @Override
        public void onDrawFrame(GL10 unused) {
            GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);

            Matrix.setLookAtM(mViewMatrix, 0,
                    0f, 0f, 2f,
                    0f, 0f, 0f,
                    0f, 1f, 0);

            float[] mvpMatrix = new float[16];
            Matrix.multiplyMM(mvpMatrix, 0, mProjectMatrix, 0, mViewMatrix, 0);

            float[] moduleMatrix = new float[16];
            Matrix.setIdentityM(moduleMatrix, 0);

            Matrix.multiplyMM(mvpMatrix, 0, mvpMatrix, 0, moduleMatrix, 0);

            mTexture.draw(mvpMatrix);
        }
    }
}


text:
package net.firejack.platform.service.content.broker.collection;

import net.firejack.platform.api.content.domain.Collection;
import net.firejack.platform.api.registry.domain.RegistryNodeTree;
import net.firejack.platform.core.broker.OPFSaveBroker;
import net.firejack.platform.core.model.registry.resource.CollectionMemberModel;
import net.firejack.platform.core.model.registry.resource.CollectionModel;
import net.firejack.platform.core.store.registry.resource.ICollectionStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import java.util.List;

public abstract class SaveCollectionBroker
        extends OPFSaveBroker<CollectionModel, Collection, RegistryNodeTree> {

    @Autowired
    @Qualifier("collectionStore")
    private ICollectionStore collectionStore;

    @Override
    protected CollectionModel convertToEntity(Collection collection) {
        return factory.convertFrom(CollectionModel.class, collection);
    }

    @Override
    protected RegistryNodeTree convertToModel(CollectionModel entity) {
        return factory.convertTo(RegistryNodeTree.class, entity);
    }

    @Override
    protected void save(CollectionModel collectionModel) throws Exception {
        List<CollectionMemberModel> collectionMemberModels = collectionModel.getCollectionMembers();
        if (collectionMemberModels != null) {
            int pos = 0;
            for (CollectionMemberModel collectionMemberModel : collectionMemberModels) {
                collectionMemberModel.setCollection(collectionModel);
                collectionMemberModel.setOrder(pos);
                pos++;
            }
        }
        collectionStore.save(collectionModel);
    }

}


text:
module Pavlov
  class AccessDenied < StandardError
  end
end


text:
<?php

namespace HanischIt\KrakenApi\Call\QueryLedgers;

use HanischIt\KrakenApi\Call\Shared\Model\LedgerInfoModel;
use HanischIt\KrakenApi\Model\ResponseInterface;

/**
 * Class QueryLedgersResponse
 * @package HanischIt\KrakenApi\Call\QueryLedgers
 */
class QueryLedgersResponse implements ResponseInterface
{
    /**
     * @var LedgerInfoModel[]
     */
    private $ledgerInfos;

    /**
     * @param array $result
     */
    public function manualMapping($result)
    {
        foreach ($result as $ledgerId => $ledger) {
            $this->ledgerInfos[] = new LedgerInfoModel(
                $ledgerId,
                $ledger['refid'],
                $ledger['time'],
                $ledger['type'],
                $ledger['aclass'],
                $ledger['asset'],
                $ledger['amount'],
                $ledger['fee'],
                $ledger['balance']
            );
        }
    }

    /**
     * @return LedgerInfoModel[]
     */
    public function getLedgerInfos()
    {
        return $this->ledgerInfos;
    }

}


text:
[![Build Status](https://travis-ci.org/rjackson/broccoli-file-mover.svg?branch=master)](https://travis-ci.org/rjackson/broccoli-file-mover)

## Installation

```bash
npm install --save-dev broccoli-file-mover
```

## Usage

Moving a single file from `app/main` to `app`:

```javascript
var moveFile = require('broccoli-file-mover');

var tree = moveFile('app', {
  srcFile: 'app/main.js',
  destFile: '/app.js'
});
```

Moving `app/main` to `app` and `test/main` to `test`:

```javacript
var moveFile = require('broccoli-file-mover');

var tree = moveFile('app', {
  files: {
    'app/main.js': 'app.js',
    'test/main.js': 'test.js'
  }
});
```

## Documentation

### `moveFile(inputTree, options)`

---

`options.srcFile` *{String}*

The path of the file to move (starting location).

---

`options.destFile` *{String}*

The path to move the file to (final location).

---

`options.copy` *{true,false}*

Should the file be copied?

 - If `copy` is `true`, then the source file is left in the tree (this might be useful to output both a non-minified and minified version).
 - If `copy` is `false`, then the source file is removed after it has been copied (essentially making this a `move` operation).

---

`options.duplicate` *{true,false}*

Should the source full contents of the input tree be duplicated into the returned tree?

 - If `true`, then the contents of the input tree is copied over into the new tree.
 - If `false`, then only the files being moved are worked on.

---

`options.files` *{Array|Object}*

This allows specifying more than one move/copy operation at a time (and reduced the total number of trees/steps
needed if you need to move many files).

 - If `files` is an object the key is used as the source path, and the value is the destination path.
 - If `files` is an array each item must be an object with a `srcFile` and `destFile` property. If `copy` is present it will
   be used also.

## ZOMG!!! TESTS?!?!!?

I know, right?

Running the tests:

```javascript
npm install
npm test
```

## License

This project is distributed under the MIT license.


text:
@interface ViewControllerWithManyUniqueStrings ()

@end

@implementation ViewControllerWithManyUniqueStrings

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do view setup here.
}

@end


text:
/* Licensed to PSF under a Contributor Agreement. */
/* See http://www.python.org/2.4/license for licensing details. */

/* TODO: handle unicode command lines? */
/* TODO: handle unicode environment? */

#include "Python.h"

#define WINDOWS_LEAN_AND_MEAN
#include "windows.h"

/* -------------------------------------------------------------------- */
/* handle wrapper.  note that this library uses integers when passing
   handles to a function, and handle wrappers when returning handles.
   the wrapper is used to provide Detach and Close methods */

typedef struct {
    PyObject_HEAD
    HANDLE handle;
} sp_handle_object;

staticforward PyTypeObject sp_handle_type;

static PyObject*
sp_handle_new(HANDLE handle)
{
    sp_handle_object* self;

    self = PyObject_NEW(sp_handle_object, &sp_handle_type);
    if (self == NULL)
        return NULL;

    self->handle = handle;

    return (PyObject*) self;
}

#if defined(MS_WIN32) && !defined(MS_WIN64)
#define HANDLE_TO_PYNUM(handle) PyInt_FromLong((long) handle)
#define PY_HANDLE_PARAM "l"
#else
#define HANDLE_TO_PYNUM(handle) PyLong_FromLongLong((long long) handle)
#define PY_HANDLE_PARAM "L"
#endif

static PyObject*
sp_handle_detach(sp_handle_object* self, PyObject* args)
{
    HANDLE handle;

    if (! PyArg_ParseTuple(args, ":Detach"))
        return NULL;

    handle = self->handle;

    self->handle = INVALID_HANDLE_VALUE;

    /* note: return the current handle, as an integer */
    return HANDLE_TO_PYNUM(handle);
}

static PyObject*
sp_handle_close(sp_handle_object* self, PyObject* args)
{
    if (! PyArg_ParseTuple(args, ":Close"))
        return NULL;

    if (self->handle != INVALID_HANDLE_VALUE) {
        CloseHandle(self->handle);
        self->handle = INVALID_HANDLE_VALUE;
    }
    Py_INCREF(Py_None);
    return Py_None;
}

static void
sp_handle_dealloc(sp_handle_object* self)
{
    if (self->handle != INVALID_HANDLE_VALUE)
        CloseHandle(self->handle);
    PyObject_FREE(self);
}

static PyMethodDef sp_handle_methods[] = {
    {"Detach", (PyCFunction) sp_handle_detach, METH_VARARGS},
    {"Close",  (PyCFunction) sp_handle_close,  METH_VARARGS},
    {NULL, NULL}
};

static PyObject*
sp_handle_getattr(sp_handle_object* self, char* name)
{
    return Py_FindMethod(sp_handle_methods, (PyObject*) self, name);
}

static PyObject*
sp_handle_as_int(sp_handle_object* self)
{
    return HANDLE_TO_PYNUM(self->handle);
}

static PyNumberMethods sp_handle_as_number;

statichere PyTypeObject sp_handle_type = {
    PyObject_HEAD_INIT(NULL)
    0,                                  /*ob_size*/
    "_subprocess_handle", sizeof(sp_handle_object), 0,
    (destructor) sp_handle_dealloc, /*tp_dealloc*/
    0, /*tp_print*/
    (getattrfunc) sp_handle_getattr,/*tp_getattr*/
    0,                                  /*tp_setattr*/
    0,                                  /*tp_compare*/
    0,                                  /*tp_repr*/
    &sp_handle_as_number,               /*tp_as_number */
    0,                                  /*tp_as_sequence */
    0,                                  /*tp_as_mapping */
    0                                   /*tp_hash*/
};

/* -------------------------------------------------------------------- */
/* windows API functions */

PyDoc_STRVAR(GetStdHandle_doc,
"GetStdHandle(handle) -> integer\n\
\n\
Return a handle to the specified standard device\n\
(STD_INPUT_HANDLE, STD_OUTPUT_HANDLE, STD_ERROR_HANDLE).\n\
The integer associated with the handle object is returned.");

static PyObject *
sp_GetStdHandle(PyObject* self, PyObject* args)
{
    HANDLE handle;
    int std_handle;

    if (! PyArg_ParseTuple(args, "i:GetStdHandle", &std_handle))
        return NULL;

    Py_BEGIN_ALLOW_THREADS
    handle = GetStdHandle((DWORD) std_handle);
    Py_END_ALLOW_THREADS

    if (handle == INVALID_HANDLE_VALUE)
        return PyErr_SetFromWindowsErr(GetLastError());

    if (! handle) {
        Py_INCREF(Py_None);
        return Py_None;
    }

    /* note: returns integer, not handle object */
    return HANDLE_TO_PYNUM(handle);
}

PyDoc_STRVAR(GetCurrentProcess_doc,
"GetCurrentProcess() -> handle\n\
\n\
Return a handle object for the current process.");

static PyObject *
sp_GetCurrentProcess(PyObject* self, PyObject* args)
{
    if (! PyArg_ParseTuple(args, ":GetCurrentProcess"))
        return NULL;

    return sp_handle_new(GetCurrentProcess());
}

PyDoc_STRVAR(DuplicateHandle_doc,
"DuplicateHandle(source_proc_handle, source_handle,\n\
                 target_proc_handle, target_handle, access,\n\
                 inherit[, options]) -> handle\n\
\n\
Return a duplicate handle object.\n\
\n\
The duplicate handle refers to the same object as the original\n\
handle. Therefore, any changes to the object are reflected\n\
through both handles.");

static PyObject *
sp_DuplicateHandle(PyObject* self, PyObject* args)
{
    HANDLE target_handle;
    BOOL result;

    HANDLE source_process_handle;
    HANDLE source_handle;
    HANDLE target_process_handle;
    int desired_access;
    int inherit_handle;
    int options = 0;

    if (! PyArg_ParseTuple(args,
                           PY_HANDLE_PARAM PY_HANDLE_PARAM PY_HANDLE_PARAM
                           "ii|i:DuplicateHandle",
                           &source_process_handle,
                           &source_handle,
                           &target_process_handle,
                           &desired_access,
                           &inherit_handle,
                           &options))
        return NULL;

    Py_BEGIN_ALLOW_THREADS
    result = DuplicateHandle(
        source_process_handle,
        source_handle,
        target_process_handle,
        &target_handle,
        desired_access,
        inherit_handle,
        options
    );
    Py_END_ALLOW_THREADS

    if (! result)
        return PyErr_SetFromWindowsErr(GetLastError());

    return sp_handle_new(target_handle);
}

PyDoc_STRVAR(CreatePipe_doc,
"CreatePipe(pipe_attrs, size) -> (read_handle, write_handle)\n\
\n\
Create an anonymous pipe, and return handles to the read and\n\
write ends of the pipe.\n\
\n\
pipe_attrs is ignored internally and can be None.");

static PyObject *
sp_CreatePipe(PyObject* self, PyObject* args)
{
    HANDLE read_pipe;
    HANDLE write_pipe;
    BOOL result;

    PyObject* pipe_attributes; /* ignored */
    int size;

    if (! PyArg_ParseTuple(args, "Oi:CreatePipe", &pipe_attributes, &size))
        return NULL;

    Py_BEGIN_ALLOW_THREADS
    result = CreatePipe(&read_pipe, &write_pipe, NULL, size);
    Py_END_ALLOW_THREADS

    if (! result)
        return PyErr_SetFromWindowsErr(GetLastError());

    return Py_BuildValue(
        "NN", sp_handle_new(read_pipe), sp_handle_new(write_pipe));
}

/* helpers for createprocess */

static int
getint(PyObject* obj, char* name)
{
    PyObject* value;
    int ret;

    value = PyObject_GetAttrString(obj, name);
    if (! value) {
        PyErr_Clear(); /* FIXME: propagate error? */
        return 0;
    }
    ret = (int) PyInt_AsLong(value);
    Py_DECREF(value);
    return ret;
}

static HANDLE
gethandle(PyObject* obj, char* name)
{
    sp_handle_object* value;
    HANDLE ret;

    value = (sp_handle_object*) PyObject_GetAttrString(obj, name);
    if (! value) {
        PyErr_Clear(); /* FIXME: propagate error? */
        return NULL;
    }
    if (value->ob_type != &sp_handle_type)
        ret = NULL;
    else
        ret = value->handle;
    Py_DECREF(value);
    return ret;
}

static PyObject*
getenvironment(PyObject* environment)
{
    int i, envsize;
    PyObject* out = NULL;
    PyObject* keys;
    PyObject* values;
    char* p;

    /* convert environment dictionary to windows enviroment string */
    if (! PyMapping_Check(environment)) {
        PyErr_SetString(
            PyExc_TypeError, "environment must be dictionary or None");
        return NULL;
    }

    envsize = PyMapping_Length(environment);

    keys = PyMapping_Keys(environment);
    values = PyMapping_Values(environment);
    if (!keys || !values)
        goto error;

    out = PyString_FromStringAndSize(NULL, 2048);
    if (! out)
        goto error;

    p = PyString_AS_STRING(out);

    for (i = 0; i < envsize; i++) {
        int ksize, vsize, totalsize;
        PyObject* key = PyList_GET_ITEM(keys, i);
        PyObject* value = PyList_GET_ITEM(values, i);

        if (! PyString_Check(key) || ! PyString_Check(value)) {
            PyErr_SetString(PyExc_TypeError,
                "environment can only contain strings");
            goto error;
        }
        ksize = PyString_GET_SIZE(key);
        vsize = PyString_GET_SIZE(value);
        totalsize = (p - PyString_AS_STRING(out)) + ksize + 1 +
                                                     vsize + 1 + 1;
        if (totalsize > PyString_GET_SIZE(out)) {
            int offset = p - PyString_AS_STRING(out);
            _PyString_Resize(&out, totalsize + 1024);
            p = PyString_AS_STRING(out) + offset;
        }
        memcpy(p, PyString_AS_STRING(key), ksize);
        p += ksize;
        *p++ = '=';
        memcpy(p, PyString_AS_STRING(value), vsize);
        p += vsize;
        *p++ = '\0';
    }

    /* add trailing null byte */
    *p++ = '\0';
    _PyString_Resize(&out, p - PyString_AS_STRING(out));

    /* PyObject_Print(out, stdout, 0); */

    Py_XDECREF(keys);
    Py_XDECREF(values);

    return out;

 error:
    Py_XDECREF(out);
    Py_XDECREF(keys);
    Py_XDECREF(values);
    return NULL;
}

PyDoc_STRVAR(CreateProcess_doc,
"CreateProcess(app_name, cmd_line, proc_attrs, thread_attrs,\n\
               inherit, flags, env_mapping, curdir,\n\
               startup_info) -> (proc_handle, thread_handle,\n\
                                 pid, tid)\n\
\n\
Create a new process and its primary thread. The return\n\
value is a tuple of the process handle, thread handle,\n\
process ID, and thread ID.\n\
\n\
proc_attrs and thread_attrs are ignored internally and can be None.");

static PyObject *
sp_CreateProcess(PyObject* self, PyObject* args)
{
    BOOL result;
    PROCESS_INFORMATION pi;
    STARTUPINFO si;
    PyObject* environment;

    char* application_name;
    char* command_line;
    PyObject* process_attributes; /* ignored */
    PyObject* thread_attributes; /* ignored */
    int inherit_handles;
    int creation_flags;
    PyObject* env_mapping;
    char* current_directory;
    PyObject* startup_info;

    if (! PyArg_ParseTuple(args, "zzOOiiOzO:CreateProcess",
                           &application_name,
                           &command_line,
                           &process_attributes,
                           &thread_attributes,
                           &inherit_handles,
                           &creation_flags,
                           &env_mapping,
                           &current_directory,
                           &startup_info))
        return NULL;

    ZeroMemory(&si, sizeof(si));
    si.cb = sizeof(si);

    /* note: we only support a small subset of all SI attributes */
    si.dwFlags = getint(startup_info, "dwFlags");
    si.wShowWindow = getint(startup_info, "wShowWindow");
    si.hStdInput = gethandle(startup_info, "hStdInput");
    si.hStdOutput = gethandle(startup_info, "hStdOutput");
    si.hStdError = gethandle(startup_info, "hStdError");

    if (PyErr_Occurred())
        return NULL;

    if (env_mapping == Py_None)
        environment = NULL;
    else {
        environment = getenvironment(env_mapping);
        if (! environment)
            return NULL;
    }

    Py_BEGIN_ALLOW_THREADS
    result = CreateProcess(application_name,
                           command_line,
                           NULL,
                           NULL,
                           inherit_handles,
                           creation_flags,
                           environment ? PyString_AS_STRING(environment) : NULL,
                           current_directory,
                           &si,
                           &pi);
    Py_END_ALLOW_THREADS

    Py_XDECREF(environment);

    if (! result)
        return PyErr_SetFromWindowsErr(GetLastError());

    return Py_BuildValue("NNii",
                         sp_handle_new(pi.hProcess),
                         sp_handle_new(pi.hThread),
                         pi.dwProcessId,
                         pi.dwThreadId);
}

PyDoc_STRVAR(TerminateProcess_doc,
"TerminateProcess(handle, exit_code) -> None\n\
\n\
Terminate the specified process and all of its threads.");

static PyObject *
sp_TerminateProcess(PyObject* self, PyObject* args)
{
    BOOL result;

    HANDLE process;
    int exit_code;
    if (! PyArg_ParseTuple(args, PY_HANDLE_PARAM "i:TerminateProcess",
                           &process, &exit_code))
        return NULL;

    result = TerminateProcess(process, exit_code);

    if (! result)
        return PyErr_SetFromWindowsErr(GetLastError());

    Py_INCREF(Py_None);
    return Py_None;
}

PyDoc_STRVAR(GetExitCodeProcess_doc,
"GetExitCodeProcess(handle) -> Exit code\n\
\n\
Return the termination status of the specified process.");

static PyObject *
sp_GetExitCodeProcess(PyObject* self, PyObject* args)
{
    DWORD exit_code;
    BOOL result;

    HANDLE process;
    if (! PyArg_ParseTuple(args, PY_HANDLE_PARAM ":GetExitCodeProcess", &process))
        return NULL;

    result = GetExitCodeProcess(process, &exit_code);

    if (! result)
        return PyErr_SetFromWindowsErr(GetLastError());

    return PyInt_FromLong(exit_code);
}

PyDoc_STRVAR(WaitForSingleObject_doc,
"WaitForSingleObject(handle, timeout) -> result\n\
\n\
Wait until the specified object is in the signaled state or\n\
the time-out interval elapses. The timeout value is specified\n\
in milliseconds.");

static PyObject *
sp_WaitForSingleObject(PyObject* self, PyObject* args)
{
    DWORD result;

    HANDLE handle;
    int milliseconds;
    if (! PyArg_ParseTuple(args, PY_HANDLE_PARAM "i:WaitForSingleObject",
                                 &handle,
                                 &milliseconds))
        return NULL;

    Py_BEGIN_ALLOW_THREADS
    result = WaitForSingleObject(handle, (DWORD) milliseconds);
    Py_END_ALLOW_THREADS

    if (result == WAIT_FAILED)
        return PyErr_SetFromWindowsErr(GetLastError());

    return PyInt_FromLong((int) result);
}

PyDoc_STRVAR(GetVersion_doc,
"GetVersion() -> version\n\
\n\
Return the version number of the current operating system.");

static PyObject *
sp_GetVersion(PyObject* self, PyObject* args)
{
    if (! PyArg_ParseTuple(args, ":GetVersion"))
        return NULL;

    return PyInt_FromLong((int) GetVersion());
}

PyDoc_STRVAR(GetModuleFileName_doc,
"GetModuleFileName(module) -> path\n\
\n\
Return the fully-qualified path for the file that contains\n\
the specified module. The module must have been loaded by the\n\
current process.\n\
\n\
The module parameter should be a handle to the loaded module\n\
whose path is being requested. If this parameter is 0, \n\
GetModuleFileName retrieves the path of the executable file\n\
of the current process.");

static PyObject *
sp_GetModuleFileName(PyObject* self, PyObject* args)
{
    BOOL result;
    HMODULE module;
    TCHAR filename[MAX_PATH];

    if (! PyArg_ParseTuple(args, PY_HANDLE_PARAM ":GetModuleFileName",
                           &module))
        return NULL;

    result = GetModuleFileName(module, filename, MAX_PATH);
    filename[MAX_PATH-1] = '\0';

    if (! result)
        return PyErr_SetFromWindowsErr(GetLastError());

    return PyString_FromString(filename);
}

static PyMethodDef sp_functions[] = {
    {"GetStdHandle", sp_GetStdHandle, METH_VARARGS, GetStdHandle_doc},
    {"GetCurrentProcess", sp_GetCurrentProcess,         METH_VARARGS,
                                              GetCurrentProcess_doc},
    {"DuplicateHandle",         sp_DuplicateHandle,     METH_VARARGS,
                                            DuplicateHandle_doc},
    {"CreatePipe", sp_CreatePipe, METH_VARARGS, CreatePipe_doc},
    {"CreateProcess", sp_CreateProcess, METH_VARARGS, CreateProcess_doc},
    {"TerminateProcess", sp_TerminateProcess, METH_VARARGS,
                                             TerminateProcess_doc},
    {"GetExitCodeProcess", sp_GetExitCodeProcess, METH_VARARGS,
                                               GetExitCodeProcess_doc},
    {"WaitForSingleObject", sp_WaitForSingleObject, METH_VARARGS,
                                                    WaitForSingleObject_doc},
    {"GetVersion", sp_GetVersion, METH_VARARGS, GetVersion_doc},
    {"GetModuleFileName", sp_GetModuleFileName, METH_VARARGS,
                                              GetModuleFileName_doc},
    {NULL, NULL}
};

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

static void
defint(PyObject* d, const char* name, int value)
{
    PyObject* v = PyInt_FromLong((long) value);
    if (v) {
        PyDict_SetItemString(d, (char*) name, v);
        Py_DECREF(v);
    }
}

#if PY_VERSION_HEX >= 0x02030000
PyMODINIT_FUNC
#else
DL_EXPORT(void)
#endif
init_subprocess()
{
    PyObject *d;
    PyObject *m;

    /* patch up object descriptors */
    sp_handle_type.ob_type = &PyType_Type;
    sp_handle_as_number.nb_int = (unaryfunc) sp_handle_as_int;

    m = Py_InitModule("_subprocess", sp_functions);
    if (m == NULL)
        return;
    d = PyModule_GetDict(m);

    /* constants */
    defint(d, "STD_INPUT_HANDLE", STD_INPUT_HANDLE);
    defint(d, "STD_OUTPUT_HANDLE", STD_OUTPUT_HANDLE);
    defint(d, "STD_ERROR_HANDLE", STD_ERROR_HANDLE);
    defint(d, "DUPLICATE_SAME_ACCESS", DUPLICATE_SAME_ACCESS);
    defint(d, "STARTF_USESTDHANDLES", STARTF_USESTDHANDLES);
    defint(d, "STARTF_USESHOWWINDOW", STARTF_USESHOWWINDOW);
    defint(d, "SW_HIDE", SW_HIDE);
    defint(d, "INFINITE", INFINITE);
    defint(d, "WAIT_OBJECT_0", WAIT_OBJECT_0);
    defint(d, "CREATE_NEW_CONSOLE", CREATE_NEW_CONSOLE);
    defint(d, "CREATE_NEW_PROCESS_GROUP", CREATE_NEW_PROCESS_GROUP);
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.cyanogenmod</groupId>
    <artifactId>cm-cloud-generator</artifactId>
    <name>${project.artifactId}</name>
    <version>1.0</version>

    <dependencies>
        <dependency>
            <groupId>com.googlecode.lambdaj</groupId>
            <artifactId>lambdaj</artifactId>
            <version>2.3.3</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.4</version>
        </dependency>
        <dependency>
            <groupId>org.jsoup</groupId>
            <artifactId>jsoup</artifactId>
            <version>1.8.2</version>
        </dependency>
        <dependency>
            <groupId>org.codeartisans.thirdparties.swing</groupId>
            <artifactId>batik-all</artifactId>
            <version>1.8pre-r1084380</version>
        </dependency>
        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20131018</version>
        </dependency>

        <!-- nlp -->
        <!-- TODO remove from kumo core -->
        <dependency>
            <groupId>org.languagetool</groupId>
            <artifactId>language-en</artifactId>
            <version>2.5</version>
            <exclusions>
                <exclusion>
                    <artifactId>commons-logging</artifactId>
                    <groupId>commons-logging</groupId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.languagetool</groupId>
            <artifactId>language-zh</artifactId>
            <version>2.5</version>
            <exclusions>
                <exclusion>
                    <artifactId>commons-logging</artifactId>
                    <groupId>commons-logging</groupId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <prerequisites>
        <maven>3.3.0</maven>
    </prerequisites>

    <licenses>
        <license>
            <name>GNU General Public License, version 3 (GPL-3.0)</name>
            <distribution>repo</distribution>
            <url>http://opensource.org/licenses/GPL-3.0</url>
        </license>
    </licenses>

    <profiles>
        <profile>
            <id>release</id>
            <build>
                <plugins>
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-gpg-plugin</artifactId>
                        <version>1.6</version>
                        <executions>
                            <execution>
                                <id>sign-artifacts</id>
                                <phase>verify</phase>
                                <goals>
                                    <goal>sign</goal>
                                </goals>
                            </execution>
                        </executions>
                    </plugin>
                </plugins>
            </build>
        </profile>
    </profiles>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.2</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-source-plugin</artifactId>
                <version>2.4</version>
                <executions>
                    <execution>
                        <id>attach-sources</id>
                        <goals>
                            <goal>jar-no-fork</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-javadoc-plugin</artifactId>
                <version>2.10.2</version>
                <executions>
                    <execution>
                        <id>attach-javadocs</id>
                        <goals>
                            <goal>jar</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.sonatype.plugins</groupId>
                <artifactId>nexus-staging-maven-plugin</artifactId>
                <version>1.6.4</version>
                <extensions>true</extensions>
                <configuration>
                    <serverId>ossrh</serverId>
                    <nexusUrl>https://oss.sonatype.org/</nexusUrl>
                    <autoReleaseAfterClose>true</autoReleaseAfterClose>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
</project>


text:
package org.schoellerfamily.gedbrowser.datamodel;

import org.schoellerfamily.gedbrowser.datamodel.visitor.GedObjectVisitor;

/**
 * @author Dick Schoeller
 */
public final class SubmitterLink extends AbstractLink {
    /**
     * Default constructor.
     */
    public SubmitterLink() {
        super();
    }

    /**
     * @param parent parent object of this submitter link
     * @param tag long version of type string
     * @param xref the reference to a submitter object
     */
    public SubmitterLink(final GedObject parent, final String tag,
            final ObjectId xref) {
        super(parent, tag, xref);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void accept(final GedObjectVisitor visitor) {
        visitor.visit(this);
    }
}


text:
package configdrive

import (
	"encoding/json"
)

type Openstack struct {
	Metadata OpenstackMetadata
	Userdata []byte
}

func (data *Openstack) Hostname() string {
	return data.Metadata.Hostname
}

func (data *Openstack) PublicKeys() []string {
	keys := []string{}
	for _, value := range data.Metadata.PublicKeys {
		keys = append(keys, value)
	}
	return keys
}

type OpenstackMetadata struct {
	Az          string            `json:"availability_zone"`
	Files       []struct{}        `json:"files"`
	Hostname    string            `json:"hostname"`
	LaunchIndex uint              `json:"launch_index"`
	Name        string            `json:"name"`
	Meta        map[string]string `json:"meta"`
	PublicKeys  map[string]string `json:"public_keys"`
	UUID        string            `json:"uuid"`
}

func (md *OpenstackMetadata) Unmarshal(in []byte) error {
	return json.Unmarshal(in, md)
}

func (md *OpenstackMetadata) Marshal() ([]byte, error) {
	return json.Marshal(md)
}


text:
package com.kaibla.hamster.example.persistence;

import com.kaibla.hamster.base.AbstractListenerOwner;
import com.kaibla.hamster.base.HamsterEngine;
import com.kaibla.hamster.base.UIContext;
import com.kaibla.hamster.persistence.attribute.DateAttribute;
import com.kaibla.hamster.persistence.attribute.DocumentReferenceAttribute;
import com.kaibla.hamster.persistence.attribute.StringAttribute;
import com.kaibla.hamster.persistence.model.DocumentCollection;
import com.kaibla.hamster.persistence.model.Document;
import com.kaibla.hamster.persistence.model.QueryResultListModel;
import com.kaibla.hamster.persistence.query.Query;
import com.mongodb.client.MongoDatabase;
import java.util.Date;

/**
 * This class defines the collection of messages. It both defines the attributes
 * of a message and contains all Data Operations (queries and write operations) for messages
 *
 * @author korend
 */
public class Messages extends DocumentCollection {

    /**
     * The Text attribute of a message
     */
    public final static StringAttribute TEXT = new StringAttribute(Messages.class, "text");

    /**
     * The creation time attribute of a message
     */
    public final static DateAttribute CREATION_TIME = new DateAttribute(Messages.class, "creation_time");
    /**
     * A reference to the User, who has created this the message
     */
    public final static DocumentReferenceAttribute USER = new DocumentReferenceAttribute(Messages.class, "author", Users.class);

    private static final long serialVersionUID = 1L;

    public Messages(HamsterEngine engine, MongoDatabase db) {
        // not much to do here, we just give this collection the name: messages
        super(engine, db, "messages");
        //if needed we would add the index creation here
    }

    /**
     * Creates a new Message and takes the necessary meta information from the UIContext
     *
     * @param text Text of the new message
     */
    public void addMessage(String text) {
        Document<Messages> message = super.createNew(); //create empty document for the new message
        message.set(CREATION_TIME, new Date()); // set the current time as creation time
        message.set(USER, UIContext.getUser()); // set User who is doing this as creator of the message
        message.set(TEXT, text); //set the Text of the message
        message.writeToDatabase(); //writes the new document to the Database and fires events for it
    }

    /**
     * Returns the messages as list model. The list model is event driven and will fire events
     * whenever the content changes.
     *
     * @param owner The owner of this list model, in our case this will be the List UI Component that will display the messages.
     * The owner is used to make sure that the list model will live as long as its owner is alive.
     *
     * @return List Model container the messages order by their creation time.
     */
    public QueryResultListModel getMessages(AbstractListenerOwner owner) {
        return query(owner,new Query().addSortCriteria(CREATION_TIME, true));
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<doctrine-mapping xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mapping http://doctrine-project.org/schemas/orm/doctrine-mapping.xsd">
  <entity name="Actor" table="ACTOR">
    <id name="actorId" type="integer" column="ACTOR_ID">
      <generator strategy="IDENTITY"/>
    </id>
    <field name="userId" type="integer" column="USER_ID" nullable="false"/>
    <field name="organisatorRefId" type="integer" column="ORGANISATOR_REF_ID" nullable="false"/>
    <field name="actorTitle" type="string" column="ACTOR_TITLE" length="55" nullable="false"/>
    <field name="actorDate" type="datetime" column="ACTOR_DATE" nullable="false"/>
  </entity>
</doctrine-mapping>


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.wpi.first.wpilibj.templates.commands;

/**
 *
 * @author David Wigley
 */
public class PitcherUp extends CommandBase {

    private static final double movingTime = 0.5;

    public PitcherUp() {
        super("PitcherUp");
        requires(shooter);
        // Use requires() here to declare subsystem dependencies
        // eg. requires(chassis);
    }

    // Called just before this Command runs the first time
    protected void initialize() {
        setTimeout(movingTime);
        shooter.setNearAngle();
        //for scoring up close
    }

    // Called repeatedly when this Command is scheduled to run
    protected void execute() {
    }

    // Make this return true when this Command no longer needs to run execute()
    protected boolean isFinished() {
        return isTimedOut();
    }

    // Called once after isFinished returns true
    protected void end() {
    }

    // Called when another command which requires one or more of the same
    // subsystems is scheduled to run
    protected void interrupted() {
    }
}


text:
FROM vulhub/java:7u21-jdk

LABEL maintainer="phithon <root@leavesongs.com>"
ENV PATH=${PATH}:/opt/maven/bin

RUN set -ex \
    && mkdir /opt/maven \
    && wget -qO- https://archive.apache.org/dist/maven/maven-3/3.5.0/binaries/apache-maven-3.5.0-bin.tar.gz | tar xz --strip-components 1 -C /opt/maven

COPY . /usr/src/
RUN set -ex \
    && cd /usr/src/ \
    && mvn -Dhttps.protocols=TLSv1.2 compile jetty:effective-web-xml

EXPOSE 8080
WORKDIR /usr/src
CMD ["mvn", "jetty:run"]


text:
require 'spec_helper'
# We can't really test much here, apart from the type roundtrips though the
# parser OK.
describe 'inherit_test1' do
  it do
    should contain_inherit_ini_setting('valid_type').with({
      'value' => 'true'
    })
  end
end


text:
// Code generated by client-gen. DO NOT EDIT.

package fake

import (
	servicecatalog "github.com/kubernetes-incubator/service-catalog/pkg/apis/servicecatalog"
	v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	labels "k8s.io/apimachinery/pkg/labels"
	schema "k8s.io/apimachinery/pkg/runtime/schema"
	types "k8s.io/apimachinery/pkg/types"
	watch "k8s.io/apimachinery/pkg/watch"
	testing "k8s.io/client-go/testing"
)

// FakeServiceInstances implements ServiceInstanceInterface
type FakeServiceInstances struct {
	Fake *FakeServicecatalog
	ns   string
}

var serviceinstancesResource = schema.GroupVersionResource{Group: "servicecatalog.k8s.io", Version: "", Resource: "serviceinstances"}

var serviceinstancesKind = schema.GroupVersionKind{Group: "servicecatalog.k8s.io", Version: "", Kind: "ServiceInstance"}

// Get takes name of the serviceInstance, and returns the corresponding serviceInstance object, and an error if there is any.
func (c *FakeServiceInstances) Get(name string, options v1.GetOptions) (result *servicecatalog.ServiceInstance, err error) {
	obj, err := c.Fake.
		Invokes(testing.NewGetAction(serviceinstancesResource, c.ns, name), &servicecatalog.ServiceInstance{})

	if obj == nil {
		return nil, err
	}
	return obj.(*servicecatalog.ServiceInstance), err
}

// List takes label and field selectors, and returns the list of ServiceInstances that match those selectors.
func (c *FakeServiceInstances) List(opts v1.ListOptions) (result *servicecatalog.ServiceInstanceList, err error) {
	obj, err := c.Fake.
		Invokes(testing.NewListAction(serviceinstancesResource, serviceinstancesKind, c.ns, opts), &servicecatalog.ServiceInstanceList{})

	if obj == nil {
		return nil, err
	}

	label, _, _ := testing.ExtractFromListOptions(opts)
	if label == nil {
		label = labels.Everything()
	}
	list := &servicecatalog.ServiceInstanceList{ListMeta: obj.(*servicecatalog.ServiceInstanceList).ListMeta}
	for _, item := range obj.(*servicecatalog.ServiceInstanceList).Items {
		if label.Matches(labels.Set(item.Labels)) {
			list.Items = append(list.Items, item)
		}
	}
	return list, err
}

// Watch returns a watch.Interface that watches the requested serviceInstances.
func (c *FakeServiceInstances) Watch(opts v1.ListOptions) (watch.Interface, error) {
	return c.Fake.
		InvokesWatch(testing.NewWatchAction(serviceinstancesResource, c.ns, opts))

}

// Create takes the representation of a serviceInstance and creates it.  Returns the server's representation of the serviceInstance, and an error, if there is any.
func (c *FakeServiceInstances) Create(serviceInstance *servicecatalog.ServiceInstance) (result *servicecatalog.ServiceInstance, err error) {
	obj, err := c.Fake.
		Invokes(testing.NewCreateAction(serviceinstancesResource, c.ns, serviceInstance), &servicecatalog.ServiceInstance{})

	if obj == nil {
		return nil, err
	}
	return obj.(*servicecatalog.ServiceInstance), err
}

// Update takes the representation of a serviceInstance and updates it. Returns the server's representation of the serviceInstance, and an error, if there is any.
func (c *FakeServiceInstances) Update(serviceInstance *servicecatalog.ServiceInstance) (result *servicecatalog.ServiceInstance, err error) {
	obj, err := c.Fake.
		Invokes(testing.NewUpdateAction(serviceinstancesResource, c.ns, serviceInstance), &servicecatalog.ServiceInstance{})

	if obj == nil {
		return nil, err
	}
	return obj.(*servicecatalog.ServiceInstance), err
}

// UpdateStatus was generated because the type contains a Status member.
// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus().
func (c *FakeServiceInstances) UpdateStatus(serviceInstance *servicecatalog.ServiceInstance) (*servicecatalog.ServiceInstance, error) {
	obj, err := c.Fake.
		Invokes(testing.NewUpdateSubresourceAction(serviceinstancesResource, "status", c.ns, serviceInstance), &servicecatalog.ServiceInstance{})

	if obj == nil {
		return nil, err
	}
	return obj.(*servicecatalog.ServiceInstance), err
}

// Delete takes name of the serviceInstance and deletes it. Returns an error if one occurs.
func (c *FakeServiceInstances) Delete(name string, options *v1.DeleteOptions) error {
	_, err := c.Fake.
		Invokes(testing.NewDeleteAction(serviceinstancesResource, c.ns, name), &servicecatalog.ServiceInstance{})

	return err
}

// DeleteCollection deletes a collection of objects.
func (c *FakeServiceInstances) DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error {
	action := testing.NewDeleteCollectionAction(serviceinstancesResource, c.ns, listOptions)

	_, err := c.Fake.Invokes(action, &servicecatalog.ServiceInstanceList{})
	return err
}

// Patch applies the patch and returns the patched serviceInstance.
func (c *FakeServiceInstances) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *servicecatalog.ServiceInstance, err error) {
	obj, err := c.Fake.
		Invokes(testing.NewPatchSubresourceAction(serviceinstancesResource, c.ns, name, data, subresources...), &servicecatalog.ServiceInstance{})

	if obj == nil {
		return nil, err
	}
	return obj.(*servicecatalog.ServiceInstance), err
}


text:
#region Copyright
// DotNetNuke® - http://www.dotnetnuke.com
// Copyright (c) 2002-2017
// by DotNetNuke Corporation
// All Rights Reserved
#endregion

#region "Usings"

using System.Collections.Generic;

using DotNetNuke.Services.Mobile;

#endregion

namespace DotNetNuke.Modules.PreviewProfileManagement.ViewModels
{
	/// <summary>
	/// View model of profile management.
	/// </summary>
	public class ProfileManagerViewModel
	{
		/// <summary>
		/// Profiles list.
		/// </summary>
		public IList<IPreviewProfile> PreviewProfiles { get; set; }

		/// <summary>
		/// Highlight profiles list.
		/// </summary>
		public List<IPreviewProfile> HighlightProfiles { get; set; }

		/// <summary>
		/// Profile need to edit.
		/// </summary>
		public IPreviewProfile EditProfile { get; set; }
	}
}