text:
> Correctly concatenates .po files.

## Install

1. Install the plugin with the following command:

	```shell
	npm install gulp-concat-po --save-dev
	```

## Usage

```js
var gulp = require('gulp');
var concatPo = require('gulp-concat-po');

gulp.task('default', function () {
    return gulp.src(['src/gettext/*.po'])
        .pipe(concatPo('messages.pot'))
        .pipe(gulp.dest('release'));
});
```

## API

### concatPo(fileName, options)

#### fileName

Type: `String`

Name of the resulting file.

#### options.headers

Type: `Object`

A list of headers that will be used in the resulting .po file. The object can contain the following keys:

- Project-Id-Version
- Report-Msgid-Bugs-To
- POT-Creation-Date
- PO-Revision-Date
- Last-Translator
- Language
- Language-Team
- Content-Type
- Content-Transfer-Encoding
- Plural-Forms

Description of the fields can be found [here](https://www.gnu.org/software/gettext/manual/html_node/Header-Entry.html#Header-Entry).
If a field is not specified the value from the first file in the stream will be used.

## License

[MIT](http://opensource.org/licenses/MIT) © Dmitriy Simushev


text:
using std::string;

#include "DTexture.h"

class DImage : public DTexture
{
    public:
              DImage    ();
              DImage    (SDL_Renderer* _renderer, string path, Uint8 red = 0xFF, Uint8 green = 0xFF, Uint8 blue = 0xFF);
             ~DImage    ();
        bool  loadImage (string path, Uint8 red = 0xFF, Uint8 green = 0xFF, Uint8 blue = 0xFF);
};

redpajama_set_name: RedPajamaGithub


text:
/**
 * @file	ofp_switch_config_apis.h
 * @brief	Agent/Data-Plane APIs for ofp_switch_config
 * @details	Describe APIs between Agent and Data-Plane for ofp_switch_config.
 */
#ifndef __LAGOPUS_OFP_SWITCH_CONFIG_APIS_H__
#define __LAGOPUS_OFP_SWITCH_CONFIG_APIS_H__

#include "lagopus_apis.h"
#include "openflow.h"
#include "lagopus/bridge.h"

/* Switch Config */
/**
 * Update the switch configuration for \b OFPT_SET_CONFIG.
 *
 *     @param[in]	dpid	Datapath id.
 *     @param[in]	switch_config	A pointer to \e ofp_switch_config structure.
 *     @param[out]	error	A pointer to \e ofp_error structure.
 *     If errors occur, set filed values.
 *
 *     @retval	LAGOPUS_RESULT_OK	Succeeded.
 *     @retval	LAGOPUS_RESULT_ANY_FAILURES	Failed.
 */
lagopus_result_t
ofp_switch_config_set(uint64_t dpid,
                      struct ofp_switch_config *switch_config,
                      struct ofp_error *error);

/**
 * Get switch configuration.
 *
 *     @param[in]	dpid	Datapath id.
 *     @param[out]	switch_config	A pointer to \e ofp_switch_config structure.
 *     @param[out]	error	A pointer to \e ofp_error structure.
 *     If errors occur, set filed values.
 *
 *     @retval	LAGOPUS_RESULT_OK	Succeeded.
 *     @retval	LAGOPUS_RESULT_ANY_FAILURES	Failed.
 */
lagopus_result_t
ofp_switch_config_get(uint64_t dpid,
                      struct ofp_switch_config *switch_config,
                      struct ofp_error *error);
/* Switch Config END */

/**
 * Get current switch mode (openflow, secure or standalone).
 *
 * @param[in]   dpid    Datapath ID.
 * @param[out]  switch_mode     Current switch_mode.
 *
 * @retval      LAGOPUS_RESULT_OK       Succeeded.
 * @retval      LAGOPUS_RESULT_NOT_FOUND        Failed, Not found.
 * @retval      LAGOPUS_RESULT_ANY_FAILURES     Failed.
 */
lagopus_result_t
ofp_switch_mode_get(uint64_t dpid, enum switch_mode *switch_mode);

/**
 * Set switch mode (openflow, secure or standalone).
 *
 * @param[in]   dpid    Datapath ID.
 * @param[in]   switch_mode     switch_mode to be set.
 *
 * @retval      LAGOPUS_RESULT_OK       Succeeded.
 * @retval      LAGOPUS_RESULT_NOT_FOUND        Failed, Not found.
 * @retval      LAGOPUS_RESULT_ANY_FAILURES     Failed.
 */
lagopus_result_t
ofp_switch_mode_set(uint64_t dpid, enum switch_mode switch_mode);

/**
 * Get OpenFlow switch fail mode.
 *
 * @param[in]   dpid    Datapath ID.
 * @param[out]  fail_mode       Bridge fail mode.
 *
 * @retval      LAGOPUS_RESULT_OK       Succeeded.
 * @retval      LAGOPUS_RESULT_NOT_FOUND        Failed, Not found.
 * @retval      LAGOPUS_RESULT_ANY_FAILURES     Failed.
 */
lagopus_result_t
ofp_switch_fail_mode_get(uint64_t dpid,
                         enum fail_mode *fail_mode);

/**
 * Get primary OpenFlow version.
 *
 * @param[in]   dpid    Datapath ID.
 * @param[out]  version Wire protocol version.
 *
 * @retval      LAGOPUS_RESULT_OK               Succeeded.
 * @retval      LAGOPUS_RESULT_NOT_FOUND        Failed, Not found.
 * @retval      LAGOPUS_RESULT_ANY_FAILURES     Failed.
 */
lagopus_result_t
ofp_switch_version_get(uint64_t dpid, uint8_t *version);

/**
 * Set primary OpenFlow version.
 *
 * @param[in]   dpid    Datapath ID.
 * @param[in]   version Wire protocol version.
 *
 * @retval      LAGOPUS_RESULT_OK               Succeeded.
 * @retval      LAGOPUS_RESULT_INVALID_ARGS     Version number is wrong.
 * @retval      LAGOPUS_RESULT_NOT_FOUND        Failed, Not found.
 * @retval      LAGOPUS_RESULT_ANY_FAILURES     Failed.
 */
lagopus_result_t
ofp_switch_version_set(uint64_t dpid, uint8_t version);

/**
 * Get supported OpenFlow version bitmap.
 *
 * @param[in]   dpid    Datapath ID.
 * @param[out]  version_bitmap  Support version bitmap.
 *
 * @retval      LAGOPUS_RESULT_OK               Succeeded.
 * @retval      LAGOPUS_RESULT_NOT_FOUND        Failed, Not found.
 * @retval      LAGOPUS_RESULT_ANY_FAILURES     Failed.
 */
lagopus_result_t
ofp_switch_version_bitmap_get(uint64_t dpid,
                              uint32_t *version_bitmap);

/**
 * Set supported OpenFlow version bitmap.
 *
 * @param[in]   dpid    Datapath ID.
 * @param[in]   version Wire protocol version to be set to version bitmap.
 *
 * @retval      LAGOPUS_RESULT_OK               Succeeded.
 * @retval      LAGOPUS_RESULT_INVALID_ARGS     Version number is wrong.
 * @retval      LAGOPUS_RESULT_NOT_FOUND        Failed, Not found.
 * @retval      LAGOPUS_RESULT_ANY_FAILURES     Failed.
 */
lagopus_result_t
ofp_switch_version_bitmap_set(uint64_t dpid, uint8_t version);

/**
 * Get OpenFlow switch features.
 *
 * @param[in]   dpid    Datapath ID.
 * @param[out]  features        ofp_switch_features structure.
 *
 * @retval      LAGOPUS_RESULT_OK               Succeeded.
 * @retval      LAGOPUS_RESULT_NOT_FOUND        Failed, Not found.
 * @retval      LAGOPUS_RESULT_ANY_FAILURES     Failed.
 */
lagopus_result_t
ofp_switch_features_get(uint64_t dpid,
                        struct ofp_switch_features *features);

#endif /* __LAGOPUS_OFP_SWITCH_CONFIG_APIS_H__ */


text:
//// [genericCallWithGenericSignatureArguments3.ts]
// When a function expression is inferentially typed (section 4.9.3) and a type assigned to a parameter in that expression references type parameters for which inferences are being made,
// the corresponding inferred type arguments to become fixed and no further candidate inferences are made for them.

function foo<T>(x: T, a: (x: T) => T, b: (x: T) => T) {
    var r: (x: T) => T;
    return r;
}

var r1 = foo('', (x: string) => '', (x: Object) => null); // any => any
var r1ii = foo('', (x) => '', (x) => null); // string => string
var r2 = foo('', (x: string) => '', (x: Object) => ''); // string => string
var r3 = foo(null, (x: Object) => '', (x: string) => ''); // Object => Object
var r4 = foo(null, (x) => '', (x) => ''); // any => any
var r5 = foo(new Object(), (x) => '', (x) => ''); // Object => Object

enum E { A }
enum F { A }

var r6 = foo(E.A, (x: number) => E.A, (x: F) => F.A); // number => number

function foo2<T, U>(x: T, a: (x: T) => U, b: (x: T) => U) {
    var r: (x: T) => U;
    return r;
}

var r8 = foo2('', (x) => '', (x) => null); // string => string
var r9 = foo2(null, (x) => '', (x) => ''); // any => any
var r10 = foo2(null, (x: Object) => '', (x: string) => ''); // Object => Object

var x: (a: string) => boolean;
var r11 = foo2(x, (a1: (y: string) => string) => (n: Object) => 1, (a2: (z: string) => string) => 2); // {} => {}
var r12 = foo2(x, (a1: (y: string) => boolean) => (n: Object) => 1, (a2: (z: string) => boolean) => 2); // (string => boolean) => {}

//// [genericCallWithGenericSignatureArguments3.js]
// When a function expression is inferentially typed (section 4.9.3) and a type assigned to a parameter in that expression references type parameters for which inferences are being made,
// the corresponding inferred type arguments to become fixed and no further candidate inferences are made for them.
function foo(x, a, b) {
    var r;
    return r;
}
var r1 = foo('', function (x) { return ''; }, function (x) { return null; }); // any => any
var r1ii = foo('', function (x) { return ''; }, function (x) { return null; }); // string => string
var r2 = foo('', function (x) { return ''; }, function (x) { return ''; }); // string => string
var r3 = foo(null, function (x) { return ''; }, function (x) { return ''; }); // Object => Object
var r4 = foo(null, function (x) { return ''; }, function (x) { return ''; }); // any => any
var r5 = foo(new Object(), function (x) { return ''; }, function (x) { return ''; }); // Object => Object
var E;
(function (E) {
    E[E["A"] = 0] = "A";
})(E || (E = {}));
var F;
(function (F) {
    F[F["A"] = 0] = "A";
})(F || (F = {}));
var r6 = foo(0 /* A */, function (x) { return 0 /* A */; }, function (x) { return 0 /* A */; }); // number => number
function foo2(x, a, b) {
    var r;
    return r;
}
var r8 = foo2('', function (x) { return ''; }, function (x) { return null; }); // string => string
var r9 = foo2(null, function (x) { return ''; }, function (x) { return ''; }); // any => any
var r10 = foo2(null, function (x) { return ''; }, function (x) { return ''; }); // Object => Object
var x;
var r11 = foo2(x, function (a1) { return function (n) { return 1; }; }, function (a2) { return 2; }); // {} => {}
var r12 = foo2(x, function (a1) { return function (n) { return 1; }; }, function (a2) { return 2; }); // (string => boolean) => {}


text:
var testHelper = require('../../test_helper');
var should = testHelper.should;
var waterlock = testHelper.waterlock_local;

var login = waterlock.actions.login;

describe('login action', function(){

  it('should exist', function(done){
    login.should.be.Function;
    done();
  });

  it('should respond with error', function(done){
    var req = {
      method: 'PUT',
      params: {
         email: 'test@test.com',
         password: 'testtesttest'
      }
    };
    var res = {
      json: function(code){
         code.should.equal(200);
         done();
      }
    };
    login(req, res);
  });

});


text:
from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.contrib.auth import urls as authurls

from NutmegCRM.apps.tickets import urls as ticketurls
from apps.crm import urls as crmurls
from django.contrib.auth import views as authviews

admin.autodiscover()

urlpatterns = [
    # Index for the entire site
    url(r'^$', 'NutmegCRM.apps.overview.views.index', name='home'),

    # our various apps for the site.
    url(r'^admin/', include(admin.site.urls)),
    url(r'^tickets/', include(ticketurls,  namespace='tickets')),
    url(r'^customers/', include(crmurls, namespace='customers')),
    url(r'^accounts/$', authviews.login),
    url(r'^accounts/', include(authurls)),
]


text:
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html
     PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  <title>Class: Fusioncharts::DbDrilldownController</title>
  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
  <meta http-equiv="Content-Script-Type" content="text/javascript" />
  <link rel="stylesheet" href="../.././rdoc-style.css" type="text/css" media="screen" />

          Class
          Fusioncharts::DbDrilldownController

            In:

                app/controllers/fusioncharts/db_drilldown_controller.rb

            Parent:

                ApplicationController

Methods

      default
      detailed

Public Instance methods

          default()

In this function, we obtain total output of quantities and name of each
factory from the database and plot them on a pie-chart. It stores URL to
the "detailed"
function in a variable passing FactoryId as parameter to the function which
returns quantity produced and date of production of the factory that are
obtained from database and which are plotted in a chart. This action
retrieves the values from the database and constructs an array to hold,
factory name, corresponding total output quantity and URL to the action
which will generate the detailed chart. The view for
this action default.html.erb will use the array values to construct the xml
for this chart. To build the xml, the view takes help from the builder file
(default_factories_quantity.builder)

          detailed()

This action retrieves the quantity and date of production of the factory
identified by the request parameter expected "FactoryId" The view
for this action is detailed.html.erb and it uses the builder file
factory_details.builder to build the xml for the column chart.

[Validate]


text:
"use strict";
// Created by Juan Camilo Osorio (JCOC611 - jcoc611.com).
// Version 1.1.1. (Beta, stable).
// Consider giving back by sharing your own code!
// Licensed under the MIT License.
// http://www.opensource.org/licenses/mit-license.php

// Includes jQuery Caret v1.0.2
// Slightly modified by JCOC611.
// Created by C. F., Wong, and also licensed
// under the MIT License. Find his project here:
// https://code.google.com/p/jcaret/

(function($) {
	if(!$) throw new Error("Input Affix: no jQuery found. Make sure window.jQuery exists.");
	// Functions
	// Caret from Wong's code.
	$.fn.caret = function(options, opt2) {
		/* (*) -> object

		Return new object that contains:
			- start: the start index of the current selection.
			- end: the end index of the current selection.
			- text: the text contained within the selection.

		Overloads:
		(object) -> object
			Set the current browser selection to this element, starting at
			options.start and ending at options.end.
		(int, int) -> object
			Set the current browser selection to this element, starting at
			options, and ending at opt2.
		(str) -> object
			Set the current browser selection to this element, containing
			the first instance of the string options.
		(regexp) -> object
			Set the current browser selection to this element, containing
			the first instance matched by the regular expression options.
		() -> object
			Do nothing but return the object described above.

		Most comments and some slight edits were made by JCOC611.
		Credit goes to C. F., Wong.

		*/

		var start, end, t = this[0];
		// For overloading.
		// .caret({start:..., end:...})
		//      or ({start ...})
		if (typeof options === "object" && typeof options.start === "number") {
			start = options.start;
			if(typeof options.end === "number") end = options.end;
			else end = options.start;
		// .caret(start, end)
		//      or (start)
		} else if (typeof options === "number") {
			start = options;
			if(typeof opt2 === "number") end = opt2;
			else end = start;
		// .caret("str")
		} else if (typeof options === "string") {
			if ((start = t.value.indexOf(options)) > -1) end = start + options.length;
			else start = null;
		// .caret(/regex/)
		} else if (Object.prototype.toString.call(options) === "[object RegExp]") {
			var re = options.exec(t.value);
			if (re != null) {
				start = re.index;
				end = start + re[0].length;
			}
		}

		// Overload for .caret(...) called with new selection information.
		if (typeof start != "undefined") {
			// For compatibility.
			if (t.createTextRange) {
				var selRange = t.createTextRange();
				selRange.collapse(true);
				selRange.moveStart('character', start);
				selRange.moveEnd('character', end - start);
				selRange.select();
			} else {
				t.selectionStart = start;
				t.selectionEnd = end;
			}
			t.focus();
			return this
		// Overload for .caret(), with no arguments.
		} else {
			// Modification as suggested by Андрей Юткин
			if(document.selection){
				var selection = document.selection;
				if (t.tagName.toLowerCase() != "textarea") {
					var val = this.val(),
						range = selection["createRange"]()["duplicate"]();

					range.moveEnd("character", val.length);

					var s = (range.text == "" ? val.length : val.lastIndexOf(range.text));

					range = selection["createRange"]()["duplicate"]();
					range.moveStart("character", -val.length);

					var e = range.text.length;
				} else {
					var range = selection["createRange"](),
						stored_range = range["duplicate"]();

					stored_range.moveToElementText(t);
					stored_range.setEndPoint('EndToEnd', range);

					var s = stored_range.text.length - range.text.length,
						e = s + range.text.length
				}
				// End of Modification
			} else {
				var s = t.selectionStart,
					e = t.selectionEnd;
			}
			// Substring text.
			var te = t.value.substring(s, e);
			// Return usable object
			return {
				start: s,
				end: e,
				text: te,
				replace: function(st) {
					return t.value.substring(0, s) + st + t.value.substring(e, t.value.length)
				}
			}
		}
	}
	$.fn.affixValue = function(val){
		/* (str) -> jQuery Object

		Set the value property of this object to val, taking care
		of adding the appropriate prefixes and suffixes if necessary.
		Mostly just a wrapper function for .val() that doesn't break
		Input Affix.

		Return the jQuery object.

		>>> $("#example").prefix("Yeah, ");
		>>> $("#example").suffix("!");
		>>> $("#example").affixValue("this works");
		>>> $("#example").val();
		"Yeah, this works!"

		*/

		// Overload for .affixValue(), with no arguments.
		if(val === undefined){
			// Get current value
			val = this.val();

			var prefix = this.data("prefix"),
				suffix = this.data("suffix");

			// Remove prefix if necessary
			if(prefix && val.substr(0, prefix.length) == prefix)
				val = val.substr(prefix.length);
			// Remove suffix if necessary
			if(suffix && val.substr(val.length - suffix.length) == suffix)
				val = val.substr(0, val.length - suffix.length);

			// Return inner value
			return val;
		}

		val += "";

		// Overload for .affixValue(val)
		// Add the prefix if necessary
		if(this.data("prefix")) val = this.data("prefix") + val;

		// Add the suffix if necessary
		if(this.data("suffix")) val += this.data("suffix");

		// Set the value
		this.val(val);

		// Return jQuery object.
		return this;
	};
	$.fn.prefix = function(pre, index){
		/* (* [, int]) -> *

		Functionality depends on the arguments,
		take a look at the following:

		Overloads:
		() -> str
			Return the current prefix.

			>>> $("#example").prefix("hello");
			>>> $("#example").prefix();
			"hello"

		(str) -> jQuery Object
			Set the current prefix to pre.
			Return jQuery element.

			>>> $("#example").prefix("hello");
			$("#example")

		(array [, int]) -> jQuery Object
			Set the current prefix to the string
			given by pre[index] if index was set, or
			pre[0] otherwise. Set the current prefix list
			to pre.
			Return jQuery element.

			>>> $("#example").prefix(["hi", "there"], 1);
			$("#example")
			>>> $("#example").prefix();
			"there"

		(int) -> jQuery Object
			Precondition: .prefix([...]) was called
			previous to the execution of .prefix(int),
			such that prefix list is set.

			Set the current prefix to the string located
			at the index pre of the array previously set
			by .prefix([...]).
			Return jQuery element.

			>>> $("#example").prefix(["zero", "one", "two"]);
			>>> $("#example").prefix(1);
			>>> $("#example").prefix();
			"one"

		*/

		// Overload for .prefix(), called with no arguments
		if(pre === undefined) return this.data("prefix");

		var val = this.val(), prefix = this.data("prefix");

		// Remove previous prefix (if it's there)
		if(prefix && val.substr(0, prefix.length) == prefix){
			this.val(val.substr(prefix.length, val.length - prefix.length));
			val = this.val();
		}

		// Overload for .prefix([...], index), an array of prefixes.
		if(typeof(pre) == "object"){
			this.data("prefix-list", pre);
			index = index || 0;
			pre = pre[index];
		// Overload for .prefix(number).
		}else if(typeof(pre) == "number" && this.data("prefix-list")){
			index = pre;
			pre = this.data("prefix-list")[index];
		// Restore prefix-list
		}else this.data("prefix-list", false);

		// Set new prefix data
		this.data("prefix", pre);
		this.data("prefixQueue", 0);
		this.trigger("prefixchange", [pre, index || 0]);

		// Allow placeholder if no value
		// Add prefix if it's not already there
		if(!(this.affixValue() == "" && this.attr("placeholder")) && val.indexOf(pre) != 0){
			this.val(pre + this.val());
		}

		// Set event handlers
		this.on("keypress", function(e){
			var t = $(this),
				caret = t.caret(),
				prefix = t.data("prefix"),
				val = t.val();
			// Ignore specials
			if(e.ctrlKey) return;
			// Caret position fix
			if(caret.start < prefix.length){
				var prefixList = t.data("prefix-list"),
					input = String.fromCharCode(e.which);
				// If a prefix list was used, update current prefix if necessary.
				if(prefixList && caret.start == 0){
					for(var z = 0; z < prefixList.length; z++){
						if(prefixList[z].substr(0, 1) == input){
							t.prefix(z);
							var newPrefix = t.prefix();
							t.caret({	 start: 1 });
							e.preventDefault();
							return;
						}
					}
				}
				// Allow to change prefix if a list is used
				if(prefixList && val.substr(0, pre.length) != pre) return;

				var prefixQueue = t.data("prefixQueue");
				if(caret.start == caret.end && prefix.substr(caret.start, 1) == input){
					t.caret(caret.start);
					t.data("prefixQueue", caret.start + 1);
					e.preventDefault();
				}else if(caret.start != caret.end && prefix.substr(caret.start, 1) == input){
					var newVal = prefix + val.substr(caret.end);
					if(t.data("suffix")){
						newVal += t.data("suffix");
					}
					t.val(newVal);
					t.caret(caret.start + 1);
					e.preventDefault();
				}else{
					if(caret.start == caret.end && prefixQueue == caret.start){
						var start = caret.start + prefix.length;

						t.val(prefix + val.substr(0, caret.start) + input + val.substr(prefix.length));
						t.caret(start+1);
						t.data("prefixQueue", 0);
						e.preventDefault();
					}else{
						t.caret({ start: prefix.length, end: Math.max(caret.end, prefix.length) });
					}
				}
			}
		}).on("keydown", function(e){
			var $t = $(this),
				caret = $t.caret(),
				prefix = $t.data("prefix");
			// Backspace & delete fix
			if(e.which == 8 || e.which == 46){
				// Allow for backspace & delete if prefix list is used
				if($t.data("prefix-list")) return;

				// Else prevent it:
				// Backspace on prefix
				// if(e.which == 8 && caret.start <= prefix.length && caret.start == caret.end) e.preventDefault();
				if(e.which == 8 && caret.end <= prefix.length){
					$t.caret(prefix.length);
					e.preventDefault();
				}else if(caret.end < prefix.length){
					$t.caret(prefix.length);
				}else if(caret.start < prefix.length){
					$t.caret({ start:prefix.length, end:caret.end });
				}

			// Paste fix position
			}else if(e.which == 86 && e.ctrlKey){
				// If prefix list is used, do nothing weird
				if($t.data("prefix-list")) return;
				// Handle caret positions
				if(caret.start < prefix.length){
					var end = caret.end;
					if(end < prefix.length) end += prefix.length;
					$t.caret({start:prefix.length, end:end});
				}
			// Home/start fix
			}else if(e.which == 36 && e.ctrlKey){
				if(e.shiftKey) $t.caret({start:prefix.length, end:Math.max(caret.start, prefix.length)});
				else $t.caret({start:prefix.length, end:prefix.length});
				e.preventDefault();
			}
		}).on("paste", function(e){
			// Fixes some pasting issues.
			// Works with context menu too.
			var t = $(this);

			// Set timeout hack to skip call stack.
			setTimeout(function(){
				// Set local vars.
				var prefix = t.data("prefix"),
					caret = t.caret(),
					val = t.val(),
					end = caret.end;

				// If prefix list was used, compute new prefix
				if(t.data("prefix-list")){
					var prefixList = t.data("prefix-list");
					for(var z = 0; z < prefixList.length; z++){
						if(val.substr(0, prefixList[z].length) == prefixList[z]){
							prefix = prefixList[z];
							t.data("prefix", prefix);
							t.trigger("prefixchange", [prefix, z]);
							break;
						}
					}
				}

				// If a paste deletes the prefix, add it again.
				if(val.substr(0, prefix.length) != prefix){
					val = prefix + val;
					end += prefix.length;
				}

				// More vars
				var body = val.substr(prefix.length),
					nbody = body;

				// Delete repeated prefix from body
				for(var z = prefix.length - 1; z >= 0; z--){
					if(body.substr(0, z + 1) == prefix.substr((prefix.length - 1) - z)){
						nbody = nbody.substr(z + 1);
						break;
					}
				}

				// Set the final value and caret pos.
				t.val(prefix + nbody);
				t.caret({
					start: end,
					end: end
				});

				// Prevent default paste.
				e.preventDefault();
			});
		}).on("change", function(e){
			// If prefix is lost in input, re-add it.
			var prefix = $(this).data("prefix"),
				// caret = $(this).caret(),
				val = $(this).val();
				// end = caret.end;

			if(val.substr(0, prefix.length) != prefix){
				val = prefix + val;
				$(this).val(val);
			}
		}).on("blur", function(e){
			var prefixList = $(this).data("prefix-list");
			var prefix = $(this).data("prefix"),
				val = $(this).val();

			// If prefix list was used, check if prefix changed
			if(prefixList && val.substr(0, prefix.length) != prefix){
				// If new prefix is in prefix list...
				for(var z = 0; z < prefixList.length; z++){
					if(val.substr(0, prefixList[z].length) == prefixList[z]){
						$(this).prefix(z);
						return;
					}
				}
				// Else readd original prefix
				val = prefix + val;
				$(this).val(val);
			}
			// If input has placeholder and is empty
			// show placeholder
			if($(this).affixValue() == "" && $(this).attr("placeholder")){
				$(this).val("");
			}
		}).on("focus", function(e){
			var val = $(this).affixValue();
			if(val == ""){
				$(this).affixValue("");
			}
		});
		return this;
	};
	$.fn.suffix = function(suff, index){
		/* (* [, int]) -> *

		Functionality depends on the arguments,
		take a look at the following:

		Overloads:
		() -> str
			Return the current suffix.

			>>> $("#example").suffix("hello");
			>>> $("#example").suffix();
			"hello"

		(str) -> jQuery Object
			Set the current suffix to suff.
			Return jQuery element.

			>>> $("#example").suffix("hello");
			$("#example")
			>>> $("#example").suffix();
			"hello"

		(array [, int]) -> jQuery Object
			Set the current suffix to the string
			given by suff[index] if index was set, or
			suff[0] otherwise. Set the current suffix list
			to suff.
			Return jQuery element.

			>>> $("#example").suffix(["hi", "there"], 1);
			$("#example")
			>>> $("#example").suffix();
			"there"

		(int) -> jQuery Object
			Precondition: .suffix([...]) was called
			previous to the execution of .suffix(int),
			such that suffix list is set.

			Set the current suffix to the string located
			at the index suff of the array previously set
			by .suffix([...]).
			Return jQuery element.

			>>> $("#example").suffix(["zero", "one", "two"]);
			>>> $("#example").suffix(1);
			>>> $("#example").suffix();
			"one"

		*/

		// Overload for .suffix(), called with no arguments
		if(suff === undefined) return this.data("suffix");

		var val = this.val(), suffix = this.data("suffix");

		// Remove previous suffix (if it's there)
		if(suffix && val.substr(val.length - suffix.length) == suffix){
			this.val(val.substr(0, val.length - suffix.length));
		}

		// Overload for .suffix([...], index), an array of suffixes.
		if(typeof(suff) == "object"){
			this.data("suffix-list", suff);
			index = index || 0;
			suff = suff[index];
		// Overload for .suffix(number).
		}else if(typeof(suff) == "number" && this.data("suffix-list")){
			index = suff;
			suff = this.data("suffix-list")[index];
		// Restore suffix-list
		}else this.data("suffix-list", false);

		// Set new suffix
		this.data("suffix", suff);
		this.data("suffixQueue", 0);
		this.trigger("suffixchange", [suff, index || 0]);

		// Allow for display of placeholder
		// Add suffix if it's not already there
		if(!(this.affixValue() == "" && this.attr("placeholder"))
			&& this.val().substr(this.val().length - suff.length) !== suff){
			this.val(this.val() + suff);
		}

		// Event handlers
		this.on("keypress", function(e){
			var t = $(this),
				caret = t.caret(),
				val = t.val(),
				suffix = t.data("suffix");

			if(caret.end >= val.length - suffix.length){
				var suffixList = t.data("suffix-list"),
					input = String.fromCharCode(e.which);
				// If a suffix list was used, update current suffix if necessary.
				if(suffixList && caret.start >= val.length - suffix.length){
					for(var z = 0; z < suffixList.length; z++){
						if(suffixList[z].substr(0, 1) == input){
							t.val(val.substr(0, caret.start));
							t.suffix(z);

							t.caret({
								start: t.val().length,
								end: t.val().length
							});
							e.preventDefault();
							return;
						}
					}
				}
				// Allow change of suffix if list is used
				if(suffixList && val.substr(val.length - suff.length) != suffix) return;

				if(caret.start == caret.end && suffix.substr(caret.end - val.length + suffix.length, 1) == input){
					t.caret({start:caret.end + 1, end:caret.end + 1});
					t.data("prefixQueue", caret.end - val.length + suffix.length + 1);
					e.preventDefault();
				}else{
					// IE-specific overwrite mode fix
					var overwriteMode = document.queryCommandValue("OverWrite");

					if(caret.start == caret.end && t.data("prefixQueue") == caret.end - val.length + suffix.length){
						t.val(val.substr(0, caret.start) + input + suffix);
						t.caret({start: caret.start+1, end: caret.start+1});
						e.preventDefault();
					}else if(overwriteMode){
						t.val(val.substr(0, caret.start) + input + suffix);
						t.caret(val.length - suffix.length + 1);
						e.preventDefault();
					} else{
						t.caret({
							start: Math.min(caret.start, val.length- suffix.length),
							end: val.length - suffix.length
						});
					}
				}
			}else if(caret.end == val.length - suffix.length && caret.start == caret.end
				&& suffix.substr(caret.end - val.length + suffix.length, 1) == input){
				t.caret({start:caret.end + 1, end:caret.end + 1});
				e.preventDefault();
			}

		}).on("keydown", function(e){
			var $t = $(this),
				caret = $t.caret(),
				val = $t.val(),
				suffix = $t.data("suffix");
			// Backspace & delete fix
			if(e.which == 8 || e.which == 46){
				// Allow for backspace & delete if suffix list is used
				if($t.data("suffix-list")) return;

				// Else continue
				if(e.which == 46 && caret.start >= val.length - suffix.length){
					$t.caret(val.length - suffix.length);
					e.preventDefault();
				}else if(caret.end > val.length - suffix.length){
					$t.caret({
						start: Math.min(caret.start, val.length - suffix.length),
						end: val.length - suffix.length
					});
					var prefix = $t.data("prefix");
					if(prefix && val.length == prefix.length + suffix.length) e.preventDefault();
				}
			// Paste fix position
			}else if(e.which == 86 && e.ctrlKey){
				// Handle caret positions
				if(caret.end > val.length - suffix.length){
					var start = caret.start;
					if(start > val.length -  suffix.length) start -= suffix.length;
					$t.caret({start:start, end:val.length - suffix.length});
				}
			// End fix
			}else if(e.which == 35 && e.ctrlKey){
				if(e.shiftKey) $t.caret({start:Math.min(val.length - suffix.length, caret.end), end:val.length - suffix.length});
				else $t.caret({start:val.length - suffix.length, end:val.length - suffix.length});
				e.preventDefault();
			}
		}).on("paste", function(e){
			// Fixes some pasting issues.
			// Works with context menu too.

			var t = $(this);

			// Set timeout hack to skip call stack.
			setTimeout(function(){
				// Set local vars.
				var suffix = t.data("suffix"),
					caret = t.caret(),
					val = t.val(),
					start = caret.end;

				// If suffix list was used, compute new suffix
				if(t.data("suffix-list")){
					var suffixList = t.data("suffix-list");
					for(var z = 0; z < suffixList.length; z++){
						if(val.substr(val.length - suffixList[z].length) == suffixList[z]){
							suffix = suffixList[z];
							t.data("suffix", suffix);
							t.trigger("suffixchange", [suffix, z]);
							break;
						}
					}
				}

				// If a paste deletes the suffix, add it again.
				if(val.substr(val.length - suffix.length) != suffix) val += suffix;

				// More vars
				var body = val.substr(0, val.length - suffix.length),
					nbody = body;

				// Handle caret positions
				if(caret.end > val.length - suffix.length){
					var start = caret.start;
					if(start > val.length -  suffix.length) start -= suffix.length;
					$(this).caret({start:start, end:val.length - suffix.length});
				}

				// Delete repeated suffix from body
				for(var z = suffix.length - 1; z >= 0; z--){
					if(body.substr(body.length - suffix.length + z) == suffix.substr(0, suffix.length - z)){
						nbody = nbody.substr(0, body.length - suffix.length + z);
						break;
					}
				}

				// Set the final value and caret pos.
				t.val(nbody + suffix);
				t.caret({
					start: start,
					end: start
				});
				// Prevent default paste.
				e.preventDefault();
			}, 1);

		}).on("change", function(e){
			var suffix = $(this).data("suffix"),
				val = $(this).val();

			// If suffix is lost in input, re-add it.
			if(val.substr(val.length - suffix.length) != suffix){
				val += suffix;
				$(this).val(val);
			}
		}).on("blur", function(e){
			var suffixList = $(this).data("suffix-list");
			var suffix = $(this).data("suffix"),
				val = $(this).val();

			// If suffix list was used, check if suffix changed
			if(suffixList && val.substr(val.length - suffix.length) != suffix){
				// If new suffix is in suffix list...
				for(var z = 0; z < suffixList.length; z++){
					if(val.substr(val.length - suffixList[z].length) == suffixList[z]){
						$(this).suffix(z);
						return;
					}
				}
				// Else re-add original suffix
				val += suffix;
				$(this).val(val);
			}
			// If input has placeholder and is empty
			// show placeholder
			if($(this).affixValue() == "" && $(this).attr("placeholder")){
				$(this).val("");
			}
		}).on("focus", function(e){
			var t = $(this), val = t.affixValue();
			// If input is empty, show suffix
			// And move caret to correct position
			if(val == ""){
				t.affixValue("");
				var pos = 0;
				if(t.data("prefix")){
					pos = t.data("prefix").length;
				}
				setTimeout(function(){
					t.caret({
						start: pos,
						end: pos
					});
				}, 1);
				e.preventDefault();
			}
		});
		return this;
	}
})(window.jQuery);
//TFIN


text:
package com.oydnatech.jpipe.impl;

import com.oydnatech.jpipe.BiListener;
import com.oydnatech.jpipe.BiPipeline;
import com.oydnatech.jpipe.UniToBiPipeline;
import com.oydnatech.jpipe.util.Checks;

import java.util.Objects;

/**
 * Created by Trond Øydna on 04.06.2016.
 */
public abstract class AbstractUniToBiPipeline<I, OL, OR> implements UniToBiPipeline<I, OL, OR> {

    private BiListener<? super OL, ? super OR> next;

    @Override
    public void setListener(BiListener<? super OL, ? super OR> listener) {
        Objects.requireNonNull(listener, "Given listener was null!");
        Checks.requireNull(next, "This pipe has already been assigned a listener!");

        this.next = listener;
    }

    public void applyToListener(OL outputLeft, OR outputRight) {
        next.apply(outputLeft, outputRight);
    }
}


text:
module ActionController #:nodoc:
  module Flash
    extend ActiveSupport::Concern

    included do
      class_attribute :_flash_types, instance_accessor: false
      self._flash_types = []

      delegate :flash, to: :request
      add_flash_types(:alert, :notice)
    end

    module ClassMethods
      def add_flash_types(*types)
        types.each do |type|
          next if _flash_types.include?(type)

          define_method(type) do
            request.flash[type]
          end
          helper_method type

          _flash_types << type
        end
      end
    end

    protected
      def redirect_to(options = {}, response_status_and_flash = {}) #:doc:
        self.class._flash_types.each do |flash_type|
          if type = response_status_and_flash.delete(flash_type)
            flash[flash_type] = type
          end
        end

        if other_flashes = response_status_and_flash.delete(:flash)
          flash.update(other_flashes)
        end

        super(options, response_status_and_flash)
      end
  end
end


text:
package net.minecraft.network.play.server;

import java.io.IOException;
import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.network.INetHandler;
import net.minecraft.network.Packet;
import net.minecraft.network.PacketBuffer;
import net.minecraft.network.play.INetHandlerPlayClient;
import net.minecraft.util.BlockPos;
import net.minecraft.world.World;

public class S23PacketBlockChange implements Packet
{
    private BlockPos field_179828_a;
    private IBlockState field_148883_d;
    private static final String __OBFID = "CL_00001287";

    public S23PacketBlockChange() {}

    public S23PacketBlockChange(World worldIn, BlockPos p_i45988_2_)
    {
        this.field_179828_a = p_i45988_2_;
        this.field_148883_d = worldIn.getBlockState(p_i45988_2_);
    }

    /**
     * Reads the raw packet data from the data stream.
     */
    public void readPacketData(PacketBuffer data) throws IOException
    {
        this.field_179828_a = data.readBlockPos();
        this.field_148883_d = (IBlockState)Block.BLOCK_STATE_IDS.getByValue(data.readVarIntFromBuffer());
    }

    /**
     * Writes the raw packet data to the data stream.
     */
    public void writePacketData(PacketBuffer data) throws IOException
    {
        data.writeBlockPos(this.field_179828_a);
        data.writeVarIntToBuffer(Block.BLOCK_STATE_IDS.get(this.field_148883_d));
    }

    public void func_180727_a(INetHandlerPlayClient p_180727_1_)
    {
        p_180727_1_.handleBlockChange(this);
    }

    public IBlockState func_180728_a()
    {
        return this.field_148883_d;
    }

    public BlockPos func_179827_b()
    {
        return this.field_179828_a;
    }

    /**
     * Passes this Packet on to the NetHandler for processing.
     */
    public void processPacket(INetHandler handler)
    {
        this.func_180727_a((INetHandlerPlayClient)handler);
    }
}


text:
<?php

namespace RAPL\RAPL\Mapping;

use RAPL\RAPL\RAPLException;

class MappingException extends \Exception implements RAPLException
{
    /**
     * @param string $className
     * @param string $fieldName
     *
     * @return MappingException
     */
    public static function mappingNotFound($className, $fieldName)
    {
        return new self("No mapping found for field '$fieldName' on class '$className'.");
    }

    /**
     * @param string $entity
     *
     * @return MappingException
     */
    public static function missingFieldName($entity)
    {
        return new self(
            sprintf("The field or association mapping misses the 'fieldName' attribute in entity '%s'.", $entity)
        );
    }

    /**
     * @param $fieldName
     *
     * @return MappingException
     */
    public static function missingTargetEntity($fieldName)
    {
        return new self(sprintf("The association mapping '%s' misses the 'targetEntity' attribute.", $fieldName));
    }

    /**
     * Exception for reflection exceptions - adds the entity name,
     * because there might be long classnames that will be shortened
     * within the stacktrace.
     *
     * @param string               $entity The entity's name
     * @param \ReflectionException $exception
     *
     * @return MappingException
     */
    public static function reflectionFailure($entity, \ReflectionException $exception)
    {
        return new self(sprintf('An error occured in %s', $entity), 0, $exception);
    }

    /**
     * @param $className
     * @param $routeType
     *
     * @return MappingException
     */
    public static function routeNotConfigured($className, $routeType)
    {
        return new self(sprintf('A %s route is not configured for class %s.', $routeType, $className));
    }
}


text:
/* */
require("../../modules/es6.typed.int16-array");
module.exports = require("../../modules/_core").Int16Array;


text:
package org.lambadaframework.stubs;

import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

@Path("/resource1")
public class StubHandler {

    public static class NewEntityRequest {

        public long id;

        public String name;

    }

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    @Path("/")
    public Response getList(@PathParam("id") long id) {
        return Response.status(200).build();
    }

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    @Path("/{id}")
    public Response getEntity(@PathParam("id") long id) {
        return Response.status(200).build();
    }

    @POST
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public Response newEntity(NewEntityRequest requestBody) {
        return Response.status(200).build();
    }

    @DELETE
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public Response removeEntity(@PathParam("id") long id) {
        return Response.status(200).build();
    }

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    @Path("/{id}/users")
    public Response getEntityUsers(@PathParam("id") long id) {
        return Response.status(200).build();
    }

    @DELETE
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    @Path("/{id}/users")
    public Response removeEntityUser(@PathParam("id") long id) {
        return Response.status(200).build();
    }

}


text:
package com.cjj.mousepaint.customview;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;

/**
 * 自定义GridView
 * @author cjj
 *
 */
public class NormalGridView extends GridView {

	private boolean isAutoSetNumColumns = true;
	private int horizontalSpacing = 0;
    private int columnWidth = 0;
    private boolean isScroll = false;

    public NormalGridView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public NormalGridView(Context context) {
        super(context);
    }

    public NormalGridView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

        int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);

        super.onMeasure(widthMeasureSpec,expandSpec);
    }

	@Override
	public void setOnItemClickListener(OnItemClickListener listener) {
		Log.i("cjj123","cjj123");
		super.setOnItemClickListener(listener);
	}

	@Override
	public void setAdapter(ListAdapter adapter) {

		if(isScroll)
		{

		int gridViewWidth = 0;
		int adapterCount = adapter.getCount();

		if(columnWidth == 0)
		{
			for(int i = 0 ; i< adapter.getCount();i++)
		    {
			View rowView = adapter.getView(i,null,null);
	        measureView(rowView);
			gridViewWidth += rowView.getMeasuredWidth();
		    }
		}
		else
		{
			gridViewWidth += columnWidth*adapterCount;
		}

		if(isAutoSetNumColumns)
		{
			gridViewWidth += (this.getPaddingLeft()+ this.getPaddingRight());
			gridViewWidth += this.horizontalSpacing*(adapterCount-1);
			this.setNumColumns(adapterCount);
		}

		this.setLayoutParams(new LinearLayout.LayoutParams(gridViewWidth,LayoutParams.WRAP_CONTENT));

		}

		super.setAdapter(adapter);
	}

	private void measureView(View child)
	{
		 ViewGroup.LayoutParams p = child.getLayoutParams();
	       if (p == null) {
	           p = new ViewGroup.LayoutParams(
	                   ViewGroup.LayoutParams.FILL_PARENT,
	                   ViewGroup.LayoutParams.WRAP_CONTENT);
	       }

	       int childWidthSpec = ViewGroup.getChildMeasureSpec(0,
	               0 + 0, p.width);
	       int lpHeight = p.height;
	       int childHeightSpec;
	       if (lpHeight > 0) {
	           childHeightSpec = MeasureSpec.makeMeasureSpec(lpHeight, MeasureSpec.EXACTLY);
	       } else {
	           childHeightSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
	       }
	       child.measure(childWidthSpec, childHeightSpec);
	}

	@Override
	public void setNumColumns(int numColumns)
	{
		isAutoSetNumColumns = false;

		super.setNumColumns(numColumns);
	}

	@Override
	public void setHorizontalSpacing(int horizontalSpacing) {

		this.horizontalSpacing = horizontalSpacing;

		super.setHorizontalSpacing(horizontalSpacing);
	}

	@Override
	public void setColumnWidth(int columnWidth) {

		this.columnWidth = columnWidth;

		super.setColumnWidth(columnWidth);
	}

	public void setEnableHorizontalScroll(boolean isScroll)
	{
		this.isScroll = isScroll;
	}
}


text:
package repository

import (
	"errors"

	"github.com/tsuru/config"
)

const defaultManager = "gandalf"

var managers map[string]RepositoryManager

var (
	ErrKeyNotFound            = errors.New("key not found")
	ErrRepositoryNotFound     = errors.New("repository not found")
	ErrUserNotFound           = errors.New("user not found")
	ErrKeyAlreadyExists       = errors.New("user already have this key")
	ErrRepositoryAlreadExists = errors.New("repository already exists")
	ErrUserAlreadyExists      = errors.New("user already exists")
)

// Key represents a public key, that is added to a repository to allow access
// to it.
type Key struct {
	Name string
	Body string
}

// Repository represents a repository in the manager.
type Repository struct {
	Name         string
	ReadWriteURL string
}

// RepositoryManager represents a manager of application repositories.
type RepositoryManager interface {
	CreateUser(username string) error
	RemoveUser(username string) error

	GrantAccess(repository, user string) error
	RevokeAccess(repository, user string) error

	CreateRepository(name string, users []string) error
	RemoveRepository(name string) error
	GetRepository(name string) (Repository, error)

	Diff(repositoryName, fromVersion, toVersion string) (string, error)

	CommitMessages(repository, ref string, limit int) ([]string, error)
}

// KeyRepositoryManager is a RepositoryManager that is able to manage public
// SSH keys.
type KeyRepositoryManager interface {
	AddKey(username string, key Key) error
	UpdateKey(username string, key Key) error
	RemoveKey(username string, key Key) error
	ListKeys(username string) ([]Key, error)
}

// Manager returns the current configured manager, as defined in the
// configuration file.
func Manager() RepositoryManager {
	managerName, err := config.GetString("repo-manager")
	if err != nil {
		managerName = defaultManager
	}
	if _, ok := managers[managerName]; !ok {
		managerName = "nop"
	}
	return managers[managerName]
}

// Register registers a new repository manager, that can be later configured
// and used.
func Register(name string, manager RepositoryManager) {
	if managers == nil {
		managers = make(map[string]RepositoryManager)
	}
	managers[name] = manager
}


text:
#import <UIKit/UITableView.h>

@interface UITableView (SyntheticEvents)
- (id)_scriptingInfo;
@end


text:
package org.killbill.billing.payment.core.sm.control;

import org.joda.time.DateTime;
import org.killbill.automaton.OperationException;
import org.killbill.automaton.State;
import org.killbill.automaton.State.LeavingStateCallback;
import org.killbill.billing.payment.api.PluginProperty;
import org.killbill.billing.payment.api.TransactionType;
import org.killbill.billing.payment.core.sm.PaymentStateContext;
import org.killbill.billing.payment.core.sm.PluginControlPaymentAutomatonRunner;
import org.killbill.billing.payment.dao.PaymentAttemptModelDao;
import org.killbill.billing.payment.dao.PaymentDao;
import org.killbill.billing.payment.dao.PaymentModelDao;
import org.killbill.billing.payment.dao.PaymentTransactionModelDao;
import org.killbill.billing.payment.dao.PluginPropertySerializer;
import org.killbill.billing.payment.dao.PluginPropertySerializer.PluginPropertySerializerException;
import org.killbill.billing.util.UUIDs;

import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;

public class DefaultControlInitiated implements LeavingStateCallback {

    private final PluginControlPaymentAutomatonRunner pluginControlPaymentAutomatonRunner;
    private final PaymentStateControlContext stateContext;
    private final State initialState;
    private final State retriedState;
    private final TransactionType transactionType;
    private final PaymentDao paymentDao;

    public DefaultControlInitiated(final PluginControlPaymentAutomatonRunner pluginControlPaymentAutomatonRunner, final PaymentStateContext stateContext, final PaymentDao paymentDao,
                                   final State initialState, final State retriedState, final TransactionType transactionType) {
        this.pluginControlPaymentAutomatonRunner = pluginControlPaymentAutomatonRunner;
        this.paymentDao = paymentDao;
        this.initialState = initialState;
        this.retriedState = retriedState;
        this.stateContext = (PaymentStateControlContext) stateContext;
        this.transactionType = transactionType;
    }

    @Override
    public void leavingState(final State state) throws OperationException {
        final DateTime utcNow = pluginControlPaymentAutomatonRunner.getClock().getUTCNow();

        if (stateContext.getPaymentId() != null && stateContext.getPaymentExternalKey() == null) {
            final PaymentModelDao payment = paymentDao.getPayment(stateContext.getPaymentId(), stateContext.getInternalCallContext());
            Preconditions.checkNotNull(payment, "payment cannot be null for id " + stateContext.getPaymentId());
            stateContext.setPaymentExternalKey(payment.getExternalKey());
        } else if (stateContext.getPaymentExternalKey() == null) {
            stateContext.setPaymentExternalKey(UUIDs.randomUUID().toString());
        }
        if (stateContext.getTransactionId() != null && stateContext.getPaymentTransactionExternalKey() == null) {
            final PaymentTransactionModelDao paymentTransactionModelDao = paymentDao.getPaymentTransaction(stateContext.getTransactionId(), stateContext.getInternalCallContext());
            Preconditions.checkNotNull(paymentTransactionModelDao, "paymentTransaction cannot be null for id " + stateContext.getTransactionId());
            stateContext.setPaymentTransactionExternalKey(paymentTransactionModelDao.getTransactionExternalKey());
        } else if (stateContext.getPaymentTransactionExternalKey() == null) {
            stateContext.setPaymentTransactionExternalKey(UUIDs.randomUUID().toString());
        }

        if (state.getName().equals(initialState.getName()) || state.getName().equals(retriedState.getName())) {
            try {
                //
                // We don't serialize any properties at this stage to avoid serializing sensitive information.
                // However, if after going through the control plugins, the attempt end up in RETRIED state,
                // the properties will be serialized in the enteringState callback (any plugin that sets a
                // retried date is responsible to correctly remove sensitive information such as CVV, ...)
                //
                final byte[] serializedProperties = PluginPropertySerializer.serialize(ImmutableList.<PluginProperty>of());
                final PaymentAttemptModelDao attempt = new PaymentAttemptModelDao(stateContext.getAccount().getId(), stateContext.getPaymentMethodId(),
                                                                                utcNow, utcNow, stateContext.getPaymentExternalKey(), stateContext.getTransactionId(),
                                                                                stateContext.getPaymentTransactionExternalKey(), transactionType, initialState.getName(),
                                                                                stateContext.getAmount(), stateContext.getCurrency(),
                                                                                stateContext.getPaymentControlPluginNames(), serializedProperties);

                pluginControlPaymentAutomatonRunner.getPaymentDao().insertPaymentAttemptWithProperties(attempt, stateContext.getInternalCallContext());

                stateContext.setAttemptId(attempt.getId());
            } catch (final PluginPropertySerializerException e) {
                throw new OperationException(e);
            }
        }
    }
}


text:
Inspired by headless (the ruby gem) X-Recorder provides utils to
start Xvfb and record (as in video recording) X11 output based on a X DISPLAY id.

Primarily designed to be used as a bin its backed by a library you can use inside other node
libaries.

## Install

````sh
npm install x-recorder -g
````

## Comands

See `x-recorder --help` for an up to date list of sub commands.

### capture

Captures output of a shell script. Will create an Xvfb instance and run your script inside it
capturing the X Display via ffmpeg.

This command is useful in a CI environemnt where you want to capture the output of you
test command. The exit status, stdout, stderr output will be exactaly the same as the command
given in -s.

````sh
x-recorder capture -s "firefox google.com" -o $PWD/foo.mov
````

### start-xvfb

Starts Xvfb instance finds an available DISPLAY id.

Will echo display ID back to you.

````sh
x-recorder start-xvfb
````

### stop-xvfb

Stops Xvfb instance. Looks up its pid via /tmp/.X{ID}-lock

````sh
x-recorder stop-xvfb --display :99
````

### start-video

Records video from an already running DISPLAY.

````sh
x-recorder start-video --display :99 --pid $PWD/video.pid --output $PWD/out.mov
````

### stop-video

Stops video recording.

````sh
x-recorder stop-video --pid $PWD/video.pid
````

## LICENSE

MIT - See LICENSE.md


text:
// This file is automatically generated.

package adila.db;

/*
 * Samsung Galaxy Go Prime
 *
 * DEVICE: grandprimelteatt
 * MODEL: SAMSUNG-SM-G530A
 */
final class grandprimelteatt {
    public static final String DATA = "Samsung|Galaxy Go Prime|";
}


text:
using System;
using System.IO;
using System.Linq;
using System.Threading;
using Dev.Data.Configuration;
using Dev.Data.ContextStorage;
using Dev.Data.Test.Domain;
using Dev.Demo.Entities2.Models;
using Infrastructure.Tests.Data;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Dev.Data.Test
{
    [TestClass]
    public class UnitTestMutiThread
    {
        private CustomerRepository customerRepository;
        [TestInitialize]
        public void Init()
        {
            AppDomain.CurrentDomain.SetData("DataDirectory", Path.Combine(AppDomain.CurrentDomain.BaseDirectory, ""));

            //DbContextManager.InitStorage(new SimpleDbContextStorage());

            CommonConfig.Instance()
                .ConfigureDbContextStorage(new ThreadDbContextStorage())
                .ConfigureData<MyDbContext>("DefaultConnection")
                .ConfigureData<SysManagerContext>("DefaultConnection1");

            //config.ConfigureData<MyDbContext>("DefaultConnection");

            this.customerRepository = new CustomerRepository("DefaultConnection");

        }
        [TestMethod]
        public void TestMethod1()
        {

            for (int i = 0; i < 10; i++)
            {

                InThread(i);
            }

            Thread.Sleep(20 * 1000);

        }

        private void InThread(int i)
        {
            var t = new Thread(() =>
            {

                Console.WriteLine("start thread " + "=>" + i);
                //for (int i = 0; i < 10; i++)
                //{
                //    this.customerRepository.Add(
                //        new Customer { Firstname = "zbw911", Inserted = DateTime.Now, Lastname = "null" });
                //}

                try
                {
                    int list = this.customerRepository.GetQuery<Customer>().Count();
                    //this.customerRepository.UnitOfWork.SaveChanges();
                    Console.WriteLine(i + "=>" + list);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                    throw;
                }

            });

            t.IsBackground = true;

            t.Start();
        }
    }
}


text:
"""Tests for the Stationary Stochastic Per-Arm Bandit environment."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import numpy as np
import tensorflow as tf  # pylint: disable=g-explicit-tensorflow-version-import
from tf_agents.bandits.environments import stationary_stochastic_per_arm_py_environment as sspe
from tf_agents.policies import random_py_policy
from tf_agents.specs import array_spec

def normal_with_sigma_1_sampler(mu):
  return np.random.normal(mu, 1)

def check_unbatched_time_step_spec(time_step, time_step_spec, batch_size):
  """Checks if time step conforms array spec, even if batched."""
  if batch_size is None:
    return array_spec.check_arrays_nest(time_step, time_step_spec)

  return array_spec.check_arrays_nest(
      time_step, array_spec.add_outer_dims_nest(time_step_spec, (batch_size,)))

class LinearNormalReward(object):

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

  def __call__(self, x):
    mu = np.dot(x, self.theta)
    return np.random.normal(mu, 1)

class StationaryStochasticPerArmBanditPyEnvironmentTest(tf.test.TestCase):

  def test_with_uniform_context_and_normal_mu_reward(self):

    def _global_context_sampling_fn():
      return np.random.randint(-10, 10, [4])

    def _arm_context_sampling_fn():
      return np.random.randint(-2, 3, [5])

    reward_fn = LinearNormalReward([0, 1, 2, 3, 4, 5, 6, 7, 8])

    env = sspe.StationaryStochasticPerArmPyEnvironment(
        _global_context_sampling_fn,
        _arm_context_sampling_fn,
        6,
        reward_fn,
        batch_size=2)
    time_step_spec = env.time_step_spec()
    action_spec = array_spec.BoundedArraySpec(
        shape=(), minimum=0, maximum=5, dtype=np.int32)

    random_policy = random_py_policy.RandomPyPolicy(
        time_step_spec=time_step_spec, action_spec=action_spec)

    for _ in range(5):
      time_step = env.reset()
      print('time_step', time_step)
      print('time_step_spec', time_step_spec)
      self.assertTrue(
          check_unbatched_time_step_spec(
              time_step=time_step,
              time_step_spec=time_step_spec,
              batch_size=env.batch_size))

      action = random_policy.action(time_step).action
      self.assertAllEqual(action.shape, [2])
      self.assertAllGreaterEqual(action, 0)
      self.assertAllLess(action, 6)
      time_step = env.step(action)

  def test_with_variable_num_actions_featurized(self):

    def _global_context_sampling_fn():
      return np.random.randint(-10, 10, [4])

    def _arm_context_sampling_fn():
      return np.random.randint(-2, 3, [5])

    def _num_actions_fn():
      return np.random.randint(0, 7)

    reward_fn = LinearNormalReward([0, 1, 2, 3, 4, 5, 6, 7, 8])

    env = sspe.StationaryStochasticPerArmPyEnvironment(
        _global_context_sampling_fn,
        _arm_context_sampling_fn,
        6,
        reward_fn,
        _num_actions_fn,
        batch_size=2)
    time_step_spec = env.time_step_spec()
    action_spec = array_spec.BoundedArraySpec(
        shape=(), minimum=0, maximum=5, dtype=np.int32)

    random_policy = random_py_policy.RandomPyPolicy(
        time_step_spec=time_step_spec, action_spec=action_spec)

    for _ in range(5):
      time_step = env.reset()
      self.assertTrue(
          check_unbatched_time_step_spec(
              time_step=time_step,
              time_step_spec=time_step_spec,
              batch_size=env.batch_size))

      action = random_policy.action(time_step).action
      self.assertAllEqual(action.shape, [2])
      self.assertAllGreaterEqual(action, 0)
      self.assertAllLess(action, 6)
      time_step = env.step(action)

if __name__ == '__main__':
  tf.test.main()


text:
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>5.3. Domain Declaration</title>
<link rel="stylesheet" type="text/css" href="docbook.css">
<meta name="generator" content="DocBook XSL Stylesheets V1.79.1">
<meta name="keywords" content="MASL, Action Language, Action Semantics, UML, Unified Modelling Language, Shlaer Mellor">
<link rel="home" href="index.html" title="MASL Reference Manual">
<link rel="up" href="Domains.html" title="Chapter 5. Domains">
<link rel="prev" href="DomainsProjectDeclaration.html" title="5.2. Project Declaration">
<link rel="next" href="DomainsDomainMembers.html" title="5.4. Domain Members">
<link rel="preface" href="preface.html" title="Preface">
<link rel="chapter" href="Grammars.html" title="Chapter 1. Grammars">
<link rel="chapter" href="LexicalStructure.html" title="Chapter 2. Lexical Structure">
<link rel="chapter" href="Types.html" title="Chapter 3. Types">
<link rel="chapter" href="TypeConversion.html" title="Chapter 4. Type Conversion">
<link rel="chapter" href="Domains.html" title="Chapter 5. Domains">
<link rel="chapter" href="Objects.html" title="Chapter 6. Objects">
<link rel="chapter" href="Relationships.html" title="Chapter 7. Relationships">
<link rel="chapter" href="Lifecycles.html" title="Chapter 8. Lifecycles">
<link rel="chapter" href="Functions.html" title="Chapter 9. Functions">
<link rel="chapter" href="Services.html" title="Chapter 10. Services">
<link rel="chapter" href="Exceptions.html" title="Chapter 11. Exceptions">
<link rel="chapter" href="Statements.html" title="Chapter 12. Statements">
<link rel="chapter" href="Names.html" title="Chapter 13. Names">
<link rel="chapter" href="Expressions.html" title="Chapter 14. Expressions">
<link rel="appendix" href="LanguageDefinedCharacteristics.html" title="Appendix A. Language Defined Characteristics">
<link rel="appendix" href="SyntaxSummary.html" title="Appendix B. Syntax Summary">
<link rel="index" href="ix01.html" title="Index">

OFFICIAL

5.3. Domain Declaration

Prev
Chapter 5. Domains
 Next

5.3. Domain Declaration

A domain declaration

declares a new domain.

The declaration
specifies the name of the domain together with declarations of its members, that
is, types, exceptions, objects, domain services and relationships.

[78]

        domain declaration

=

        'domain',
        domain name,
        'is',
        {domain declarative item},
        'end', ['domain'], ';'
    ;

[79]

        domain name

=

        identifier,
    ;

Prev
Up
 Next

5.2. Project Declaration

Home | ToC

 5.4. Domain Members

OFFICIAL


text: module.exports={"dependencies":{"nl.fokkezb.drawer":"*"}};


text:
package library

import (
	"github.com/garyburd/redigo/redis"
	"logger"
)

type RedisHash struct {
	redis_connection redis.Conn
	hash_name        string
	page_size        int
}

var redisHash map[string]*RedisHash

const (
	prefixhash = "hash-"
)

func GetRedisHashInstance(hashName string) *RedisHash {
	if redisHash == nil {
		redisHash = make(map[string]*RedisHash)
	}
	if redisHash[hashName] == nil {
		hashInstance := newRedisHash()
		redisHash[hashName] = hashInstance
		redisHash[hashName].hash_name = prefixhash + hashName
	}
	return redisHash[hashName]
}

func newRedisHash() *RedisHash {
	return &RedisHash{}
}

func (r *RedisHash) GetRedisConnection() redis.Conn {
	if r.redis_connection == nil {
		r.redis_connection = NewRedisConnectionPool().GetConnection()
	}
	return r.redis_connection
}

func (r *RedisHash) CloseConn() {
	redisConn := r.GetRedisConnection()
	if redisConn != nil {
		redisConn.Close()
	}
}

func (r *RedisHash) AddHashValue(key string, value string) {
	if r.redis_connection != nil {
		_, err := r.redis_connection.Do("HSET", r.hash_name, key, value)
		if err != nil {
			logger.Get().Debug("Error is : " + err.Error())
		}
	}
}

func (r *RedisHash) RemoveHashValue(key string) {
	if r.redis_connection != nil {
		_, err := r.redis_connection.Do("HDEL", r.hash_name, key)
		if err != nil {
			logger.Get().Debug("Error is : " + err.Error())
		}
	}
}

func (r *RedisHash) TotalValue() int {
	if r.redis_connection != nil {
		count, err := redis.Int(r.redis_connection.Do("HGETALL", r.hash_name))
		if err != nil {
			logger.Get().Debug("Error is : " + err.Error())
		}
		return count
	}
	return 0
}

func (r *RedisHash) GetHashValue(key string) string {
	if r.redis_connection != nil {
		value, err := redis.String(r.redis_connection.Do("HGET", r.hash_name, key))
		if err != nil {
			logger.Get().Debug("Error is : " + err.Error())
		}
		return value
	}
	return ""
}

func (r *RedisHash) SetHashFromMap(mapValues map[string]string) {
	if r.redis_connection != nil {
		r.redis_connection.Send("MULTI")
		for key := range mapValues {
			r.redis_connection.Send("HSET", r.hash_name, key, mapValues[key])
		}
		_, err := r.redis_connection.Do("EXEC")
		if err != nil {
			logger.Get().Debug("Error is : " + err.Error())
		}
	}
}


text:
'use strict';

var bookapp = angular.module('bookapp');

bookapp.config(function config( $stateProvider ) {
    $stateProvider.state( 'authors', {
        url: '/authors',
        templateUrl: 'pages/authors.tpl.html'
    });
});

bookapp.controller('AuthorController', function ($scope, Author) {
    $scope.currentAuthor = new Author();
    $scope.authors = Author.query();
    $scope.showId = false;

    $scope.cancel = function () {
        $scope.currentAuthor = new Author();
    };

    $scope.save = function () {
        var isNew = $scope.currentAuthor.id == null;
        if (isNew) {
            $scope.currentAuthor = Author.save($scope.currentAuthor);
            $scope.authors.push($scope.currentAuthor);
        } else {
            $scope.currentAuthor = Author.update($scope.currentAuthor);
        }
        $scope.cancel();
    };

    $scope.edit = function (author) {
        $scope.currentAuthor = author;
    };

    $scope.remove = function (index, id) {
        $scope.authors.splice(index, 1);
        Author.remove({authorId: id});
    };
});

bookapp.factory('Author', function ($resource) {
    return $resource('rest/authors/:authorId', {authorId: '@id'}, {
        'update': {method: 'PUT'}
    });
});


text:
Generic SDL2-based template game using entityx and glm.

## Requirements

* sdl2
* sdl2_gfx
* sdl2_image
* sdl2_mixer
* sdl2_ttf
* cmake
* git
* emscripten (optionally)
* python (optionally)
* clang (optionally)

## Instructions

0. Make your own git repo
1. Copy the contents of the `base_game` directory into your repo
2. Navigate into your repo
3. `git submodule add git@github.com:svenstaro/strapon.git strapon`
4. `git submodule add git@github.com:alecthomas/entityx.git entityx`
5. `git submodule add git@github.com:g-truc/glm.git glm`
6. Type `make`


text:
Content for adding to build.gradle

    repositories {
        mavenCentral()
    }

    dependencies {
        classpath "com.github.nrudenko:anarcho-gradle:0.2.2"
    }

    apply plugin: "anarcho"

    anarcho {
        host = "{{ host }}"
        buildTypes {
            defaultConfig {
                appKey = "{{ appKey }}"
                apiToken = "{{ apiToken }}"
                releaseNotes = "BuildType: {build_type} Branch: {git_branch} Commit: {git_commit}"
            }
    }


text:
package com.radishsystems.choiceview.webapi;

import static org.junit.Assert.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.MethodNotSupportedException;
import org.apache.http.ProtocolException;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.localserver.LocalTestServer;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpRequestHandler;
import org.apache.http.util.EntityUtils;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

public class ChoiceViewSessionTest {

	static class Link {
		public String rel;
		public String href;
		public Link(String rel, String href) {
			this.rel = rel;
			this.href = href;
		}
	}
	static class Property {
		public String name;
		public String value;
		public Property() { this("", ""); }
		public Property(String name, String value) {
			this.name = name;
			this.value = value;
		}
	}
	static class Session {
		public int sessionId;
		public String callerId;
		public String callId;
		public String status;
		public String networkQuality;
		public String networkType;
		final public Map<String, String> properties;
		final public List<Link> links;
		public Session() {
			sessionId = expectedSessionId;
			status = "connected";
			networkQuality = "excellent";
			networkType = "WiFi";
			properties = new HashMap<String, String>();
			properties.put("TestKey1", "TestValue");
			properties.put("TestKey2", "TestValue");
			links = new ArrayList<Link>();
		}
	}
	static class Payload {
		final public Map<String, String> properties;
		final public List<Link> links;
		public Payload() {
			properties = new HashMap<String, String>();
			properties.put("TestKey1", "UpdatedTestValue");
			properties.put("TestKey2", "UpdatedTestValue");
			links = new ArrayList<Link>();
		}
	}

	final static int expectedSessionId = 1001;
	final static String expectedCallerId = "7202950840";
	final static String expectedCallId = "12345";
	final static String expectedStateChangeUrl = "http://test.ivr.com/1001/state_change";
	final static String expectedNewMessageUrl = "http://test.ivr.com/1001/new_message";
	final static Map<String, String> expectedControlMessage = new HashMap<String, String>();

	private ChoiceViewSession testSession;
	private LocalTestServer testServer;
	private ObjectMapper mapper;

	private boolean activeSession = false;
	private boolean controlMessageAvailable = false;

	private HttpRequestHandler sessionsHandler = new HttpRequestHandler() {
		public void handle(HttpRequest request, HttpResponse response,
				HttpContext context) throws HttpException, IOException {
			String method = request.getRequestLine().getMethod().toUpperCase();
			if(method.equals("PUT") || method.equals("GET")) {
				throw new MethodNotSupportedException(method + " request not supported for sessions");
			}
			if(method.equals("DELETE")) {
				response.setStatusCode(403);
			}
			if(method.equals("POST")) {
				String content = null;
				Map<String, String> params = null;
				String requestUri = request.getRequestLine().getUri();
				String selfUri = "http://" + testServer.getServiceAddress().getHostName() +
						":" + testServer.getServiceAddress().getPort() + "/" +
						requestUri.substring(0, requestUri.length()-1) + "/" + expectedSessionId;
				if(request instanceof HttpEntityEnclosingRequest) {
	                HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();
	                content = EntityUtils.toString(entity);
				}
				if(content != null) {
	                if(request.containsHeader("Content-Type")) {
	                	String value = request.getFirstHeader("Content-Type").getValue();
	                	if(value == null) {
	    					throw new ProtocolException("No content type specified in POST request!");
	                	}
	                	if(value.toUpperCase().contains("JSON")) {
							params = mapper.readValue(content,
									new TypeReference<Map<String, String>>() {});
	                	} else {
	                		throw new ProtocolException("Content is not json!");
	                	}
	                } else {
	                	throw new ProtocolException("No Content-Type header!");
	                }
				}
				if(params == null) {
					throw new ProtocolException("No content in POST request!");
				}

				if(params.containsKey("callerId") && params.get("callerId") != null) {
					response.setStatusCode(201);
					Session session = new Session();
					session.callerId = params.get("callerId");
					session.callId = params.containsKey("callId") ? params.get("callId") : "";
					session.links.add(new Link("self",selfUri));
					session.links.add(new Link(ChoiceViewSession.ControlMessageRel,
							          selfUri + "/controlmessage"));
					session.links.add(new Link(ChoiceViewSession.PayloadRel,
					          selfUri + "/properties"));
					response.setEntity(new StringEntity(mapper.writeValueAsString(session),
							ContentType.create("application/json", "utf-8")));
					activeSession = true;
					controlMessageAvailable = true;
				} else {
					throw new ProtocolException("No caller id in POST request content!");
				}
			}
		}
	};

	private HttpRequestHandler sessionHandler = new HttpRequestHandler() {
		public void handle(HttpRequest request, HttpResponse response,
				HttpContext context) throws HttpException, IOException {
			String method = request.getRequestLine().getMethod().toUpperCase();
			if(method.equals("PUT")) {
				throw new MethodNotSupportedException("PUT request not supported for sessions");
			}
			if(method.equals("DELETE")) {
				if(activeSession) {
					activeSession = false;
					controlMessageAvailable = false;
					response.setStatusCode(200);
				} else {
					response.setStatusCode(404);
				}
			}
			if(method.equals("GET")) {
				if(!activeSession) {
					response.setStatusCode(404);
					return;
				}
				String sessionUri = "http://" + testServer.getServiceAddress().getHostName() + ":" +
						testServer.getServiceAddress().getPort() + "/" +
						request.getRequestLine().getUri();
				response.setStatusCode(200);
				Session session = new Session();
				session.callerId = expectedCallerId;
				session.callId = expectedCallId;
				session.links.add(new Link("self", sessionUri));
				session.links.add(new Link(ChoiceViewSession.ControlMessageRel,
						          sessionUri + "/controlmessage"));
				session.links.add(new Link(ChoiceViewSession.PayloadRel,
				          sessionUri + "/properties"));
				if(request.containsHeader("ACCEPT")) {
					String acceptHeader = request.getFirstHeader("ACCEPT").getValue();
					if(acceptHeader != null && !acceptHeader.toUpperCase().contains("JSON")) {
						throw new ProtocolException(acceptHeader + " type not supported!");
					}
				}
				response.setEntity(new StringEntity(mapper.writeValueAsString(session),
						ContentType.create("application/json", "utf-8")));
				return;
			}
			if(method.equals("POST")) {
				if(!activeSession) {
					response.setStatusCode(404);
					return;
				}
				String content = null;
				if(request instanceof HttpEntityEnclosingRequest) {
	                HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();
	                content = EntityUtils.toString(entity);
					if(content == null) {
						throw new ProtocolException("Cannot retrieve content from POST request!");
					}
	                if(request.containsHeader("Content-Type")) {
	                	String value = request.getFirstHeader("Content-Type").getValue().toLowerCase();
	                	if(value == null) {
	    					throw new ProtocolException("No content type specified in POST request!");
	                	}
	                	if(value.contains("application/json")) {
	        				Map<String, String> params = mapper.readValue(content,
	    							new TypeReference<Map<String, String>>() {});
	        				if(params.keySet().size() != 1 || !params.containsKey("url")) {
	    						throw new ProtocolException("No url in POST request!");
	        				}
	                	}
	                	response.setStatusCode(200);
	                } else {
		                throw new ProtocolException("No content-type header in POST request!");
	                }
				} else {
					throw new ProtocolException("No content in POST request!");
				}
				return;
			}
		}
	};

	private HttpRequestHandler propertiesHandler = new HttpRequestHandler() {
		public void handle(HttpRequest request, HttpResponse response,
				HttpContext context) throws HttpException, IOException {
			String method = request.getRequestLine().getMethod().toUpperCase();
			if(method.equals("PUT")) {
				throw new MethodNotSupportedException("PUT request not supported for properties");
			}
			if(method.equals("DELETE")) {
				throw new MethodNotSupportedException("DELETE request not supported for properties");
			}
			if(method.equals("GET")) {
				if(!activeSession) {
					response.setStatusCode(404);
					return;
				}
				String payloadUri = "http://" + testServer.getServiceAddress().getHostName() + ":" +
						testServer.getServiceAddress().getPort() + request.getRequestLine().getUri();
				String sessionUri = payloadUri.replace("/properties", "");
				Payload payload = new Payload();
				payload.links.add(new Link("self", payloadUri));
				payload.links.add(new Link(ChoiceViewSession.SessionRel,
						          sessionUri));
				if(request.containsHeader("ACCEPT")) {
					String acceptHeader = request.getFirstHeader("ACCEPT").getValue();
					if(acceptHeader != null && !acceptHeader.toUpperCase().contains("JSON")) {
						throw new ProtocolException(acceptHeader + " type not supported!");
					}
				}
				response.setEntity(new StringEntity(mapper.writeValueAsString(payload),
						ContentType.create("application/json", "utf-8")));
            	response.setStatusCode(200);
				return;
			}
			if(method.equals("POST")) {
				if(!activeSession) {
					response.setStatusCode(404);
					return;
				}
				String content = null;
				if(request instanceof HttpEntityEnclosingRequest) {
	                HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();
	                content = EntityUtils.toString(entity);
					if(content == null) {
						throw new ProtocolException("Cannot retrieve content from POST request!");
					}
	                if(request.containsHeader("Content-Type")) {
	                	String value = request.getFirstHeader("Content-Type").getValue().toLowerCase();
	                	if(value == null) {
	    					throw new ProtocolException("No content type specified in POST request!");
	                	}
	                	if(value.contains("application/json")) {
	        				Map<String, String> params = mapper.readValue(content,
	        						new TypeReference<Map<String, String>>() {});
	        				if(params != null && params.size() == 2 && params.containsKey("name")) {
			                	response.setStatusCode(200);
			                	return;
	        				}
	                	}
						throw new ProtocolException("No client property in POST request!");
	                } else {
		                throw new ProtocolException("No content-type header in POST request!");
	                }
				} else {
					throw new ProtocolException("No content in POST request!");
				}
			}
		}
	};

	private HttpRequestHandler controlMessageHandler = new HttpRequestHandler() {
		public void handle(HttpRequest request, HttpResponse response,
				HttpContext context) throws HttpException, IOException {
			String method = request.getRequestLine().getMethod().toUpperCase();
			if(method.equals("PUT")) {
				throw new MethodNotSupportedException("PUT request not supported for control message");
			}
			if(method.equals("DELETE")) {
				if(activeSession) {
					if(controlMessageAvailable) {
						response.setStatusCode(200);
						controlMessageAvailable = false;
					} else {
						response.setStatusCode(304);
					}
				} else {
					response.setStatusCode(404);
				}
			}
			if(method.equals("GET")) {
				if(!activeSession) {
					response.setStatusCode(404);
				} else {
					response.setStatusCode(200);
					if(controlMessageAvailable) {
						response.setEntity(new StringEntity(mapper.writeValueAsString(expectedControlMessage),
								ContentType.create("application/json", "utf-8")));
					}
				}
			}
			if(method.equals("POST")) {
				throw new MethodNotSupportedException("POST request not supported for control message");
			}
		}
	};

	private HttpRequestHandler transferHandler = new HttpRequestHandler() {
		public void handle(HttpRequest request, HttpResponse response,
				HttpContext context) throws HttpException, IOException {
			String method = request.getRequestLine().getMethod().toUpperCase();
			if(method.equals("PUT")) {
				throw new MethodNotSupportedException("PUT request not supported for transfers");
			}
			if(method.equals("DELETE")) {
				throw new MethodNotSupportedException("DELETE request not supported for transfers");
			}
			if(method.equals("GET")) {
				throw new MethodNotSupportedException("GET request not supported for transfers");
			}
			if(method.equals("POST")) {
				if(activeSession) {
					activeSession = false;
					response.setStatusCode(200);
				} else {
					response.setStatusCode(404);
				}
			}
		}
	};

	@BeforeClass
	public static void onlyOnce() {
		expectedControlMessage.put("MenuNumber", "1");
		expectedControlMessage.put("MenuName", "Radish_Main_Menu");
		expectedControlMessage.put("ButtonNumber", "0");
		expectedControlMessage.put("ButtonName", "ChoiceView+Demo");
	}

	@Before
	public void setUp() throws Exception {
		mapper = new ObjectMapper();

		testServer = new LocalTestServer(null, null);
		String baseUri = "/ivr/api/session/";
		String sessionUri = baseUri + expectedSessionId;
		testServer.register("/ivr/api/sessions", sessionsHandler);
		testServer.register(sessionUri, sessionHandler);
		testServer.register(sessionUri + "/controlmessage", controlMessageHandler);
		testServer.register(sessionUri + "/properties", propertiesHandler);
		testServer.register(sessionUri + "/transfer/*", transferHandler);
		testServer.start();

		testSession = new ChoiceViewSession(testServer.getServiceAddress().getHostName(),
				testServer.getServiceAddress().getPort(), false);
	}

	@Test
	public void testStartSession() throws IOException {
		assertTrue(testSession.startSession(expectedCallerId, expectedCallId));
		assertEquals(expectedSessionId, testSession.getSessionId());
		assertEquals(expectedCallerId, testSession.getCallerId());
		assertEquals(expectedCallId, testSession.getCallId());
	}

	@Test
	public void testStartSessionWithGoodUrls() throws IOException {
		assertTrue(testSession.startSession(expectedCallerId, expectedCallId, expectedStateChangeUrl, expectedNewMessageUrl, "basic"));
		assertEquals(expectedSessionId, testSession.getSessionId());
		assertEquals(expectedCallerId, testSession.getCallerId());
		assertEquals(expectedCallId, testSession.getCallId());
	}

	@Test(expected=IllegalArgumentException.class)
	public void testStartSessionWithGoodUrlsAndBadNotificationType() throws IOException {
		assertTrue(testSession.startSession(expectedCallerId, expectedCallId, expectedStateChangeUrl, expectedNewMessageUrl, "badType"));
	}

	@Test(expected=IllegalArgumentException.class)
	public void testStartSessionWithBadUrls() throws IOException {
		assertFalse(testSession.startSession(expectedCallerId, expectedCallId, "Bad url 1", "Bad url 2", "ccxml"));
	}

	@Test(expected=IllegalArgumentException.class)
	public void testStartSessionWithOpaqueUrls() throws IOException {
		assertFalse(testSession.startSession(expectedCallerId, expectedCallId, "mailto:dfjacobs@yahoo.com", "mailto:dfjacobs@sshores.com", "basic"));
	}

	@Test
	public void testEndSession() throws IOException {
		// EndSession fails if no session
		assertFalse(testSession.endSession());

		// EndSession succeeds if the session is active
		assertTrue(testSession.startSession(expectedCallerId, expectedCallId));
		assertTrue(testSession.endSession());
		// EndSession fails if the session is not active
		assertFalse(testSession.endSession());
	}

	@Test
	public void testUpdateSessionWhenIVREndsSession() throws IOException {
		// UpdateSession fails if no session
		assertFalse(testSession.updateSession());

		// UpdateSession succeeds if session is started
		assertTrue(testSession.startSession(expectedCallerId, expectedCallId));
		assertTrue(testSession.updateSession());
		assertEquals(expectedSessionId, testSession.getSessionId());
		assertEquals(expectedCallerId, testSession.getCallerId());
		assertEquals(expectedCallId, testSession.getCallId());
		// UpdateSession succeeds if the session has ended
		assertTrue(testSession.endSession());
		assertTrue(testSession.updateSession());
		assertTrue("disconnected".equals(testSession.getStatus()));
	}

	@Test
	public void testUpdateSessionWhenSwitchEndsSession() throws IOException {
		// UpdateSession succeeds if the session is ended by the server
		assertTrue(testSession.startSession(expectedCallerId, expectedCallId));
		assertTrue("connected".equals(testSession.getStatus()));
		activeSession = false;
		assertTrue(testSession.updateSession());
		assertTrue("disconnected".equals(testSession.getStatus()));
	}

	@Test
	public void testTransferSessionWithBadAccountId() throws IOException {
		String badAccountId = "";

		assertTrue(testSession.startSession(expectedCallerId, expectedCallId));

		// TransferSession fails if accountId is not specified
		assertFalse(testSession.transferSession(badAccountId));
		assertFalse(testSession.transferSession(null));
	}

	@Test
	public void testTransferSessionWithGoodAccountId() throws IOException {
		String expectedAccountId = "test1";

		// TransferSession fails if no session
		assertFalse(testSession.transferSession(expectedAccountId));

		assertTrue(testSession.startSession(expectedCallerId, expectedCallId));

		// TransferSession succeeds if the session is active
		assertTrue(testSession.transferSession(expectedAccountId));
		// After successful TransferSession, connection state is disconnected
		assertTrue(testSession.getStatus().equals("disconnected"));
		// TransferSession fails if session has ended
		assertFalse(testSession.transferSession(expectedAccountId));
	}

	@Test
	public void testSendUrl() throws IOException {
		// SendUrl fails if no session
		assertFalse(testSession.sendUrl("http://www.radishsystems.com/"));

		assertTrue(testSession.startSession(expectedCallerId, expectedCallId));
		// SendUrl fails if no url
		assertFalse(testSession.sendUrl(""));
		assertFalse(testSession.sendUrl(null));
		// SendUrl succeeds if url is specified
		assertTrue(testSession.sendUrl("http://www.radishsystems.com/"));
		// SendUrl fails if session has ended
		assertTrue(testSession.endSession());
		assertFalse(testSession.sendUrl("http://www.radishsystems.com/"));
	}

	@Test
	public void testSendText() throws IOException {
		// SendText fails if no session
		assertFalse(testSession.sendText("How may I help you?"));

		assertTrue(testSession.startSession(expectedCallerId, expectedCallId));
		// SendText fails if no text
		assertFalse(testSession.sendText(""));
		assertFalse(testSession.sendText(null));
		// SendText succeeds if text is specified
		assertTrue(testSession.sendText("How may I help you?"));
		// SendText fails if session has ended
		assertTrue(testSession.endSession());
		assertFalse(testSession.sendText("How may I help you?"));
	}

	@Test
	public void testGetControlMessage() throws IOException {
		// GetControlMessage returns null if no session
		assertNull(testSession.getControlMessage());
		assertTrue(testSession.startSession(expectedCallerId, expectedCallId));
		// GetControlMessage returns message if session is active
		Map<String, String> actualControlMessage = testSession.getControlMessage();
		assertEquals(expectedControlMessage, actualControlMessage);
		// Once GetControlMessage reads the message, it is cleared
		assertNull(testSession.getControlMessage());
		// GetControlMessage returns null if session has ended
		controlMessageAvailable = true;
		assertTrue(testSession.endSession());
		assertNull(testSession.getControlMessage());
	}

	@Test
	public void testClearControlMessage() throws IOException {
		// ClearControlMessage fails if no session
		assertFalse(testSession.clearControlMessage());

		// ClearControlMessage succeeds if the session is active
		assertTrue(testSession.startSession(expectedCallerId, expectedCallId));
		assertTrue(testSession.clearControlMessage());
		// ClearControlMessage fails if there is no message
		assertFalse(testSession.clearControlMessage());
		// ClearControlMessage fails if session has ended
		controlMessageAvailable = true;
		assertTrue(testSession.endSession());
		assertFalse(testSession.clearControlMessage());
	}

	@Test
	public void testUpdateProperties() throws IOException {
		final Map<String, String> expectedProperties = new HashMap<String, String>();
		expectedProperties.put("TestKey1", "UpdatedTestValue");
		expectedProperties.put("TestKey2", "UpdatedTestValue");

		// UpdateProperties fails if no session
		assertNull(testSession.updateProperties());
		// UpdateProperties succeeds if the session is active
		assertTrue(testSession.startSession(expectedCallerId, expectedCallId));
		Map<String, String> actualProperties = testSession.updateProperties();
		assertEquals(expectedProperties, actualProperties);
		// UpdateProperties returns null if session has ended
		assertTrue(testSession.endSession());
		assertNull(testSession.updateProperties());
	}

	@Test
	public void testAddProperties() throws IOException {
		final Map<String, String> duplicateProperties = new HashMap<String, String>();
		duplicateProperties.put("TestKey1", "UpdatedTestValue");
		duplicateProperties.put("TestKey2", "UpdatedTestValue");

		final Map<String, String> goodProperties = new HashMap<String, String>();
		goodProperties.put("TestKey3", "NewTestValue");
		goodProperties.put("TestKey4", "NewTestValue");

		final Map<String, String> goodProperties2 = new HashMap<String, String>();
		goodProperties2.put("TestKey5", "NewTestValue");
		goodProperties2.put("TestKey6", "NewTestValue");

		// AddProperties fails if no session
		assertFalse(testSession.addProperties(duplicateProperties));
		// AddProperties succeeds if the session is active
		assertTrue(testSession.startSession(expectedCallerId, expectedCallId));
		assertFalse(testSession.addProperties(duplicateProperties));
		assertTrue(testSession.addProperties(goodProperties));
		// AddProperties fails if session is ended
		assertTrue(testSession.endSession());
		assertFalse(testSession.addProperties(goodProperties2));
	}

	@Test
	public void testAddProperty() throws IOException {
		String badName = "TestKey1";
		String goodName = "TestKey3";
		String goodName2 = "TestKey4";
		String testValue = "TestValue";

		// AddProperty fails if no session
		assertFalse(testSession.addProperty(goodName, testValue));
		// AddProperty succeeds if the session is active
		assertTrue(testSession.startSession(expectedCallerId, expectedCallId));
		assertFalse(testSession.addProperty(badName, testValue));
		assertTrue(testSession.addProperty(goodName, testValue));
		// AddProperty fails if the session is ended
		assertTrue(testSession.endSession());
		assertFalse(testSession.addProperty(goodName2, testValue));
	}

	@After
	public void tearDown() throws Exception {
		testServer.stop();
	}
}


text:
<?php
namespace Chaos\ORM;

use ArrayIterator;
use IteratorAggregate;

/**
 * The Query wrapper.
 */
class Buffer implements IteratorAggregate
{
    /**
     * The data.
     *
     * @var mixed
     */
    protected $_data = [];

    /**
     * Creates a new record object with default values.
     *
     * @param mixed $handler The handler.
     */
    public function __construct($handler)
    {
        $this->_handler = $handler;
    }

    /**
     * Log calls
     */
    public function __call($name, $params = [])
    {
        $this->_data[$name][] = $params;
    }

    /**
     * Executes the query and returns the result (must implements the `Iterator` interface).
     *
     * (Automagically called on `foreach`)
     *
     * @return object An iterator instance.
     */
    public function getIterator()
    {
        $data = $this->get();
        return is_array($data) ? new ArrayIterator($data) : $data;
    }

    /**
     * Executes the query and returns the result.
     *
     * @param  array  $options The fetching options.
     * @return object          An iterator instance.
     */
    public function get($options = [])
    {
        $handler = $this->_handler;
        return $handler($this->_data, $options);
    }

    /**
     * Alias for `get()`
     *
     * @return object An iterator instance.
     */
    public function all($options = [])
    {
        return $this->get($options);
    }

    /**
     * Executes the query and returns the first result only.
     *
     * @return object An entity instance.
     */
    public function first($options = [])
    {
        $result = $this->get($options);
        return is_object($result) ? $result->rewind() : reset($result);
    }

    /**
     * Executes the query and returns the count number.
     *
     * @return integer The number of rows in result.
     */
    public function count()
    {
        return (int) count($this->get());
    }
}