text:
/* this file has been autogenerated by vtkNodeJsWrap */
/* editing this might proof futile */

#define VTK_WRAPPING_CXX
#define VTK_STREAMS_FWD_ONLY
#include <nan.h>

#include "vtkWidgetRepresentationWrap.h"
#include "vtkAngleRepresentationWrap.h"
#include "vtkObjectWrap.h"
#include "vtkHandleRepresentationWrap.h"
#include "../../plus/plus.h"

using namespace v8;

extern Nan::Persistent<v8::Object> vtkNodeJsNoWrap;
Nan::Persistent<v8::FunctionTemplate> VtkAngleRepresentationWrap::ptpl;

VtkAngleRepresentationWrap::VtkAngleRepresentationWrap()
{ }

VtkAngleRepresentationWrap::VtkAngleRepresentationWrap(vtkSmartPointer<vtkAngleRepresentation> _native)
{ native = _native; }

VtkAngleRepresentationWrap::~VtkAngleRepresentationWrap()
{ }

void VtkAngleRepresentationWrap::Init(v8::Local<v8::Object> exports)
{
	Nan::SetAccessor(exports, Nan::New("vtkAngleRepresentation").ToLocalChecked(), ConstructorGetter);
	Nan::SetAccessor(exports, Nan::New("AngleRepresentation").ToLocalChecked(), ConstructorGetter);
}

void VtkAngleRepresentationWrap::ConstructorGetter(
	v8::Local<v8::String> property,
	const Nan::PropertyCallbackInfo<v8::Value>& info)
{
	InitPtpl();
	info.GetReturnValue().Set(Nan::New(ptpl)->GetFunction());
}

void VtkAngleRepresentationWrap::InitPtpl()
{
	if (!ptpl.IsEmpty()) return;
	v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New);
	VtkWidgetRepresentationWrap::InitPtpl( );
	tpl->Inherit(Nan::New<FunctionTemplate>(VtkWidgetRepresentationWrap::ptpl));
	tpl->SetClassName(Nan::New("VtkAngleRepresentationWrap").ToLocalChecked());
	tpl->InstanceTemplate()->SetInternalFieldCount(1);

	Nan::SetPrototypeMethod(tpl, "ArcVisibilityOff", ArcVisibilityOff);
	Nan::SetPrototypeMethod(tpl, "arcVisibilityOff", ArcVisibilityOff);

	Nan::SetPrototypeMethod(tpl, "ArcVisibilityOn", ArcVisibilityOn);
	Nan::SetPrototypeMethod(tpl, "arcVisibilityOn", ArcVisibilityOn);

	Nan::SetPrototypeMethod(tpl, "BuildRepresentation", BuildRepresentation);
	Nan::SetPrototypeMethod(tpl, "buildRepresentation", BuildRepresentation);

	Nan::SetPrototypeMethod(tpl, "CenterWidgetInteraction", CenterWidgetInteraction);
	Nan::SetPrototypeMethod(tpl, "centerWidgetInteraction", CenterWidgetInteraction);

	Nan::SetPrototypeMethod(tpl, "ComputeInteractionState", ComputeInteractionState);
	Nan::SetPrototypeMethod(tpl, "computeInteractionState", ComputeInteractionState);

	Nan::SetPrototypeMethod(tpl, "GetArcVisibility", GetArcVisibility);
	Nan::SetPrototypeMethod(tpl, "getArcVisibility", GetArcVisibility);

	Nan::SetPrototypeMethod(tpl, "GetCenterRepresentation", GetCenterRepresentation);
	Nan::SetPrototypeMethod(tpl, "getCenterRepresentation", GetCenterRepresentation);

	Nan::SetPrototypeMethod(tpl, "GetClassName", GetClassName);
	Nan::SetPrototypeMethod(tpl, "getClassName", GetClassName);

	Nan::SetPrototypeMethod(tpl, "GetLabelFormat", GetLabelFormat);
	Nan::SetPrototypeMethod(tpl, "getLabelFormat", GetLabelFormat);

	Nan::SetPrototypeMethod(tpl, "GetPoint1Representation", GetPoint1Representation);
	Nan::SetPrototypeMethod(tpl, "getPoint1Representation", GetPoint1Representation);

	Nan::SetPrototypeMethod(tpl, "GetPoint2Representation", GetPoint2Representation);
	Nan::SetPrototypeMethod(tpl, "getPoint2Representation", GetPoint2Representation);

	Nan::SetPrototypeMethod(tpl, "GetRay1Visibility", GetRay1Visibility);
	Nan::SetPrototypeMethod(tpl, "getRay1Visibility", GetRay1Visibility);

	Nan::SetPrototypeMethod(tpl, "GetRay2Visibility", GetRay2Visibility);
	Nan::SetPrototypeMethod(tpl, "getRay2Visibility", GetRay2Visibility);

	Nan::SetPrototypeMethod(tpl, "GetTolerance", GetTolerance);
	Nan::SetPrototypeMethod(tpl, "getTolerance", GetTolerance);

	Nan::SetPrototypeMethod(tpl, "GetToleranceMaxValue", GetToleranceMaxValue);
	Nan::SetPrototypeMethod(tpl, "getToleranceMaxValue", GetToleranceMaxValue);

	Nan::SetPrototypeMethod(tpl, "GetToleranceMinValue", GetToleranceMinValue);
	Nan::SetPrototypeMethod(tpl, "getToleranceMinValue", GetToleranceMinValue);

	Nan::SetPrototypeMethod(tpl, "InstantiateHandleRepresentation", InstantiateHandleRepresentation);
	Nan::SetPrototypeMethod(tpl, "instantiateHandleRepresentation", InstantiateHandleRepresentation);

	Nan::SetPrototypeMethod(tpl, "IsA", IsA);
	Nan::SetPrototypeMethod(tpl, "isA", IsA);

	Nan::SetPrototypeMethod(tpl, "NewInstance", NewInstance);
	Nan::SetPrototypeMethod(tpl, "newInstance", NewInstance);

	Nan::SetPrototypeMethod(tpl, "Ray1VisibilityOff", Ray1VisibilityOff);
	Nan::SetPrototypeMethod(tpl, "ray1VisibilityOff", Ray1VisibilityOff);

	Nan::SetPrototypeMethod(tpl, "Ray1VisibilityOn", Ray1VisibilityOn);
	Nan::SetPrototypeMethod(tpl, "ray1VisibilityOn", Ray1VisibilityOn);

	Nan::SetPrototypeMethod(tpl, "Ray2VisibilityOff", Ray2VisibilityOff);
	Nan::SetPrototypeMethod(tpl, "ray2VisibilityOff", Ray2VisibilityOff);

	Nan::SetPrototypeMethod(tpl, "Ray2VisibilityOn", Ray2VisibilityOn);
	Nan::SetPrototypeMethod(tpl, "ray2VisibilityOn", Ray2VisibilityOn);

	Nan::SetPrototypeMethod(tpl, "SafeDownCast", SafeDownCast);
	Nan::SetPrototypeMethod(tpl, "safeDownCast", SafeDownCast);

	Nan::SetPrototypeMethod(tpl, "SetArcVisibility", SetArcVisibility);
	Nan::SetPrototypeMethod(tpl, "setArcVisibility", SetArcVisibility);

	Nan::SetPrototypeMethod(tpl, "SetHandleRepresentation", SetHandleRepresentation);
	Nan::SetPrototypeMethod(tpl, "setHandleRepresentation", SetHandleRepresentation);

	Nan::SetPrototypeMethod(tpl, "SetLabelFormat", SetLabelFormat);
	Nan::SetPrototypeMethod(tpl, "setLabelFormat", SetLabelFormat);

	Nan::SetPrototypeMethod(tpl, "SetRay1Visibility", SetRay1Visibility);
	Nan::SetPrototypeMethod(tpl, "setRay1Visibility", SetRay1Visibility);

	Nan::SetPrototypeMethod(tpl, "SetRay2Visibility", SetRay2Visibility);
	Nan::SetPrototypeMethod(tpl, "setRay2Visibility", SetRay2Visibility);

	Nan::SetPrototypeMethod(tpl, "SetTolerance", SetTolerance);
	Nan::SetPrototypeMethod(tpl, "setTolerance", SetTolerance);

	Nan::SetPrototypeMethod(tpl, "StartWidgetInteraction", StartWidgetInteraction);
	Nan::SetPrototypeMethod(tpl, "startWidgetInteraction", StartWidgetInteraction);

	Nan::SetPrototypeMethod(tpl, "WidgetInteraction", WidgetInteraction);
	Nan::SetPrototypeMethod(tpl, "widgetInteraction", WidgetInteraction);

#ifdef VTK_NODE_PLUS_VTKANGLEREPRESENTATIONWRAP_INITPTPL
	VTK_NODE_PLUS_VTKANGLEREPRESENTATIONWRAP_INITPTPL
#endif
	ptpl.Reset( tpl );
}

void VtkAngleRepresentationWrap::New(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	if(!info.IsConstructCall())
	{
		Nan::ThrowError("Constructor not called in a construct call.");
		return;
	}

	if(info.Length() == 0)
	{
		Nan::ThrowError("Cannot create instance of abstract class.");
		return;
	}
	else
	{
		if(info[0]->ToObject() != vtkNodeJsNoWrap )
		{
			Nan::ThrowError("Parameter Error");
			return;
		}
	}

	info.GetReturnValue().Set(info.This());
}

void VtkAngleRepresentationWrap::ArcVisibilityOff(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	VtkAngleRepresentationWrap *wrapper = ObjectWrap::Unwrap<VtkAngleRepresentationWrap>(info.Holder());
	vtkAngleRepresentation *native = (vtkAngleRepresentation *)wrapper->native.GetPointer();
		if(info.Length() != 0)
	{
		Nan::ThrowError("Too many parameters.");
		return;
	}
	native->ArcVisibilityOff();
}

void VtkAngleRepresentationWrap::ArcVisibilityOn(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	VtkAngleRepresentationWrap *wrapper = ObjectWrap::Unwrap<VtkAngleRepresentationWrap>(info.Holder());
	vtkAngleRepresentation *native = (vtkAngleRepresentation *)wrapper->native.GetPointer();
		if(info.Length() != 0)
	{
		Nan::ThrowError("Too many parameters.");
		return;
	}
	native->ArcVisibilityOn();
}

void VtkAngleRepresentationWrap::BuildRepresentation(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	VtkAngleRepresentationWrap *wrapper = ObjectWrap::Unwrap<VtkAngleRepresentationWrap>(info.Holder());
	vtkAngleRepresentation *native = (vtkAngleRepresentation *)wrapper->native.GetPointer();
		if(info.Length() != 0)
	{
		Nan::ThrowError("Too many parameters.");
		return;
	}
	native->BuildRepresentation();
}

void VtkAngleRepresentationWrap::CenterWidgetInteraction(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	VtkAngleRepresentationWrap *wrapper = ObjectWrap::Unwrap<VtkAngleRepresentationWrap>(info.Holder());
	vtkAngleRepresentation *native = (vtkAngleRepresentation *)wrapper->native.GetPointer();
	size_t i;
	if(info.Length() > 0 && info[0]->IsFloat64Array())
	{
		v8::Local<v8::Float64Array>a0(v8::Local<v8::Float64Array>::Cast(info[0]->ToObject()));
		if( a0->Length() < 2 )
		{
			Nan::ThrowError("Array too short.");
			return;
		}

				if(info.Length() != 1)
		{
			Nan::ThrowError("Too many parameters.");
			return;
		}
		native->CenterWidgetInteraction(
			(double *)(a0->Buffer()->GetContents().Data())
		);
		return;
	}
	else if(info.Length() > 0 && info[0]->IsArray())
	{
		v8::Local<v8::Array>a0(v8::Local<v8::Array>::Cast(info[0]->ToObject()));
		double b0[2];
		if( a0->Length() < 2 )
		{
			Nan::ThrowError("Array too short.");
			return;
		}

		for( i = 0; i < 2; i++ )
		{
			if( !a0->Get(i)->IsNumber() )
			{
				Nan::ThrowError("Array contents invalid.");
				return;
			}
			b0[i] = a0->Get(i)->NumberValue();
		}
				if(info.Length() != 1)
		{
			Nan::ThrowError("Too many parameters.");
			return;
		}
		native->CenterWidgetInteraction(
			b0
		);
		return;
	}
	Nan::ThrowError("Parameter mismatch");
}

void VtkAngleRepresentationWrap::ComputeInteractionState(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	VtkAngleRepresentationWrap *wrapper = ObjectWrap::Unwrap<VtkAngleRepresentationWrap>(info.Holder());
	vtkAngleRepresentation *native = (vtkAngleRepresentation *)wrapper->native.GetPointer();
	if(info.Length() > 0 && info[0]->IsInt32())
	{
		if(info.Length() > 1 && info[1]->IsInt32())
		{
			if(info.Length() > 2 && info[2]->IsInt32())
			{
				int r;
				if(info.Length() != 3)
				{
					Nan::ThrowError("Too many parameters.");
					return;
				}
				r = native->ComputeInteractionState(
					info[0]->Int32Value(),
					info[1]->Int32Value(),
					info[2]->Int32Value()
				);
				info.GetReturnValue().Set(Nan::New(r));
				return;
			}
		}
	}
	Nan::ThrowError("Parameter mismatch");
}

void VtkAngleRepresentationWrap::GetArcVisibility(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	VtkAngleRepresentationWrap *wrapper = ObjectWrap::Unwrap<VtkAngleRepresentationWrap>(info.Holder());
	vtkAngleRepresentation *native = (vtkAngleRepresentation *)wrapper->native.GetPointer();
	int r;
	if(info.Length() != 0)
	{
		Nan::ThrowError("Too many parameters.");
		return;
	}
	r = native->GetArcVisibility();
	info.GetReturnValue().Set(Nan::New(r));
}

void VtkAngleRepresentationWrap::GetCenterRepresentation(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	VtkAngleRepresentationWrap *wrapper = ObjectWrap::Unwrap<VtkAngleRepresentationWrap>(info.Holder());
	vtkAngleRepresentation *native = (vtkAngleRepresentation *)wrapper->native.GetPointer();
	vtkHandleRepresentation * r;
	if(info.Length() != 0)
	{
		Nan::ThrowError("Too many parameters.");
		return;
	}
	r = native->GetCenterRepresentation();
	VtkHandleRepresentationWrap::InitPtpl();
	v8::Local<v8::Value> argv[1] =
		{ Nan::New(vtkNodeJsNoWrap) };
	v8::Local<v8::Function> cons =
		Nan::New<v8::FunctionTemplate>(VtkHandleRepresentationWrap::ptpl)->GetFunction();
	v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
	VtkHandleRepresentationWrap *w = new VtkHandleRepresentationWrap();
	w->native = r;
	w->Wrap(wo);
	info.GetReturnValue().Set(wo);
}

void VtkAngleRepresentationWrap::GetClassName(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	VtkAngleRepresentationWrap *wrapper = ObjectWrap::Unwrap<VtkAngleRepresentationWrap>(info.Holder());
	vtkAngleRepresentation *native = (vtkAngleRepresentation *)wrapper->native.GetPointer();
	char const * r;
	if(info.Length() != 0)
	{
		Nan::ThrowError("Too many parameters.");
		return;
	}
	r = native->GetClassName();
	info.GetReturnValue().Set(Nan::New(r).ToLocalChecked());
}

void VtkAngleRepresentationWrap::GetLabelFormat(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	VtkAngleRepresentationWrap *wrapper = ObjectWrap::Unwrap<VtkAngleRepresentationWrap>(info.Holder());
	vtkAngleRepresentation *native = (vtkAngleRepresentation *)wrapper->native.GetPointer();
	char const * r;
	if(info.Length() != 0)
	{
		Nan::ThrowError("Too many parameters.");
		return;
	}
	r = native->GetLabelFormat();
	info.GetReturnValue().Set(Nan::New(r).ToLocalChecked());
}

void VtkAngleRepresentationWrap::GetPoint1Representation(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	VtkAngleRepresentationWrap *wrapper = ObjectWrap::Unwrap<VtkAngleRepresentationWrap>(info.Holder());
	vtkAngleRepresentation *native = (vtkAngleRepresentation *)wrapper->native.GetPointer();
	vtkHandleRepresentation * r;
	if(info.Length() != 0)
	{
		Nan::ThrowError("Too many parameters.");
		return;
	}
	r = native->GetPoint1Representation();
	VtkHandleRepresentationWrap::InitPtpl();
	v8::Local<v8::Value> argv[1] =
		{ Nan::New(vtkNodeJsNoWrap) };
	v8::Local<v8::Function> cons =
		Nan::New<v8::FunctionTemplate>(VtkHandleRepresentationWrap::ptpl)->GetFunction();
	v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
	VtkHandleRepresentationWrap *w = new VtkHandleRepresentationWrap();
	w->native = r;
	w->Wrap(wo);
	info.GetReturnValue().Set(wo);
}

void VtkAngleRepresentationWrap::GetPoint2Representation(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	VtkAngleRepresentationWrap *wrapper = ObjectWrap::Unwrap<VtkAngleRepresentationWrap>(info.Holder());
	vtkAngleRepresentation *native = (vtkAngleRepresentation *)wrapper->native.GetPointer();
	vtkHandleRepresentation * r;
	if(info.Length() != 0)
	{
		Nan::ThrowError("Too many parameters.");
		return;
	}
	r = native->GetPoint2Representation();
	VtkHandleRepresentationWrap::InitPtpl();
	v8::Local<v8::Value> argv[1] =
		{ Nan::New(vtkNodeJsNoWrap) };
	v8::Local<v8::Function> cons =
		Nan::New<v8::FunctionTemplate>(VtkHandleRepresentationWrap::ptpl)->GetFunction();
	v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
	VtkHandleRepresentationWrap *w = new VtkHandleRepresentationWrap();
	w->native = r;
	w->Wrap(wo);
	info.GetReturnValue().Set(wo);
}

void VtkAngleRepresentationWrap::GetRay1Visibility(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	VtkAngleRepresentationWrap *wrapper = ObjectWrap::Unwrap<VtkAngleRepresentationWrap>(info.Holder());
	vtkAngleRepresentation *native = (vtkAngleRepresentation *)wrapper->native.GetPointer();
	int r;
	if(info.Length() != 0)
	{
		Nan::ThrowError("Too many parameters.");
		return;
	}
	r = native->GetRay1Visibility();
	info.GetReturnValue().Set(Nan::New(r));
}

void VtkAngleRepresentationWrap::GetRay2Visibility(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	VtkAngleRepresentationWrap *wrapper = ObjectWrap::Unwrap<VtkAngleRepresentationWrap>(info.Holder());
	vtkAngleRepresentation *native = (vtkAngleRepresentation *)wrapper->native.GetPointer();
	int r;
	if(info.Length() != 0)
	{
		Nan::ThrowError("Too many parameters.");
		return;
	}
	r = native->GetRay2Visibility();
	info.GetReturnValue().Set(Nan::New(r));
}

void VtkAngleRepresentationWrap::GetTolerance(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	VtkAngleRepresentationWrap *wrapper = ObjectWrap::Unwrap<VtkAngleRepresentationWrap>(info.Holder());
	vtkAngleRepresentation *native = (vtkAngleRepresentation *)wrapper->native.GetPointer();
	int r;
	if(info.Length() != 0)
	{
		Nan::ThrowError("Too many parameters.");
		return;
	}
	r = native->GetTolerance();
	info.GetReturnValue().Set(Nan::New(r));
}

void VtkAngleRepresentationWrap::GetToleranceMaxValue(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	VtkAngleRepresentationWrap *wrapper = ObjectWrap::Unwrap<VtkAngleRepresentationWrap>(info.Holder());
	vtkAngleRepresentation *native = (vtkAngleRepresentation *)wrapper->native.GetPointer();
	int r;
	if(info.Length() != 0)
	{
		Nan::ThrowError("Too many parameters.");
		return;
	}
	r = native->GetToleranceMaxValue();
	info.GetReturnValue().Set(Nan::New(r));
}

void VtkAngleRepresentationWrap::GetToleranceMinValue(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	VtkAngleRepresentationWrap *wrapper = ObjectWrap::Unwrap<VtkAngleRepresentationWrap>(info.Holder());
	vtkAngleRepresentation *native = (vtkAngleRepresentation *)wrapper->native.GetPointer();
	int r;
	if(info.Length() != 0)
	{
		Nan::ThrowError("Too many parameters.");
		return;
	}
	r = native->GetToleranceMinValue();
	info.GetReturnValue().Set(Nan::New(r));
}

void VtkAngleRepresentationWrap::InstantiateHandleRepresentation(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	VtkAngleRepresentationWrap *wrapper = ObjectWrap::Unwrap<VtkAngleRepresentationWrap>(info.Holder());
	vtkAngleRepresentation *native = (vtkAngleRepresentation *)wrapper->native.GetPointer();
		if(info.Length() != 0)
	{
		Nan::ThrowError("Too many parameters.");
		return;
	}
	native->InstantiateHandleRepresentation();
}

void VtkAngleRepresentationWrap::IsA(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	VtkAngleRepresentationWrap *wrapper = ObjectWrap::Unwrap<VtkAngleRepresentationWrap>(info.Holder());
	vtkAngleRepresentation *native = (vtkAngleRepresentation *)wrapper->native.GetPointer();
	if(info.Length() > 0 && info[0]->IsString())
	{
		Nan::Utf8String a0(info[0]);
		int r;
		if(info.Length() != 1)
		{
			Nan::ThrowError("Too many parameters.");
			return;
		}
		r = native->IsA(
			*a0
		);
		info.GetReturnValue().Set(Nan::New(r));
		return;
	}
	Nan::ThrowError("Parameter mismatch");
}

void VtkAngleRepresentationWrap::NewInstance(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	VtkAngleRepresentationWrap *wrapper = ObjectWrap::Unwrap<VtkAngleRepresentationWrap>(info.Holder());
	vtkAngleRepresentation *native = (vtkAngleRepresentation *)wrapper->native.GetPointer();
	vtkAngleRepresentation * r;
	if(info.Length() != 0)
	{
		Nan::ThrowError("Too many parameters.");
		return;
	}
	r = native->NewInstance();
	VtkAngleRepresentationWrap::InitPtpl();
	v8::Local<v8::Value> argv[1] =
		{ Nan::New(vtkNodeJsNoWrap) };
	v8::Local<v8::Function> cons =
		Nan::New<v8::FunctionTemplate>(VtkAngleRepresentationWrap::ptpl)->GetFunction();
	v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
	VtkAngleRepresentationWrap *w = new VtkAngleRepresentationWrap();
	w->native = r;
	w->Wrap(wo);
	info.GetReturnValue().Set(wo);
}

void VtkAngleRepresentationWrap::Ray1VisibilityOff(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	VtkAngleRepresentationWrap *wrapper = ObjectWrap::Unwrap<VtkAngleRepresentationWrap>(info.Holder());
	vtkAngleRepresentation *native = (vtkAngleRepresentation *)wrapper->native.GetPointer();
		if(info.Length() != 0)
	{
		Nan::ThrowError("Too many parameters.");
		return;
	}
	native->Ray1VisibilityOff();
}

void VtkAngleRepresentationWrap::Ray1VisibilityOn(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	VtkAngleRepresentationWrap *wrapper = ObjectWrap::Unwrap<VtkAngleRepresentationWrap>(info.Holder());
	vtkAngleRepresentation *native = (vtkAngleRepresentation *)wrapper->native.GetPointer();
		if(info.Length() != 0)
	{
		Nan::ThrowError("Too many parameters.");
		return;
	}
	native->Ray1VisibilityOn();
}

void VtkAngleRepresentationWrap::Ray2VisibilityOff(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	VtkAngleRepresentationWrap *wrapper = ObjectWrap::Unwrap<VtkAngleRepresentationWrap>(info.Holder());
	vtkAngleRepresentation *native = (vtkAngleRepresentation *)wrapper->native.GetPointer();
		if(info.Length() != 0)
	{
		Nan::ThrowError("Too many parameters.");
		return;
	}
	native->Ray2VisibilityOff();
}

void VtkAngleRepresentationWrap::Ray2VisibilityOn(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	VtkAngleRepresentationWrap *wrapper = ObjectWrap::Unwrap<VtkAngleRepresentationWrap>(info.Holder());
	vtkAngleRepresentation *native = (vtkAngleRepresentation *)wrapper->native.GetPointer();
		if(info.Length() != 0)
	{
		Nan::ThrowError("Too many parameters.");
		return;
	}
	native->Ray2VisibilityOn();
}

void VtkAngleRepresentationWrap::SafeDownCast(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	VtkAngleRepresentationWrap *wrapper = ObjectWrap::Unwrap<VtkAngleRepresentationWrap>(info.Holder());
	vtkAngleRepresentation *native = (vtkAngleRepresentation *)wrapper->native.GetPointer();
	if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkObjectWrap::ptpl))->HasInstance(info[0]))
	{
		VtkObjectWrap *a0 = ObjectWrap::Unwrap<VtkObjectWrap>(info[0]->ToObject());
		vtkAngleRepresentation * r;
		if(info.Length() != 1)
		{
			Nan::ThrowError("Too many parameters.");
			return;
		}
		r = native->SafeDownCast(
			(vtkObject *) a0->native.GetPointer()
		);
		VtkAngleRepresentationWrap::InitPtpl();
		v8::Local<v8::Value> argv[1] =
			{ Nan::New(vtkNodeJsNoWrap) };
		v8::Local<v8::Function> cons =
			Nan::New<v8::FunctionTemplate>(VtkAngleRepresentationWrap::ptpl)->GetFunction();
		v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
		VtkAngleRepresentationWrap *w = new VtkAngleRepresentationWrap();
		w->native = r;
		w->Wrap(wo);
		info.GetReturnValue().Set(wo);
		return;
	}
	Nan::ThrowError("Parameter mismatch");
}

void VtkAngleRepresentationWrap::SetArcVisibility(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	VtkAngleRepresentationWrap *wrapper = ObjectWrap::Unwrap<VtkAngleRepresentationWrap>(info.Holder());
	vtkAngleRepresentation *native = (vtkAngleRepresentation *)wrapper->native.GetPointer();
	if(info.Length() > 0 && info[0]->IsInt32())
	{
				if(info.Length() != 1)
		{
			Nan::ThrowError("Too many parameters.");
			return;
		}
		native->SetArcVisibility(
			info[0]->Int32Value()
		);
		return;
	}
	Nan::ThrowError("Parameter mismatch");
}

void VtkAngleRepresentationWrap::SetHandleRepresentation(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	VtkAngleRepresentationWrap *wrapper = ObjectWrap::Unwrap<VtkAngleRepresentationWrap>(info.Holder());
	vtkAngleRepresentation *native = (vtkAngleRepresentation *)wrapper->native.GetPointer();
	if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkHandleRepresentationWrap::ptpl))->HasInstance(info[0]))
	{
		VtkHandleRepresentationWrap *a0 = ObjectWrap::Unwrap<VtkHandleRepresentationWrap>(info[0]->ToObject());
				if(info.Length() != 1)
		{
			Nan::ThrowError("Too many parameters.");
			return;
		}
		native->SetHandleRepresentation(
			(vtkHandleRepresentation *) a0->native.GetPointer()
		);
		return;
	}
	Nan::ThrowError("Parameter mismatch");
}

void VtkAngleRepresentationWrap::SetLabelFormat(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	VtkAngleRepresentationWrap *wrapper = ObjectWrap::Unwrap<VtkAngleRepresentationWrap>(info.Holder());
	vtkAngleRepresentation *native = (vtkAngleRepresentation *)wrapper->native.GetPointer();
	if(info.Length() > 0 && info[0]->IsString())
	{
		Nan::Utf8String a0(info[0]);
				if(info.Length() != 1)
		{
			Nan::ThrowError("Too many parameters.");
			return;
		}
		native->SetLabelFormat(
			*a0
		);
		return;
	}
	Nan::ThrowError("Parameter mismatch");
}

void VtkAngleRepresentationWrap::SetRay1Visibility(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	VtkAngleRepresentationWrap *wrapper = ObjectWrap::Unwrap<VtkAngleRepresentationWrap>(info.Holder());
	vtkAngleRepresentation *native = (vtkAngleRepresentation *)wrapper->native.GetPointer();
	if(info.Length() > 0 && info[0]->IsInt32())
	{
				if(info.Length() != 1)
		{
			Nan::ThrowError("Too many parameters.");
			return;
		}
		native->SetRay1Visibility(
			info[0]->Int32Value()
		);
		return;
	}
	Nan::ThrowError("Parameter mismatch");
}

void VtkAngleRepresentationWrap::SetRay2Visibility(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	VtkAngleRepresentationWrap *wrapper = ObjectWrap::Unwrap<VtkAngleRepresentationWrap>(info.Holder());
	vtkAngleRepresentation *native = (vtkAngleRepresentation *)wrapper->native.GetPointer();
	if(info.Length() > 0 && info[0]->IsInt32())
	{
				if(info.Length() != 1)
		{
			Nan::ThrowError("Too many parameters.");
			return;
		}
		native->SetRay2Visibility(
			info[0]->Int32Value()
		);
		return;
	}
	Nan::ThrowError("Parameter mismatch");
}

void VtkAngleRepresentationWrap::SetTolerance(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	VtkAngleRepresentationWrap *wrapper = ObjectWrap::Unwrap<VtkAngleRepresentationWrap>(info.Holder());
	vtkAngleRepresentation *native = (vtkAngleRepresentation *)wrapper->native.GetPointer();
	if(info.Length() > 0 && info[0]->IsInt32())
	{
				if(info.Length() != 1)
		{
			Nan::ThrowError("Too many parameters.");
			return;
		}
		native->SetTolerance(
			info[0]->Int32Value()
		);
		return;
	}
	Nan::ThrowError("Parameter mismatch");
}

void VtkAngleRepresentationWrap::StartWidgetInteraction(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	VtkAngleRepresentationWrap *wrapper = ObjectWrap::Unwrap<VtkAngleRepresentationWrap>(info.Holder());
	vtkAngleRepresentation *native = (vtkAngleRepresentation *)wrapper->native.GetPointer();
	size_t i;
	if(info.Length() > 0 && info[0]->IsFloat64Array())
	{
		v8::Local<v8::Float64Array>a0(v8::Local<v8::Float64Array>::Cast(info[0]->ToObject()));
		if( a0->Length() < 2 )
		{
			Nan::ThrowError("Array too short.");
			return;
		}

				if(info.Length() != 1)
		{
			Nan::ThrowError("Too many parameters.");
			return;
		}
		native->StartWidgetInteraction(
			(double *)(a0->Buffer()->GetContents().Data())
		);
		return;
	}
	else if(info.Length() > 0 && info[0]->IsArray())
	{
		v8::Local<v8::Array>a0(v8::Local<v8::Array>::Cast(info[0]->ToObject()));
		double b0[2];
		if( a0->Length() < 2 )
		{
			Nan::ThrowError("Array too short.");
			return;
		}

		for( i = 0; i < 2; i++ )
		{
			if( !a0->Get(i)->IsNumber() )
			{
				Nan::ThrowError("Array contents invalid.");
				return;
			}
			b0[i] = a0->Get(i)->NumberValue();
		}
				if(info.Length() != 1)
		{
			Nan::ThrowError("Too many parameters.");
			return;
		}
		native->StartWidgetInteraction(
			b0
		);
		return;
	}
	Nan::ThrowError("Parameter mismatch");
}

void VtkAngleRepresentationWrap::WidgetInteraction(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	VtkAngleRepresentationWrap *wrapper = ObjectWrap::Unwrap<VtkAngleRepresentationWrap>(info.Holder());
	vtkAngleRepresentation *native = (vtkAngleRepresentation *)wrapper->native.GetPointer();
	size_t i;
	if(info.Length() > 0 && info[0]->IsFloat64Array())
	{
		v8::Local<v8::Float64Array>a0(v8::Local<v8::Float64Array>::Cast(info[0]->ToObject()));
		if( a0->Length() < 2 )
		{
			Nan::ThrowError("Array too short.");
			return;
		}

				if(info.Length() != 1)
		{
			Nan::ThrowError("Too many parameters.");
			return;
		}
		native->WidgetInteraction(
			(double *)(a0->Buffer()->GetContents().Data())
		);
		return;
	}
	else if(info.Length() > 0 && info[0]->IsArray())
	{
		v8::Local<v8::Array>a0(v8::Local<v8::Array>::Cast(info[0]->ToObject()));
		double b0[2];
		if( a0->Length() < 2 )
		{
			Nan::ThrowError("Array too short.");
			return;
		}

		for( i = 0; i < 2; i++ )
		{
			if( !a0->Get(i)->IsNumber() )
			{
				Nan::ThrowError("Array contents invalid.");
				return;
			}
			b0[i] = a0->Get(i)->NumberValue();
		}
				if(info.Length() != 1)
		{
			Nan::ThrowError("Too many parameters.");
			return;
		}
		native->WidgetInteraction(
			b0
		);
		return;
	}
	Nan::ThrowError("Parameter mismatch");
}


text:
package org.apache.geronimo.interop.util;

import org.apache.geronimo.interop.properties.BooleanProperty;
import org.apache.geronimo.interop.properties.SystemProperties;

public abstract class MemoryBarrier {
    public static BooleanProperty useVolatileMemoryBarrierProperty =
            new BooleanProperty(SystemProperties.class, "org.apache.geronimo.interop.useVolatileMemoryBarrier")
            .defaultValue(true);

    public static final boolean USE_VOLATILE = useVolatileMemoryBarrierProperty.getBoolean();
}

redpajama_set_name: RedPajamaGithub


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('osf', '0081_alter_abstractprovider_permissions'),
    ]

    operations = [
        migrations.AlterField(
            model_name='abstractprovider',
            name='preprint_word',
            field=models.CharField(choices=[('preprint', 'Preprint'), ('paper', 'Paper'), ('thesis', 'Thesis'), ('work', 'Work'), ('none', 'None')], default='preprint', max_length=10, null=True),
        ),
    ]


text:
package org.dstadler.commons.exec;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Map;
import java.util.logging.Logger;

import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.ExecuteException;
import org.apache.commons.exec.ExecuteWatchdog;
import org.apache.commons.exec.Executor;
import org.apache.commons.exec.PumpStreamHandler;
import org.dstadler.commons.arrays.ArrayUtils;
import org.dstadler.commons.logging.jdk.LoggerFactory;

/**
 * Helper class which provides convenience support for execution of commandline processes via commons-exec.
 *
 * Use getCommandResult() for processes where the output is small as they will store the output in
 * memory. Use getCommandResultIntoStream() in order to properly stream out potentially large
 * amounts of output from the executable.
 */
public class ExecutionHelper {
	private final static Logger log = LoggerFactory.make();

	/**
	 * Run the given commandline in the given directory and verify that the tool
	 * has the expected exit code and does finish in the timeout.
	 *
	 * Note: The resulting output is stored in memory, running a command
	 * which prints out a huge amount of data to stdout or stderr will
	 * cause memory problems.
	 *
     * @param cmdLine The commandline object filled with the executable and command line arguments
     * @param dir The working directory for the command
     * @param expectedExit The expected exit value or -1 to not fail on any exit value
	 * @param timeout The timeout in milliseconds or ExecuteWatchdog.INFINITE_TIMEOUT
	 * @return An InputStream which provides the output of the command.
     *
     * @throws IOException Execution of sub-process failed or the
     *          sub-process returned an exit value indicating a failure
	 */
	public static InputStream getCommandResult(
			CommandLine cmdLine, File dir, int expectedExit,
			long timeout) throws IOException {
		return getCommandResult(cmdLine, dir, expectedExit, timeout, null);
	}

	/**
	 * Run the given commandline in the given directory and provide the given input to the command.
	 * Also verify that the tool has the expected exit code and does finish in the timeout.
	 *
	 * Note: The resulting output is stored in memory, running a command
	 * which prints out a huge amount of data to stdout or stderr will
	 * cause memory problems.
	 *
	 * @param cmdLine The commandline object filled with the executable and command line arguments
	 * @param dir The working directory for the command
	 * @param expectedExit The expected exit value or -1 to not fail on any exit value
	 * @param timeout The timeout in milliseconds or ExecuteWatchdog.INFINITE_TIMEOUT
	 * @param input Input for the command-execution
	 * @return An InputStream which provides the output of the command.
     *
     * @throws IOException Execution of sub-process failed or the
     *          sub-process returned an exit value indicating a failure
	 */
	public static InputStream getCommandResult(
			CommandLine cmdLine, File dir, int expectedExit,
			long timeout, InputStream input) throws IOException {
		Executor executor = getDefaultExecutor(dir, expectedExit, timeout);

		try (ByteArrayOutputStream outStr = new ByteArrayOutputStream()) {
			executor.setStreamHandler(new PumpStreamHandler(outStr, outStr, input));
			try {
				execute(cmdLine, dir, executor, null);

				return new ByteArrayInputStream(outStr.toByteArray());
			} catch (IOException e) {
				if (outStr.size() > 0) {
					log.warning("Had output before error: \n" + outStr);
				}
				throw new IOException(e);
			}
		}
	}

	/**
	 * Run the given commandline in the given directory and verify that the tool
	 * has the expected exit code and does finish in the timeout.
	 *
     * @param cmdLine The commandline object filled with the executable and command line arguments
     * @param dir The working directory for the command
     * @param expectedExit The expected exit value or -1 to not fail on any exit value
	 * @param timeout The timeout in milliseconds or ExecuteWatchdog.INFINITE_TIMEOUT
	 * @param stream An OutputStream which receives the output of the executed command
     *
     * @throws IOException Execution of sub-process failed or the
     *          sub-process returned an exit value indicating a failure
	 */
	public static void getCommandResultIntoStream(
			CommandLine cmdLine, File dir, int expectedExit,
			long timeout, OutputStream stream) throws IOException {
		getCommandResultIntoStream(cmdLine, dir, expectedExit, timeout, stream, null);
	}

	/**
	 * Run the given commandline in the given directory and verify that the tool
	 * has the expected exit code and does finish in the timeout.
	 *
     * @param cmdLine The commandline object filled with the executable and command line arguments
     * @param dir The working directory for the command
     * @param expectedExit The expected exit value or -1 to not fail on any exit value
	 * @param timeout The timeout in milliseconds or ExecuteWatchdog.INFINITE_TIMEOUT
     * @param stream An OutputStream which receives the output of the executed command
	 * @param environment Environment variables that should be set for the execution of the command
	 *
	 * @throws IOException Execution of subprocess failed or the
     *          subprocess returned an exit value indicating a failure
	 */
	public static void getCommandResultIntoStream(
			CommandLine cmdLine, File dir, int expectedExit,
			long timeout, OutputStream stream, Map<String,String> environment) throws IOException {
		Executor executor = getDefaultExecutor(dir, expectedExit, timeout);
		executor.setStreamHandler(new PumpStreamHandler(stream));
		execute(cmdLine, dir, executor, environment);
	}

	private static Executor getDefaultExecutor(File dir, int expectedExit, long timeout) {
		Executor executor = new DefaultExecutor();
		if(expectedExit != -1) {
			executor.setExitValue(expectedExit);
		} else {
			executor.setExitValues(null);
		}

		ExecuteWatchdog watchdog = new ExecuteWatchdog(timeout);
		executor.setWatchdog(watchdog);
		executor.setWorkingDirectory(dir);
		return executor;
	}

	private static void execute(CommandLine cmdLine, File dir, Executor executor,
								Map<String,String> environment) throws IOException {
		log.info("-Executing(" + dir + "): " + toString(cmdLine));
		try {
			int exitValue = executor.execute(cmdLine, environment);
			if (exitValue != 0) {
				log.info("Had exit code " + exitValue + " when calling " + cmdLine);
			}
		} catch (ExecuteException e) {
			throw new ExecuteException("While executing (" + dir + "); " + toString(cmdLine), e.getExitValue(), e);
		}
	}

	private static String toString(CommandLine cmdLine) {
		return ArrayUtils.toString(cmdLine.toStrings(), " ", "", "");
	}
}


text: hawtioPluginLoader.addModule('mobileControlPanelApp');


text:
[![build status](https://secure.travis-ci.org/twilson63/linchpin.png)](http://travis-ci.org/twilson63/linchpin)

Event Driven Application Architecture Module

This module creates a global instance of an EventEmitter that can be
required by any module that would like to communicate with any other
module in the application.  This module provides the ability to create
loosely coupled modules or event application architecture.

Event Application Architecture is the process of creating self contained
modules that only communicate to other modules via messaging.  This
significantly reduces the rigid coupling that causes applications to
become hard to test and manage.

## Basic Usage

>module1.js

``` javascript
var pin = require('linchpin');

pin.on('foo', function(d) { console.log('you called foo.'); });
```

>module2.js

``` javascript
var pin = require('linchpin');

pin.emit('foo', 'bar');
```

>main.js

``` javascript
require('module1');
require('module2');
```

>exec

``` sh
node main.js
#> You Called Foo
```

## Wildcard Support

``` javascript
var pin = require('linchpin');
pin.on('foo/*', function () { console.log('you called foo xxx'); });
pin.on('foo/bar/*', function () { console.log('you called foo bar xxx'); });
pin.on('foo/bar/baz', function () { console.log('you called foo bar baz'); });

pin.emit('foo/bar/baz');

```

## Install

``` sh
npm install linchpin  --save
```

## Tests

``` sh
npm test
```

## License

SEE LICENSE

## How to contribute

* Check out Open Issues
* Post an Issue for a Feature
* Submit a Pull Request (Please Include Test Case)

## Credits

* Ryan Dahl creator of nodejs and the whole nodejs team.
* Addy Osman for his presentations
[videos](http://addyosmani.com/scalable-javascript-videos/)


text: link ../../../SBJson/src/main/objc/SBJson4StreamTokeniser.h


text:
package metier.entites;

import metier.dao.ExemplairesDao;
import metier.dao.UtilisateursDao;

public class TestAdherentTroisEmprunts {

	public static void main (String [] argv){

		/**
		 * Scenario de test d'emprunt par les adherents
		 * Il faut réaliser ici 3 emprunts
		 */

		// Instanciation de la classe ExemplairesDao
		System.out.println( "\n------------------------------------------------------");
		System.out.println ("Utilisation de la classe ExemplairesDao() pour l'affichage des exemplaires");
		System.out.println();
		ExemplairesDao eDao = new ExemplairesDao();

		// Methode findByKey

		try {
			for (int i=1; i <5; i++){
				System.out.println(eDao.findByKey(i));
			}

		} catch (BiblioException e) {
			System.out.println("Exception levée :"+e.getMessage());
		}

		// Instanciation de la classe UtilisateursDao

		System.out.println();
		System.out.println( "\n------------------------------------------------------");
		System.out.println ("Utilisation de la classe UtilisateursDao()");
		System.out.println();
		UtilisateursDao uDao = new UtilisateursDao();

		try {
			System.out.println(uDao.findByKey(3));
		} catch (BiblioException e) {
			System.out.println("Exception levée :"+e.getMessage());
		}
		System.out.println();
		System.out.println( "\n------------------------------------------------------");
		System.out.println ("AJOUT D'EMPRUNT A l'ADHERENT");
		System.out.println();

		EmpruntEnCours ep1, ep2, ep3;
		try {
			ep1 = new EmpruntEnCours(uDao.findByKey(3), eDao.findByKey(1));
			ep2 = new EmpruntEnCours(uDao.findByKey(3), eDao.findByKey(2));
			ep3 = new EmpruntEnCours(uDao.findByKey(3), eDao.findByKey(3));
			uDao.findByKey(3).addEmpruntEnCours(ep1);
			uDao.findByKey(3).addEmpruntEnCours(ep2);
			uDao.findByKey(3).addEmpruntEnCours(ep3);
			System.out.println(ep1);
			System.out.println(ep2);
			System.out.println(ep3);
		} catch (BiblioException e) {
			System.out.println("Exception levée :"+e.getMessage());
		}

		System.out.println();
		System.out.println( "\n------------------------------------------------------");
		System.out.println ("AJOUT D'un 4 EME EMPRUNT A l'ADHERENT");
		System.out.println();

		EmpruntEnCours ep4;

		try {

			//System.out.println(uDao.findByKey(3).getEmpruntEnCours());
			ep4 = new EmpruntEnCours(uDao.findByKey(3), eDao.findByKey(4));
			uDao.findByKey(3).addEmpruntEnCours(ep4);

			//System.out.println(ep1);
			//System.out.println(ep2);
			//System.out.println(ep3);
			System.out.println(ep4);

		} catch (BiblioException e) {
			System.out.println("Exception levée :"+e.getMessage());
		}

	}

}


text:
Price: {{ stock.price }}

      More details

      Stock History


text:
package com.badlogic.gdx.graphics.g3d.loaders.ogre.mesh;

import java.util.ArrayList;
import java.util.List;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

/**
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {"vertexbuffer"})
@XmlRootElement(name = "geometry")
public class Geometry implements BaseGeometry {

	@XmlAttribute public int vertexcount;
	@XmlElement(required = true) protected List<Vertexbuffer> vertexbuffer;

	/** Gets the value of the vertexbuffer property.
	 *
	 *

	 * This accessor method returns a reference to the live list, not a snapshot. Therefore any modification you make to the
	 * returned list will be present inside the JAXB object. This is why there is not a set method for the
	 * vertexbuffer property.
	 *
	 *

	 * For example, to add a new item, do as follows:
	 *
	 *

	 * getVertexbuffer().add(newItem);
	 *

	 *
	 *
	 *

	 * Objects of the following type(s) are allowed in the list {@link Vertexbuffer } */
	public List<Vertexbuffer> getVertexbuffer () {
		if (vertexbuffer == null) {
			vertexbuffer = new ArrayList<Vertexbuffer>();
		}
		return this.vertexbuffer;
	}

	@Override
	public int getVertexCount () {
		// TODO Auto-generated method stub
		return vertexcount;
	}

}


text:
describe("reddebox", function() {
  var frag;
  beforeEach(function(){
    frag = $(readFixtures('images.html'))
  });

  it("reddebox доступен в объете jquery", function(){
    expect($.fn.reddebox).toBeDefined();
  });

  it('method chaining', function(){
    expect(frag.reddebox()).toBe(frag)
  });

});

describe("Bar", function() {
  var frag, links, reddebox;
  beforeEach(function(){
    frag = $(readFixtures('reddebox.html'));
    links = frag.find('a');
  });

  afterEach(function(){
    reddebox.remove()
  });

  it('activeIndex', function(){
    reddebox = new $.reddebox(links.get(1), links, {overlayOpacity: 1});
    expect(reddebox.activeIndex).toBe(1)
  });

  it('class-wrapper', function(){
    reddebox = new $.reddebox(links.get(0), links, {classWrapper: 'test-class'});
    expect($("#redde-box")).toHaveClass('test-class')
  });

  it('dont have class-wrapper', function(){
    reddebox = new $.reddebox(links.get(0), links);
    expect($("#redde-box").attr('class')).toBeUndefined()
  });

});

describe('useThisLink', function(){
  var reddebox, link;

  beforeEach(function(){
    link = $('<a/>').attr({
      href: 'test.html'
    });
  });

  afterEach(function(){
    reddebox.remove()
  });

  it('default', function(){
    reddebox = new $.reddebox(link.get(0), link, {
      imageArray: ['i/004.jpg', 'i/016.jpg']
    });
    expect(reddebox.jQueryMatchedObj.length).toBe(3)
  });

  it('false', function(){
    reddebox = new $.reddebox(link.get(0), link, {
      useThisLink: false,
      imageArray: ['i/004.jpg', 'i/016.jpg']
    });
    expect(reddebox.jQueryMatchedObj.length).toBe(2)
  });

  it('random', function(){
    var r = Math.round(Math.random()*9+0.5)-1
    reddebox = new $.reddebox(link.get(0), link, {
      activeIndex: function(){
        return r
      },
      imageArray: ['i/004.jpg', 'i/016.jpg', 'i/004.jpg', 'i/016.jpg', 'i/004.jpg', 'i/016.jpg', 'i/004.jpg', 'i/016.jpg', 'i/004.jpg', 'i/016.jpg']
    });
    expect(reddebox.activeIndex).toBe(r)
  });

});


text:
var Path = require('path');
var rawExpr = /^[^\\/.]+$/;

function PrivateRepoWarnPlugin(options) {
  this.options = options;
}

module.exports = PrivateRepoWarnPlugin;

PrivateRepoWarnPlugin.prototype.apply = function (compiler) {
  var dev = this.options.dev;
  var privateRepo = this.options.privateRepo;

  if (privateRepo && !dev) {
    privateRepo = Path.normalize(privateRepo);
    compiler.plugin('compilation', function (compilation) {
      compilation.plugin('normal-module-loader', function (loaderContext, module) {
        if (rawExpr.test(module.rawRequest) && ~module.request.indexOf(privateRepo)) {
          loaderContext.emitWarning(`require a module ${module.rawRequest} in private repository ${privateRepo}`);
        }
      });
    });
  }
};


text:
module.exports = {
  extends: ['plugin:jest-playwright/recommended'],
};


text:
import sys, argparse, re
from subprocess import Popen, PIPE
from Bio.Format.Sam import SamStream
from Bio.Stream import LocusStream
from Bio.Range import Bed
from Bio.Structure import Junction

def main():
  parser = argparse.ArgumentParser(description="",formatter_class=argparse.ArgumentDefaultsHelpFormatter)
  parser.add_argument('input',help="Use - for STDIN or read bam")
  parser.add_argument('--minimum_intron_size',type=int,default=68,help="Require intron to be this size or larger")
  parser.add_argument('--minimum_overhang',type=int,default=10,help="At least this many bases on each side of an intron")
  parser.add_argument('--minimum_support',type=int,default=1,help="Minimum number of reads that should support a junction to report any of the reads")
  args = parser.parse_args()

  inf = sys.stdin
  if args.input != '-':
    cmd = 'samtools view -F 4 -h '+args.input
    p = Popen(cmd.split(),stdout=PIPE,bufsize=1)
    inf = p.stdout
  cmd2 = 'awk '+"'"+'{if(NF<10) print $0; else if($6~/N/) print $0;}'+"'"
  p2 = Popen(cmd2,stdout=PIPE,stdin=inf,bufsize=1,shell=True)
  stream = SamStream(p2.stdout,minimum_intron_size=args.minimum_intron_size,minimum_overhang=args.minimum_overhang)
  lstream = LocusStream(stream)
  for h in stream.header:
    print h.rstrip()
  for r in lstream:
    # now we have all the possible junctions from the range
    [juncs,sams] = get_junctions(r.get_payload(),args)
    evidence = {}
    lines = {}
    for x in set([x[0].get_range_string() for x in juncs]):
      evidence[x] = 0
      lines[x] = set()
    for i in range(0,len(juncs)):
      jstr = juncs[i][0].get_range_string()
      evidence[jstr]+=1
      lines[jstr].add(juncs[i][1])
    accepted = set()
    for jstr in evidence:
      if evidence[jstr] >= args.minimum_support:
        #print jstr
        for i in lines[jstr]: accepted.add(i)
    for i in sorted(list(accepted)):
      print sams[i].get_line().rstrip()
  p2.communicate()
  if args.input != '-':
    p.communicate()

def get_junctions(sams,args):
  prog = re.compile('^[MDNX=]$')
  outsams = {}
  z = 0
  outs = []
  for sam in sams:
    z+=1
    outsams[z] = sam
    v = [x for x in sam.value('cigar_array') if prog.match(x['op'])]
    juncs = [i for i in range(0,len(v)) if v[i]['op'] =='N' and v[i]['val'] >= args.minimum_intron_size]
    for i in juncs:
      coord1 = sum([x['val'] for x in v[0:i]]) + sam.value('pos')
      coord2 = coord1 + v[i]['val']
      b1 = Bed(sam.value('rname'),coord1-2,coord1-1)
      b2 = Bed(sam.value('rname'),coord2-1,coord2)
      outs.append([Junction(b1,b2),z])
  return [outs,outsams]

if __name__=="__main__":
  main()


text:
<?php

namespace Nzo\UrlEncryptorBundle\Annotations;

use Doctrine\Common\Annotations\Reader;
use Nzo\UrlEncryptorBundle\UrlEncryptor\UrlEncryptor;
use Symfony\Component\HttpKernel\Event\ControllerEvent;

class AnnotationResolver
{
    /**
     * @var Reader
     */
    private $reader;

    /**
     * @var UrlEncryptor
     */
    private $decryptor;

    /**
     * AnnotationResolver constructor.
     *
     * @param Reader $reader
     * @param UrlEncryptor $decryptor
     */
    public function __construct(Reader $reader, UrlEncryptor $decryptor)
    {
        $this->reader = $reader;
        $this->decryptor = $decryptor;
    }

    /**
     * @param ControllerEvent $event
     */
    public function onKernelController(ControllerEvent $event)
    {
        if (!is_array($controller = $event->getController())) {
            return;
        }

        $objectController = new \ReflectionObject($controller[0]);
        $method = $objectController->getMethod($controller[1]);
        foreach ($this->reader->getMethodAnnotations($method) as $configuration) {
            if ($configuration instanceof ParamEncryptor) {
                if (isset($configuration->params)) {
                    $request = $event->getRequest();
                    foreach ($configuration->params as $key => $param) {
                        if ($request->attributes->has($param)) {
                            $decrypted = $this->decryptor->encrypt($request->attributes->get($param));
                            $request->attributes->set($param, $decrypted);
                        } elseif ($request->request->has($param)) {
                            $decrypted = $this->decryptor->encrypt($request->request->get($param));
                            $request->request->set($param, $decrypted);
                        }
                    }
                }
            } elseif ($configuration instanceof ParamDecryptor) {
                if (isset($configuration->params)) {
                    $request = $event->getRequest();
                    foreach ($configuration->params as $key => $param) {
                        if ($request->attributes->has($param)) {
                            $decrypted = $this->decryptor->decrypt($request->attributes->get($param));
                            $request->attributes->set($param, $decrypted);
                        } elseif ($request->request->has($param)) {
                            $decrypted = $this->decryptor->decrypt($request->request->get($param));
                            $request->request->set($param, $decrypted);
                        }
                    }
                }
            }
        }
    }
}


text:
module GameOfLife
  # Raised when a {Board} gets into an invalid shape
  class InvalidBoardError < RuntimeError; end;

  # The board used in the game. Holds the {Cell}s.
  class Board

    # The {Cell}s in this board,internally maintained as a 2D Array of {Cell}s.
    # The x-coordinate increases horizontally and is always positive.
    # The y-coordinate increases vertically and is always positive.
    # Internally, the cells are arranged as a 2D array. The first-level Array indexed
    # with the y-coordinates. It contains an Array of {Cell}s, whose position is
    # the x-coordinate.
    # @note Use {#each_cell}, {#each_row} etc. methods to access the cells individually.
    attr_reader :cells

    # Creates the board
    # @param [2D Array<Symbol>] seed_data the data for the {Cell}s in the board, as an 2D array.
    # @example seed_data looks like
    #   the output of SimpleStringInputter#parse
    # @raise [InvalidBoardError] if the seed_data is not in the shape of a square,
    #   or if all elements are not present
    def initialize(seed_data)
      @cells = Array.new(Array.new)
      seed_with!(seed_data)
      begin
        validate
      rescue InvalidBoardError => ex
        # Add the seed_data into the error message, so the caller gets a clue
        raise InvalidBoardError, ex.message + " [seed data was: #{seed_data.inspect}]"
      end
    end

    # @param [OutPutter] the outputter that you want to use. Defaults to {Outputters::SimpleStringOutputter}
    def view(outputter = Outputters::SimpleStringOutputter.new)
      outputter.render(self)
    end

    def each_row(&block)
      @cells.each { |row| yield row }
    end

    def each_row_with_index(&block)
      @cells.each_with_index { |row, i| yield row, i }
    end

    def each_cell(&block)
      @cells.flatten.each { |cell| yield cell }
    end

    # Find the cell at a given pair of co-ordinates. Following Array symantics,
    # this method returns nil if nothing exists at that location or if the
    # location is out of the board. To avoid Array's negative index symantics it
    # returns nill if a negative index is passed.
    # @param [Integer] x the x-coordinate
    # @param [Integer] y the y-coordinate
    # @return [Cell] or nil
    def cell_at(x, y)
      return nil if (x < 0 || y < 0)
      @cells[y][x] if @cells[y]
    end

    # Finds the neighbors of a given {Cell}'s co-ordinates. The neighbors are the eight cells
    # that surround the given one.
    # @param [Integer] x the x-coordinate of the cell you find the neighbors of
    # @param [Integer] y the y-coordinate of the cell you find the neighbors of
    # @return [Array<Cell>]
    def neighbors_of_cell_at(x, y)
      neighbors = coords_of_neighbors(x, y).map { |x, y| self.cell_at(x, y) }
      neighbors.reject {|n| n.nil?}
    end

    # This is the first stage in a Game's #tick.
    # @see Game#tick
    def reformat_for_next_generation!
      # create an array of dead cells and insert it as the first and last row of cells
      dead_cells = (1..@cells.first.size).map { Cell.new }
      # don't forget to deep copy the dead_cells
      @cells.unshift Marshal.load(Marshal.dump(dead_cells))
      @cells.push Marshal.load(Marshal.dump(dead_cells))

      # also insert a dead cell at the left and right of each row
      @cells.each do |row|
        row.unshift Cell.new
        row.push Cell.new
      end

      # validate to see if we broke the board
      validate
    end

    # Goes through each {Cell} and marks it (using {Rules}) to signal it's state for the next
    # generation. This prevents modifying any {Cell} in-place as each generation is a pure
    # function of the previous. Once all {Cell}s are marked, it sweeps across them gets them
    # to change their state if they were marked to.
    # @see #mark_changes_for_next_generation
    # @see #sweep_changes_for_next_generation!
    def mark_and_sweep_for_next_generation!
      mark_changes_for_next_generation
      sweep_changes_for_next_generation!
    end

    # This is the third and last stage in a Game's #tick.
    # @see Game#tick
    def shed_dead_weight!
      # Remove the first and last rows if all cells are dead
      @cells.shift if @cells.first.all? { |cell| cell.dead? }
      @cells.pop if @cells.last.all? { |cell| cell.dead? }

      # Remove the first cell of every row, if they are all dead
      first_columns = @cells.map { |row| row.first }
      if first_columns.all? { |cell| cell.dead? }
        @cells.each { |row| row.shift }
      end

      # Remove the last cell of every row, if they are all dead
      last_columns = @cells.map { |row| row.last }
      if last_columns.all? { |cell| cell.dead? }
        @cells.each { |row| row.pop }
      end

      validate
    end

    private
      def validate
        num_o_rows = @cells.size
        columns_in_each_row = @cells.map(&:size)
        unless columns_in_each_row.uniq.size == 1
          msg = "Unequal number of columns, #{columns_in_each_row.inspect} in different rows found"
          raise InvalidBoardError, msg
        end

        num_o_columns = columns_in_each_row.uniq.first
        num_o_elements = @cells.flatten.reject {|d| d.nil? }.size
        unless (num_o_rows * num_o_columns) == num_o_elements
          msg = "Not a rectangular shape: " +
            "rows(#{num_o_rows}) x columns(#{num_o_columns}) != total elements(#{num_o_elements})]. "
          raise InvalidBoardError, msg
        end
      end

      def seed_with!(data)
        data.each_with_index do |row, y|
          @cells << []
          row.each_with_index do |state, x|
            @cells[y] << Cell.new(state)
          end
        end
      end

      def mark_changes_for_next_generation
        self.each_row_with_index do |cells, y|
          cells.each_with_index do |cell, x|
            cell.should_live_in_next_generation =
              Rules.should_cell_live?(self, cell, x, y)
          end
        end
      end

      def sweep_changes_for_next_generation!
        self.each_cell { |cell| cell.change_state_if_needed! }
      end

      # Calculates the co-ordinates of neighbors of a given pair of co-ordinates.
      # @param [Integer] x the x-coordinate
      # @param [Integer] y the y-coordinate
      # @return [Array<Integer, Integer>] the list of neighboring co-ordinates
      # @example
      #   coords_of_neighbors(1,1) =>
      #     [
      #       [0, 0], [0, 1], [0, 2],
      #       [1, 0],         [1, 2],
      #       [2, 0], [2, 1], [2, 2],
      #     ]
      # @note This method returns all possible co-ordinate pairs of neighbors,
      #   so it can contain coordinates of cells not in the board, or negative ones.
      # @see #neighbors_of_cell_at
      def coords_of_neighbors(x, y)
        coords_of_neighbors = []
        (x - 1).upto(x + 1).each do |neighbors_x|
          (y - 1).upto(y + 1).each do |neighbors_y|
            next if (x == neighbors_x) && (y == neighbors_y)
            coords_of_neighbors << [neighbors_x, neighbors_y]
          end
        end
        coords_of_neighbors
      end

  end
end


text:
<?php
namespace Hacks;

use Silex\Application;
use Nette\Utils\Json;

class SchoolDesign
{
    /**
     * @var \Silex\Application
     */
    protected $_app;

    public function __construct(Application $app)
    {
        $this->_app = $app;
    }

    /**
     * Get the school design document
     * @return object
     */
    public function get() {
    	/** @var \GuzzleHttp\Client $guzzle */
        $guzzle = $this->_app['guzzle'];

        $response = $guzzle->get('/schools/design/document');

        if ($response->getStatusCode() == 200) {
            return Json::decode(
                $response->getBody()
            )->_source;
        } else {
            return null;
        }
    }

    public function isUpdateValid($old, $new, $level) {
        $design = $this->get();

        if ($design === NULL)
            return FALSE;

        try {

            foreach ($design->categories as $category) {
                // when the category level is higher than the user level is, check
                // if the categories are the same (both missing or identical)
                if ($category->level > $level) {
                    $key = $category->key;
                    if (isset($old->$key) && isset($new->$key)) {
                        if ($old->$key != $new->$key) {
                            return FALSE;
                        }
                    } else if (isset($old->$key) || isset($new->$key)) {
                        return FALSE;
                    }
                }
            }

        } catch (\Exception $e) {
            return FALSE;
        }

        return TRUE;
    }
}


text:
/*
* Semaphore
* (C) 2013 Joel Low
*
* Botan is released under the Simplified BSD License (see license.txt)
*/

#ifndef BOTAN_SEMAPHORE_H_
#define BOTAN_SEMAPHORE_H_

#include <botan/mutex.h>

#if defined(BOTAN_TARGET_OS_HAS_THREADS)
  #include <condition_variable>
#endif

namespace Botan {

#if defined(BOTAN_TARGET_OS_HAS_THREADS)
class Semaphore final
   {
   public:
      explicit Semaphore(int value = 0) : m_value(value), m_wakeups(0) {}

      void acquire();

      void release(size_t n = 1);

   private:
      int m_value;
      int m_wakeups;
      mutex_type m_mutex;
      std::condition_variable m_cond;
   };
#endif

}

#endif


text:
"""Regression tests for issues."""

import sys
import unittest
import subprocess

class TestIssues(unittest.TestCase):
    """Each test method is named after the issue it is testing. The docstring
       contains the link for the issue and the issue's description.
    """

    def test_issue_13_17_and_6(self):
        """
        Improve library loading.

        This issue used to manifest as an inability to load SWI-Prolog's
        SO/DLL. If this test fails, it will usually kill Python, so the test is
        very simple.

        This test is here but it should be run on several platforms to ensure it
        works.

        http://code.google.com/p/pyswip/issues/detail?id=13
        http://code.google.com/p/pyswip/issues/detail?id=6
        https://code.google.com/p/pyswip/issues/detail?id=17
        """

        import pyswip.core # This implicitly tests library loading code. It
                           # won't be very useful if it is not tested in several
                           # OSes

    def test_issue_1(self):
        """
        Segmentation fault when assertz-ing

        Notes: This issue manifests only in 64bit stacks (note that a full 64
        bit stack is needed. If running 32 in 64bit, it will not happen.)

        http://code.google.com/p/pyswip/issues/detail?id=1
        """

        # The simple code below should be enough to trigger the issue. As with
        # issue 13, if it does not work, it will segfault Python.
        from pyswip import Prolog
        prolog = Prolog()
        prolog.assertz("randomTerm(michael,john)")

    def test_issue_8(self):
        """
        Callbacks can cause segv's

        https://code.google.com/p/pyswip/issues/detail?id=8
        """

        from pyswip import Prolog, registerForeign

        callsToHello = []
        def hello(t):
            callsToHello.append(t)
        hello.arity = 1

        registerForeign(hello)

        prolog = Prolog()
        prolog.assertz("parent(michael,john)")
        prolog.assertz("parent(michael,gina)")
        p = prolog.query("parent(michael,X), hello(X)")
        result = list(p)   # Will run over the iterator

        self.assertEqual(len(callsToHello), 2)  # ['john', 'gina']
        self.assertEqual(len(result), 2) # [{'X': 'john'}, {'X': 'gina'}]

    def test_issue_15(self):
        """
       	sys.exit does not work when importing pyswip

        https://code.google.com/p/pyswip/issues/detail?id=15
        """

        # We will use it to test several return codes
        pythonExec = sys.executable
        def runTestCode(code):
            parameters = [pythonExec,
                          '-c',
                          'import sys; import pyswip; sys.exit(%d)' % code,]
            result = subprocess.call(parameters)
            self.assertEqual(result, code)

        runTestCode(0)
        runTestCode(1)
        runTestCode(2)
        runTestCode(127)

    def test_issue_5(self):
        """
       	Patch: hash and eq methods for Atom class.

        Ensures that the patch is working.

        https://code.google.com/p/pyswip/issues/detail?id=5
        """

        from pyswip import Atom, Variable

        a = Atom('test')
        b = Atom('test2')
        c = Atom('test')    # Should be equal to a

        self.assertNotEqual(a, b)
        self.assertNotEqual(c, b)
        self.assertEqual(a, c)

        atomSet = set()
        atomSet.add(a)
        atomSet.add(b)
        atomSet.add(c)  # This is equal to a
        self.assertEqual(len(atomSet), 2)
        self.assertEqual(atomSet, set([a, b]))

        # The same semantics should be valid for other classes
        A = Variable()
        B = Variable()
        C = Variable(A.handle)   # This is equal to A

        self.assertNotEqual(A, B)
        self.assertNotEqual(C, B)
        self.assertEqual(A, C)
        varSet = set()
        varSet.add(A)
        varSet.add(B)
        varSet.add(C)  # This is equal to A
        self.assertEqual(len(varSet), 2)
        self.assertEqual(varSet, set([A, B]))

    def test_issue_4(self):
        """
       	Patch for a dynamic method

        Ensures that the patch is working.

        https://code.google.com/p/pyswip/issues/detail?id=4
        """

        from pyswip import Prolog

        Prolog.dynamic('test_issue_4_d/1')
        Prolog.assertz('test_issue_4_d(test1)')
        Prolog.assertz('test_issue_4_d(test1)')
        Prolog.assertz('test_issue_4_d(test1)')
        Prolog.assertz('test_issue_4_d(test2)')
        results = list(Prolog.query('test_issue_4_d(X)'))
        self.assertEqual(len(results), 4)

        Prolog.retract('test_issue_4_d(test1)')
        results = list(Prolog.query('test_issue_4_d(X)'))
        self.assertEqual(len(results), 3)

        Prolog.retractall('test_issue_4_d(test1)')
        results = list(Prolog.query('test_issue_4_d(X)'))
        self.assertEqual(len(results), 1)

    def test_issue_3(self):
        """
       	Problem with variables in lists

        https://code.google.com/p/pyswip/issues/detail?id=3
        """

        from pyswip import Prolog, Functor, Variable, Atom

        p = Prolog()

        f = Functor('f', 1)
        A = Variable()
        B = Variable()
        C = Variable()

        x = f([A, B, C])
        x = Functor.fromTerm(x)
        args = x.args[0]

        self.assertFalse(args[0] == args[1], "Var A equals var B")
        self.assertFalse(args[0] == args[2], "Var A equals var C")
        self.assertFalse(args[1] == args[2], "Var B equals var C")

        self.assertFalse(A == B, "Var A equals var B")
        self.assertFalse(B == C, "Var A equals var C")
        self.assertFalse(A == C, "Var B equals var C")

        # A more complex test
        x = f([A, B, 'c'])
        x = Functor.fromTerm(x)
        args = x.args[0]
        self.assertEqual(type(args[0]), Variable)
        self.assertEqual(type(args[1]), Variable)
        self.assertEqual(type(args[2]), Atom)

        # A test with repeated variables
        x = f([A, B, A])
        x = Functor.fromTerm(x)
        args = x.args[0]
        self.assertEqual(type(args[0]), Variable)
        self.assertEqual(type(args[1]), Variable)
        self.assertEqual(type(args[2]), Variable)
        self.assertTrue(args[0] == args[2], "The first and last var of "
                                            "f([A, B, A]) should be the same")

    def test_functor_return(self):
        """
        pyswip should generate string representations of query results
        that are at least meaningful, preferably equal to what
        SWI-Prolog would generate. This test checks if this is true for
        `Functor` instance results.

        Not a formal issue, but see forum topic:
        https://groups.google.com/forum/#!topic/pyswip/Mpnfq4DH-mI
        """

        import pyswip.prolog as pl

        p = pl.Prolog()

        # Add a simple grammar to the base
        p.consult("test_functor_return.pl")

        query = "sentence(Parse_tree, [the,bat,eats,a,cat], [])"
        expectedTree = "s(np(d(the), n(bat)), vp(v(eats), np(d(a), n(cat))))"

        # This should not throw an exception
        results = list(p.query(query))
        self.assertEqual(len(results), 1,
                         "Query should return exactly one result")

        ptree = results[0]["Parse_tree"]
        self.assertEqual(ptree, expectedTree)

        # A second test, based on what was posted in the forum
        p.assertz("friend(john,son(miki))")
        p.assertz("friend(john,son(kiwi))")
        p.assertz("friend(john,son(wiki))")
        p.assertz("friend(john,son(tiwi))")
        p.assertz("father(son(miki),kur)")
        p.assertz("father(son(kiwi),kur)")
        p.assertz("father(son(wiki),kur)")

        soln = [s["Y"] for s in p.query("friend(john,Y), father(Y,kur)",
                                         maxresult=1)]
        self.assertEqual(soln[0], "son(miki)")

if __name__ == "__main__":
    unittest.main()


text:
(function(global, code_stubs) {

"use strict";

code_stubs.StringLengthTFStub = function StringLengthTFStub(call_conv, minor_key) {
  var stub = function(receiver, name, i, v) {
    // i and v are dummy parameters mandated by the InterfaceDescriptor,
    // (LoadWithVectorDescriptor).
    return %_StringGetLength(%_JSValueGetValue(receiver));
  }
  return stub;
}

code_stubs.StringAddTFStub = function StringAddTFStub(call_conv, minor_key) {
  var stub = function(left, right) {
    return %StringAdd(left, right);
  }
  return stub;
}

const kTurboFanICCallModeMask = 1;
const kTurboFanICCallForUnptimizedCode = 0;
const kTurboFanICCallForOptimizedCode = 1;

code_stubs.MathFloorStub = function MathFloorStub(call_conv, minor_key) {
  var call_from_optimized_ic = function(f, i, tv, receiver, v) {
    "use strict";
    // |f| is this function's JSFunction
    // |i| is TypeFeedbackVector slot # of callee's CallIC for Math.floor call
    // |receiver| is receiver, should not be used
    // |tv| is the calling function's type vector
    // |v| is the value to floor
    if (f !== %_FixedArrayGet(tv, i|0)) {
      return %_CallFunction(receiver, v, f);
    }
    var r = %_MathFloor(+v);
    if (%_IsMinusZero(r)) {
      // Collect type feedback when the result of the floor is -0. This is
      // accomplished by storing a sentinel in the second, "extra"
      // TypeFeedbackVector slot corresponding to the Math.floor CallIC call in
      // the caller's TypeVector.
      %_FixedArraySet(tv, ((i|0)+1)|0, 1);
      return -0;
    }
    // Return integers in smi range as smis.
    var trunc = r|0;
    if (trunc === r) {
      return trunc;
    }
    return r;
  }
  var call_mode = (minor_key & kTurboFanICCallModeMask);
  if (call_mode == kTurboFanICCallForOptimizedCode) {
    return call_from_optimized_ic;
  } else {
    %SetForceInlineFlag(call_from_optimized_ic);
    var call_from_unoptimized_ic = function(f, i, receiver, v) {
      var tv = %_GetTypeFeedbackVector(%_GetCallerJSFunction());
      return call_from_optimized_ic(f, i, tv, receiver, v);
    }
    return call_from_unoptimized_ic;
  }
}

})


text:
<?php

namespace eni\QCMBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class QuestionType extends AbstractType {

	public function buildForm(FormBuilderInterface $oBuilder, array $tOptions) {
		$oBuilder
				->add('themes', 'entity', array(
					'label' => 'Thème',
	                'required' => true,
	                'class' => "eniQCMBundle:Theme",
	                'multiple' => true
	            ))
				->add('type', 'choice', array(
					'required' => true,
					'empty_value' => 'Type de question',
					'empty_data' => null,
	                'choices' => array(
	                    "simple" => "Une seul réponse possible",
	                    "multiple" => "Réponses multiple possibles"
	                )
	            ))
	            ->add('enonce', 'ckeditor', array(
	            	'label' => 'Enoncé'
	            ))
	            ->add('reponses', 'collection', array(
	                'required' => true,
	                'type' => new ReponseType(),
	                'allow_add'    => true,
	                'allow_delete' => true,
	                'by_reference' => false
	            ));
	}

	public function getName() {
		return 'question';
	}

	public function setDefaultOptions(OptionsResolverInterface $resolver) {
		$resolver->setDefaults(array(
			'data_class' => 'eni\QCMBundle\Entity\Question'
		));
	}
}


text:
require 'spec_helper'

RSpec.describe Projects::Alerting::NotificationsController do
  let_it_be(:project) { create(:project) }
  let_it_be(:environment) { create(:environment, project: project) }

  describe 'POST #create' do
    around do |example|
      ForgeryProtection.with_forgery_protection { example.run }
    end

    shared_examples 'process alert payload' do |notify_service_class|
      let(:service_response) { ServiceResponse.success }
      let(:notify_service) { instance_double(notify_service_class, execute: service_response) }

      before do
        allow(notify_service_class).to receive(:new).and_return(notify_service)
      end

      def make_request
        post :create, params: project_params, body: payload.to_json, as: :json
      end

      context 'when notification service succeeds' do
        let(:permitted_params) { ActionController::Parameters.new(payload).permit! }

        it 'responds with ok' do
          make_request

          expect(response).to have_gitlab_http_status(:ok)
        end

        it 'does not pass excluded parameters to the notify service' do
          make_request

          expect(notify_service_class)
            .to have_received(:new)
            .with(project, nil, permitted_params)
        end
      end

      context 'when notification service fails' do
        let(:service_response) { ServiceResponse.error(message: 'Unauthorized', http_status: :unauthorized) }

        it 'responds with the service response' do
          make_request

          expect(response).to have_gitlab_http_status(:unauthorized)
        end
      end

      context 'bearer token' do
        context 'when set' do
          it 'extracts bearer token' do
            request.headers['HTTP_AUTHORIZATION'] = 'Bearer some token'

            expect(notify_service).to receive(:execute).with('some token')

            make_request
          end

          it 'pass nil if cannot extract a non-bearer token' do
            request.headers['HTTP_AUTHORIZATION'] = 'some token'

            expect(notify_service).to receive(:execute).with(nil)

            make_request
          end
        end

        context 'when missing' do
          it 'passes nil' do
            expect(notify_service).to receive(:execute).with(nil)

            make_request
          end
        end
      end
    end

    context 'generic alert payload' do
      it_behaves_like 'process alert payload', Projects::Alerting::NotifyService do
        let(:payload) { { title: 'Alert title' } }
      end
    end

    context 'Prometheus alert payload' do
      include PrometheusHelpers

      it_behaves_like 'process alert payload', Projects::Prometheus::Alerts::NotifyService do
        let(:payload) { prometheus_alert_payload }
      end
    end
  end

  private

  def project_params(opts = {})
    opts.reverse_merge(namespace_id: project.namespace, project_id: project)
  end
end


text:
package com.spotify.helios;

import com.google.common.base.Throwables;
import com.google.common.io.Files;

import org.apache.commons.io.FileUtils;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.CuratorFrameworkFactory.Builder;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.curator.test.TestingServer;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.server.auth.DigestAuthenticationProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.nio.file.Path;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import static java.util.concurrent.TimeUnit.MINUTES;
import static org.apache.commons.io.FileUtils.deleteQuietly;

/**
 * A ZooKeeperTestManager that uses the {@link org.apache.curator.test.TestingServer}
 * to run an in-process ZooKeeper instance.
 */
public class ZooKeeperTestingServerManager implements ZooKeeperTestManager {

  private static final Logger log = LoggerFactory.getLogger(ZooKeeperTestingServerManager.class);

  private static final String SUPER_USER = "super";
  private static final String SUPER_PASSWORD = "hunter2****";

  public final TemporaryPorts temporaryPorts = TemporaryPorts.create();

  private final int port = temporaryPorts.localPort("zookeeper");
  private final String endpoint = "127.0.0.1:" + port;
  private final File dataDir;

  private CuratorFramework curator;
  private TestingServer server;

  static {
    try {
      final String superDigest = DigestAuthenticationProvider.generateDigest(
          SUPER_USER + ":" + SUPER_PASSWORD);

      final Field digestField = DigestAuthenticationProvider.class.getDeclaredField("superDigest");
      digestField.setAccessible(true);

      final Field modifiersField = Field.class.getDeclaredField("modifiers");
      modifiersField.setAccessible(true);
      modifiersField.setInt(digestField, digestField.getModifiers() & ~Modifier.FINAL);

      digestField.set(null, superDigest);
    } catch (NoSuchAlgorithmException | IllegalAccessException | NoSuchFieldException e) {
      // i mean, for real?
      throw Throwables.propagate(e);
    }
  }

  public ZooKeeperTestingServerManager() {
    this.dataDir = Files.createTempDir();

    final ExponentialBackoffRetry retryPolicy = new ExponentialBackoffRetry(1000, 3);

    final Builder builder = CuratorFrameworkFactory.builder()
        .connectString(endpoint)
        .retryPolicy(retryPolicy)
        .authorization("digest", (SUPER_USER + ":" + SUPER_PASSWORD).getBytes());

    curator = builder.build();

    log.info("starting CuratorFramework connected to {}", endpoint);

    curator.start();
    start();
  }

  @Override
  public void ensure(String path) throws Exception {
    curator.newNamespaceAwareEnsurePath(path).ensure(curator.getZookeeperClient());
  }

  @Override
  public void close() throws InterruptedException {
    try {
      server.close();
    } catch (IOException e) {
      Throwables.propagate(e);
    }

    stop();
    deleteQuietly(dataDir);
  }

  @Override
  public String connectString() {
    return endpoint;
  }

  @Override
  public CuratorFramework curatorWithSuperAuth() {
    return curator;
  }

  @Override
  public void awaitUp(long timeout, TimeUnit timeunit) throws TimeoutException {
    Polling.awaitUnchecked(timeout, timeunit, (Callable<Object>) () -> {
      try {
        return curatorWithSuperAuth().usingNamespace(null).getChildren().forPath("/");
      } catch (Exception e) {
        return null;
      }
    });
  }

  @Override
  public void awaitDown(int timeout, TimeUnit timeunit) throws TimeoutException {
    Polling.awaitUnchecked(timeout, timeunit, (Callable<Object>) () -> {
      try {
        curatorWithSuperAuth().usingNamespace(null).getChildren().forPath("/");
        return null;
      } catch (KeeperException.ConnectionLossException e) {
        return true;
      } catch (Exception e) {
        return null;
      }
    });
  }

  @Override
  public void start() {
    log.info("starting zookeeper TestingServer at port={}, dataDir={}", port, dataDir);
    try {
      server = new TestingServer(port, dataDir);
      awaitUp(2, MINUTES);
    } catch (Exception e) {
      throw Throwables.propagate(e);
    }
  }

  @Override
  public void stop() throws InterruptedException {
    try {
      server.stop();
    } catch (IOException e) {
      throw Throwables.propagate(e);
    }
  }

  public void backup(final Path destination) {
    try {
      FileUtils.copyDirectory(dataDir, destination.toFile());
    } catch (IOException e) {
      throw Throwables.propagate(e);
    }
  }

  public void restore(final Path source) {
    try {
      FileUtils.deleteDirectory(dataDir);
      FileUtils.copyDirectory(source.toFile(), dataDir);
    } catch (IOException e) {
      throw Throwables.propagate(e);
    }
  }

  public void reset() {
    FileUtils.deleteQuietly(dataDir);
  }
}


text:
define([
	'scripts/upfront/preset-settings/select-preset-item',
	'scripts/upfront/preset-settings/new-preset-item'
], function(SelectPresetItem, NewPresetItem) {
	var SelectPresetPanel = Upfront.Views.Editor.Settings.Panel.extend({
		className: 'preset-manager-panel',

		initialize: function (opts) {
			this.options = opts;

			this.newPresetItem = new NewPresetItem({
				model: this.model
			});

			this.selectPresetItem = new SelectPresetItem({
				model: this.model,
				presets: this.options.presets
			});

			this.listenTo(this.newPresetItem, 'upfront:presets:new', this.createPreset);
			this.listenTo(this.selectPresetItem, 'upfront:presets:edit', this.editPreset);

			this.settings = _([
				this.selectPresetItem,
				this.newPresetItem
			]);
		},

		// Propagate to parent
		createPreset: function(presetName) {
			this.trigger('upfront:presets:new', presetName);
		},

		// Propagate to parent
		editPreset: function(preset) {
			this.trigger('upfront:presets:edit', preset);
		}
	});

	return SelectPresetPanel;
});


text:
#include "hwconstant.h"
#include "base64dec.h"
#include "hwutil.h"

const int Base64Dec::DEC_CHUNK_MAX_LEN = 4;

/**
 * C'tor.
 *
 * @param filePath          File path
 */
Base64Dec::Base64Dec(std::string filePath) : Base64Dump(filePath) {
    _paddedCount    = 0;
    _curBitPos      = 0;

    initDecMap();
}

/**
 * Sets the error message with invalid input
 */
void Base64Dec::setInvalidInputError() const {
    std::string msg = "Error: Unable to decode base64 input : Invalid input. (error bit range ";
    msg += HwUtil::getString(_curBitPos+1);
    msg += ":";
    msg += HwUtil::getString(_curBitPos + DEC_CHUNK_MAX_LEN);
    msg += ")";

    HwUtil::setLastErrorMessage(msg);
}

/**
 * Validates the Encoded data to see if it follows
 * base-64 encoding standard. If = sign is present,
 * it has to be the last two.
 *
 * @param dataArray         Array of data
 *
 */
int Base64Dec::validateEncData( const unsigned char * dataArray )  {

    int status = 0;

    if( _paddedCount > 0 ) {
        status = HwConstant::ERROR_INVALID_INPUT;
    } else {
        unsigned char data = 0;
        for( int i=0; i<DEC_CHUNK_MAX_LEN; i++ ) {
            data = dataArray[i];
            char c = static_cast<char>(data);

            if( ! isMapHasKey(c)) {
                if( '=' == c ) {
                    _paddedCount++;
                } else {
                    status = HwConstant::ERROR_INVALID_INPUT;
                }
            }

            if( (0 == status) && (_paddedCount > 0) ) {
                if( _paddedCount > 2 ) {
                    status = HwConstant::ERROR_INVALID_INPUT;
                } else {
                    if( i < 2 ) { //padded character is in the first 2 bytes - error
                        status = HwConstant::ERROR_INVALID_INPUT;
                    } else if( 2 == i ) { //if second last character is padded, last should also be padded
                        c = static_cast<char>(dataArray[3]);
                        if( '=' != c ) {
                            status = HwConstant::ERROR_INVALID_INPUT;
                        }
                    }
                }
            }
        }
    }

    if( 0 != status ) {
        setInvalidInputError();
    }

    return status;
}

/**
 * Outputs the decoded data for the given 4 bytes of encoded data.
 *
 * @param dataArray             Array of data
 */
int Base64Dec::outputDecodedData( const unsigned char * dataArray ) {
    int status = 0;
    int i = 0;
    char c = '0';
    unsigned char data = 0;
    unsigned int intData = 0;

    for( i=0; i<DEC_CHUNK_MAX_LEN; i++ ) {
        data = dataArray[i];
        c = static_cast<char>(data);

        if( isMapHasKey(c)) {
            data = _decMap[c];
        } else if( '=' == c ) {
            data = 0;  //padded value
        } else {
            //should never reach here
            status = HwConstant::ERROR_INVALID_INPUT;
            HwUtil::setLastErrorMessage("Invalid data file - error point");
            break;
        }

        //we are interested in only the last 6 bits of a byte.
        //So, we'll shift the bits by 2 to the left, so that top
        //6 bits (MSB) are the useful data
        data = (data << 2);

        //shift to the left of the int (first one will go up to 26)
        unsigned int tempIntData = 0;
        tempIntData = data << ((3-i)*6);
        //shift 2 bit out to even the data
        tempIntData = (tempIntData >> 2);

        intData |= tempIntData;
    }

    unsigned char outputArray[3] = {0,0,0};
    //get the 3 original bytes
    for(i=0; i<3; i++ ) {
        data = (intData >> (i*8)) & 0xff; //get each byte
        //data is extracted in reverse order, so start stroing from the bottom
        outputArray[2-i] = data;
    }

    unsigned char * outputArray_ptr = NULL;
    int arraySize = (3 - _paddedCount); //take care of the padded data towards the end
    status = createBuffer(arraySize, outputArray_ptr );

    //check - in case
    assert( (arraySize >0) && (arraySize <= 3) );

    if( 0 == status ) {
        for(i=0; i<arraySize;i++){
            outputArray_ptr[i] = outputArray[i];

        }

        //print the data to console
        HwUtil::writeOutput( outputArray_ptr, arraySize );
        delete [] outputArray_ptr;
    }

    return status;
}

/**
 * Virtual D'tor.
 */
Base64Dec::~Base64Dec() {}

/**
 * Performs the hex dump operation.
 *
 * @param buffer_ptr        Pointer to buffer
 */
int Base64Dec::performBase64Dec( const unsigned char *buffer_ptr ) {

    assert(NULL != buffer_ptr);

    int status = 0;

    status = validateEncData(buffer_ptr);

    if( 0 == status ) {
        status = outputDecodedData(buffer_ptr);

        _curBitPos += DEC_CHUNK_MAX_LEN; //advance the bit pos by 4
    }

    return status;
}

/**
 * Dumps the output (based on input file or stdin)
 */
int Base64Dec::dump() {

    int status          = 0;
    int readLen         = 0;
    unsigned char data  = 0;
    int curIndex        = 0; //current index within the tempBuffer.

    unsigned char *buffer_ptr = NULL;
    unsigned char tempBuffer[DEC_CHUNK_MAX_LEN];

    status = openInputFile();

    if( 0 == status ) {
        status = createBuffer(HwConstant::BUFFER_SIZE, buffer_ptr );

        if( 0 == status ) {
            while( (!feof(_fp)) && (0 == status) ) {
                readLen = fread(buffer_ptr,
                                sizeof(unsigned char),
                                HwConstant::BUFFER_SIZE,
                                _fp );

                status = checkFileReadStatus();

                if( 0 == status ) {
                    if( readLen > 0 ) {
                        for(int i=0; i<readLen; i++) {
                            data = buffer_ptr[i];
                            //ignore the line break characters from the input file
                            if( 10 != data ) {
                                tempBuffer[curIndex] = data;
                                curIndex++;
                                if( DEC_CHUNK_MAX_LEN == curIndex ) {
                                    status = performBase64Dec(tempBuffer);
                                    curIndex = 0;

                                    if( 0 != status ) {
                                        break; //break for loop in case of error
                                    }
                                }
                            }
                        }
                    }
                }
            }

            //delete the buffer
            delete [] buffer_ptr;
            buffer_ptr = NULL;
        }

        //close input file
        closeInputFile();
    }

    if( (0 == status) && (curIndex != 0 ) ) {
        status = HwConstant::ERROR_INVALID_INPUT;
        setInvalidInputError();
    }

    if( (0 != status) && (_curBitPos >= DEC_CHUNK_MAX_LEN) ) {
        //insert a blank line if some data got outputted
        //so that error msg can be in a new line
        std::string emptyStr;
        HwUtil::writeOutputLn(emptyStr);
    }

    return status;
}

/**
 * Initializes the decoding map
 */
void Base64Dec::initDecMap() {
    unsigned char index = 0;
    unsigned char i = 0;

    //fill A-Z
    for(i=0;i<26; i++ ) {
        char c = char(i + 65); //ascii 65 = A
        _decMap[c] = index++;
    }
    //fill a-z
    for(i=0;i<26; i++ ) {
        char c = char(i + 97); //ascii 97 = a
        _decMap[c] = index++;
    }
    //fill 0-9
    for(i=0;i<10; i++ ) {
        char c = char(i + 48); //ascii 48 = 0
        _decMap[c] = index++;
    }
    _decMap['+'] = index++;
    _decMap['/'] = index++;
}

/**
 * Returns true, if the map contains the given key
 */
bool Base64Dec::isMapHasKey( unsigned char key) const {
    bool  status = false;

    Base64DecMap::const_iterator iter = _decMap.find(key);

    if( iter != _decMap.end() ) {
        status = true;
    }

    return status;
}


text:
typedef void(^ViAPIReadyCb)(NSDictionary* data, NSError* error);

@protocol ViAPIService <NSObject>

-(BOOL)getResource:(NSString*)resourcePath onReady:(ViAPIReadyCb)readyCb;

@optional  // SOME DAY ...

-(BOOL)postData:(NSDictionary*)data forResource:(NSString*)resourcePath onReady:(ViAPIReadyCb)readyCb;
-(BOOL)putData:(NSDictionary*)data forResource:(NSString*)resourcePath onReady:(ViAPIReadyCb)readyCb;

-(BOOL)deleteResource:(NSString*)resourcePath onReady:(ViAPIReadyCb)readyCb;

@end


text:
package org.eclipse.cdt.internal.pdom.tests;

import java.io.File;
import java.util.Random;

import junit.framework.Test;

import org.eclipse.cdt.core.testplugin.CTestPlugin;
import org.eclipse.cdt.core.testplugin.util.BaseTestCase;
import org.eclipse.cdt.internal.core.pdom.db.BTree;
import org.eclipse.cdt.internal.core.pdom.db.ChunkCache;
import org.eclipse.cdt.internal.core.pdom.db.Database;
import org.eclipse.cdt.internal.core.pdom.db.IBTreeComparator;
import org.eclipse.cdt.internal.core.pdom.db.IBTreeVisitor;
import org.eclipse.cdt.internal.core.pdom.db.IString;
import org.eclipse.cdt.internal.core.pdom.db.ShortString;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;

/**
 * Tests for the {@link Database} class.
 */
public class DatabaseTest extends BaseTestCase {
	// This constant can be used to run the test with very large databases.
	// Try, for example, setting it to Integer.MAX_VALUE * 7L;
	private static final long TEST_OFFSET = 0;
	protected Database db;

	@Override
	protected void setUp() throws Exception {
		super.setUp();
		db = new Database(getTestDir().append(getName() + System.currentTimeMillis() + ".dat").toFile(),
				new ChunkCache(), 0, false);
		db.setExclusiveLock();

		// Allocate all database chunks up to TEST_OFFSET.
		int count = 0;
		for (long offset = 0; offset < TEST_OFFSET;) {
			offset = db.malloc(Database.MAX_MALLOC_SIZE);
			if (++count >= 1000) {
				db.flush();
				count = 0;
			}
		}
		db.flush();
	}

	public static Test suite() {
		return suite(DatabaseTest.class);
	}

	protected IPath getTestDir() {
		IPath path = CTestPlugin.getDefault().getStateLocation().append("tests/");
		File file = path.toFile();
		if (!file.exists())
			file.mkdir();
		return path;
	}

	@Override
	protected void tearDown() throws Exception {
		db.close();
		if (!db.getLocation().delete()) {
			db.getLocation().deleteOnExit();
		}
		db= null;
	}

	public void testBlockSizeAndFirstBlock() throws Exception {
		assertEquals(0, db.getVersion());

		final int realsize = 42;
		final int deltas = (realsize + Database.BLOCK_HEADER_SIZE + Database.BLOCK_SIZE_DELTA - 1) / Database.BLOCK_SIZE_DELTA;
		final int blocksize = deltas * Database.BLOCK_SIZE_DELTA;
		final int freeDeltas= Database.CHUNK_SIZE / Database.BLOCK_SIZE_DELTA - deltas;

		long mem = db.malloc(realsize);
		assertEquals(-blocksize, db.getShort(mem - Database.BLOCK_HEADER_SIZE));
		db.free(mem);
		assertEquals(blocksize, db.getShort(mem - Database.BLOCK_HEADER_SIZE));
		assertEquals(mem, db.getRecPtr((deltas - Database.MIN_BLOCK_DELTAS +1 ) * Database.INT_SIZE));
		assertEquals(mem + blocksize, db.getRecPtr((freeDeltas - Database.MIN_BLOCK_DELTAS + 1) * Database.INT_SIZE));
	}

	public void testBug192437() throws Exception {
		File tmp= File.createTempFile("readOnlyEmpty", ".db");
		try {
			tmp.setReadOnly();

			/* check opening a readonly file for rw access fails */
			try {
				new Database(tmp, ChunkCache.getSharedInstance(), 0, false);
				fail("A readonly file should not be openable with write-access");
			} catch (CoreException e) {
				// we expect to get a failure here
			}

			/* check opening a readonly file for read access does not fail */
			try {
				new Database(tmp, ChunkCache.getSharedInstance(), 0, true);
			} catch (CoreException e) {
				fail("A readonly file should be readable by a permanently readonly database " + e);
			}
		} finally {
			tmp.delete(); // this may be pointless on some platforms
		}
	}

	public void testFreeBlockLinking() throws Exception {
		final int realsize = 42;
		final int deltas = (realsize + Database.BLOCK_HEADER_SIZE + Database.BLOCK_SIZE_DELTA - 1) / Database.BLOCK_SIZE_DELTA;
		final int blocksize = deltas * Database.BLOCK_SIZE_DELTA;
		final int freeDeltas= Database.MIN_BLOCK_DELTAS - deltas;

		long mem1 = db.malloc(realsize);
		long mem2 = db.malloc(realsize);
		db.free(mem1);
		db.free(mem2);
		assertEquals(mem2, db.getRecPtr((deltas - Database.MIN_BLOCK_DELTAS + 1) * Database.INT_SIZE));
		assertEquals(0, db.getRecPtr(mem2));
		assertEquals(mem1, db.getRecPtr(mem2 + Database.INT_SIZE));
		assertEquals(mem2, db.getRecPtr(mem1));
		assertEquals(0, db.getRecPtr(mem1 + Database.INT_SIZE));
	}

	public void testSimpleAllocationLifecycle() throws Exception {
		long mem1 = db.malloc(42);
		db.free(mem1);
		long mem2 = db.malloc(42);
		assertEquals(mem2, mem1);
	}

	private static class FindVisitor implements IBTreeVisitor {
		private Database db;
		private String key;
		private long record;

		public FindVisitor(Database db, String key) {
			this.db = db;
			this.key = key;
		}

		@Override
		public int compare(long record) throws CoreException {
			return db.getString(db.getRecPtr(record + 4)).compare(key, true);
		}

		@Override
		public boolean visit(long record) throws CoreException {
			this.record = record;
			return false;
		}

		public long getRecord() {
			return record;
		}
	}

	public void testStringsInBTree() throws Exception {
		String[] names = {
				"ARLENE",
				"BRET",
				"CINDY",
				"DENNIS",
				"EMILY",
				"FRANKLIN",
				"GERT",
				"HARVEY",
				"IRENE",
				"JOSE",
				"KATRINA",
				"LEE",
				"MARIA",
				"NATE",
				"OPHELIA",
				"PHILIPPE",
				"RITA",
				"STAN",
				"TAMMY",
				"VINCE",
				"WILMA",
				"ALPHA",
				"BETA"
		};

		IBTreeComparator comparator = new IBTreeComparator() {
			@Override
			public int compare(long record1, long record2) throws CoreException {
				IString string1 = db.getString(db.getRecPtr(record1 + 4));
				IString string2 = db.getString(db.getRecPtr(record2 + 4));
				return string1.compare(string2, true);
			}
		};

		BTree btree = new BTree(db, Database.DATA_AREA, comparator);
		for (int i = 0; i < names.length; ++i) {
			String name = names[i];
			long record = db.malloc(8);
			db.putInt(record + 0, i);
			IString string = db.newString(name);
			db.putRecPtr(record + 4, string.getRecord());
			btree.insert(record);
		}

		for (int i = 0; i < names.length; ++i) {
			String name = names[i];
			FindVisitor finder = new FindVisitor(db, name);
			btree.accept(finder);
			long record = finder.getRecord();
			assertTrue(record != 0);
			assertEquals(i, db.getInt(record));
			IString rname = db.getString(db.getRecPtr(record + 4));
			assertTrue(rname.equals(name));
		}
	}

	private final int GT = 1, LT = -1, EQ = 0;

	public void testShortStringComparison() throws CoreException {
		Random r= new Random(90210);

		assertCMP("",  EQ, "", true);
		assertCMP("",  EQ, "", false);

		doTrials(1000, 1, ShortString.MAX_BYTE_LENGTH / 2, r, true);
		doTrials(1000, 1, ShortString.MAX_BYTE_LENGTH / 2, r, false);
		doTrials(1000, 1, ShortString.MAX_BYTE_LENGTH, r, true);
		doTrials(1000, 1, ShortString.MAX_BYTE_LENGTH, r, false);

		assertCMP("a",  LT, "b", true);
		assertCMP("aa", LT, "ab", true);
		assertCMP("a",  EQ, "a", true);

		assertCMP("a",  GT, "A", true);
		assertCMP("aa", GT, "aA", true);
		assertCMP("a",  GT, "B", true);

		assertCMP("a",  EQ, "a", false);
		assertCMP("a",  EQ, "A", false);
	}

	public void testLongStringComparison() throws CoreException {
		Random r= new Random(314159265);
		doTrials(100, ShortString.MAX_BYTE_LENGTH + 1, ShortString.MAX_BYTE_LENGTH * 2, r, true);
		doTrials(100, ShortString.MAX_BYTE_LENGTH + 1, ShortString.MAX_BYTE_LENGTH * 2, r, false);
	}

	private void doTrials(int n, int min, int max, Random r, boolean caseSensitive) throws CoreException {
		long start = System.currentTimeMillis();
		for (int i= 0; i < n; i++) {
			String a = randomString(min, max, r);
			String b = randomString(min, max, r);
			int expected = caseSensitive ? a.compareTo(b) : a.compareToIgnoreCase(b);
			assertCMP(a, expected, b, caseSensitive);
		}
//		System.out.print("Trials: " + n + " Max length: " + max + " ignoreCase: " + !caseSensitive);
//		System.out.println(" Time: " + (System.currentTimeMillis() - start));
	}

	private String randomString(int min, int max, Random r) {
		int len = min + r.nextInt(max - min);
		return randomString(len, r);
	}

	private String randomString(int len, Random r) {
		StringBuilder result = new StringBuilder(len);
		for (int i= 0; i < len; i++) {
			result.append(randomChar(r));
		}
		return result.toString();
	}

	private char randomChar(Random r) {
		// We only match String.compareToIgnoreCase behavior within this limited range.
		return (char) (32 + r.nextInt(40));
	}

	private void assertCMP(String a, int expected, String b, boolean caseSensitive) throws CoreException {
		char[] acs = a.toCharArray();
		char[] bcs = b.toCharArray();
		IString aiss = db.newString(a);
		IString biss = db.newString(b);
		IString aisc = db.newString(acs);
		IString bisc = db.newString(bcs);

		assertEquals(a.hashCode(), aiss.hashCode());
		assertEquals(a.hashCode(), aisc.hashCode());
		assertEquals(b.hashCode(), biss.hashCode());
		assertEquals(b.hashCode(), bisc.hashCode());

		assertEquals(aiss, a);
		assertEquals(aisc, a);
		assertEquals(biss, b);
		assertEquals(bisc, b);

		assertSignEquals(expected, aiss.compare(bcs, caseSensitive));
		assertSignEquals(expected, aiss.compare(biss, caseSensitive));
		assertSignEquals(expected, aiss.compare(bisc, caseSensitive));
		assertSignEquals(expected, aiss.compare(b, caseSensitive));
		assertSignEquals(expected, aiss.comparePrefix(bcs, caseSensitive));

		assertSignEquals(expected, -biss.compare(acs, caseSensitive));
		assertSignEquals(expected, -biss.compare(aiss, caseSensitive));
		assertSignEquals(expected, -biss.compare(aisc, caseSensitive));
		assertSignEquals(expected, -biss.compare(a, caseSensitive));
		assertSignEquals(expected, -biss.comparePrefix(acs, caseSensitive));

		if (!caseSensitive && expected != 0) {
			assertSignEquals(expected, aiss.compareCompatibleWithIgnoreCase(bcs));
			assertSignEquals(expected, aiss.compareCompatibleWithIgnoreCase(biss));
			assertSignEquals(expected, aiss.compareCompatibleWithIgnoreCase(bisc));

			assertSignEquals(expected, -biss.compareCompatibleWithIgnoreCase(acs));
			assertSignEquals(expected, -biss.compareCompatibleWithIgnoreCase(aiss));
			assertSignEquals(expected, -biss.compareCompatibleWithIgnoreCase(aisc));
		}
	}

	private void assertSignEquals(int a, int b) {
		a= a < 0 ? -1 : (a > 0 ? 1 : 0);
		b= b < 0 ? -1 : (b > 0 ? 1 : 0);
		assertEquals(a, b);
	}
}