text:
/******************************************************************************

	File: Primitiv.cpp

	Description:

	Implementation of the Interpreter class' primitive methods

******************************************************************************/
#include "Ist.h"
#pragma code_seg(PRIM_SEG)

#include "ObjMem.h"
#include "Interprt.h"
#include "rc_vm.h"
#include "InterprtPrim.inl"

// Smalltalk classes
#include "STBehavior.h"
#include "STArray.h"
#include "STByteArray.h"
#include "STAssoc.h"

#ifdef PROFILING
	extern size_t blocksInstantiated;
	extern size_t	freeBlocks = 0;
	extern size_t contextsSuspended;
#endif

///////////////////////////////////////////////////////////////////////////////
// Primitive Helper routines

Oop* PRIMCALL Interpreter::unusedPrimitive(Oop* const, primargcount_t)
{
	// Note that the failure code is not set.
#ifdef _DEBUG
	auto primitiveIndex = m_registers.m_oopNewMethod->m_location->m_header.primitiveIndex;
	TRACESTREAM << L"Unused primitive " << primitiveIndex << " in " << m_registers.m_oopNewMethod << std::endl;
#endif

	return primitiveFailure(_PrimitiveFailureCode::NotImplemented);
}

///////////////////////////////////////////////////////////////////////////////
//	Float Primitives - See FlotPrim.cpp
///////////////////////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////////////////////
//	String Primitives - See StrgPrim.cpp
///////////////////////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////////////////////
//	External Call Primitives - See ExtCall.cpp
///////////////////////////////////////////////////////////////////////////////

#pragma code_seg(MEM_SEG)

Oop* PRIMCALL Interpreter::primitiveBasicIdentityHash(Oop* const sp, primargcount_t)
{
	OTE* ote = (OTE*)*sp;
	*sp = ObjectMemoryIntegerObjectOf(ote->identityHash());
	return sp;
}

Oop* PRIMCALL Interpreter::primitiveIdentityHash(Oop* const sp, primargcount_t)
{
	OTE* ote = (OTE*)*sp;
	*sp = ObjectMemoryIntegerObjectOf(ote->identityHash() << 14);
	return sp;
}

Oop* PRIMCALL Interpreter::primitiveClass(Oop* const sp, primargcount_t)
{
	Oop receiver = *sp;
	*sp = reinterpret_cast<Oop>(!ObjectMemoryIsIntegerObject(receiver)
			? reinterpret_cast<OTE*>(receiver)->m_oteClass : Pointers.ClassSmallInteger);
	return sp;
}

Oop* PRIMCALL Interpreter::primitiveIdentical(Oop* const sp, primargcount_t)
{
	Oop receiver = *(sp-1);
	Oop arg = *sp;
	*(sp - 1) = reinterpret_cast<Oop>(arg == receiver ? Pointers.True : Pointers.False);
	return sp - 1;
}

// This primitive is unusual(like primitiveClass) in that it cannot fail
// Essentially same code as shortSpecialSendBasicSize
Oop* PRIMCALL Interpreter::primitiveSize(Oop* const sp, primargcount_t)
{
	// The primitive assumes it is never called for SmallIntegers.
	OTE* oteReceiver = reinterpret_cast<OTE*>(*sp);
	size_t bytesSize = oteReceiver->getSize();
	if (oteReceiver->m_flags.m_pointer)
	{
		InstanceSpecification instSpec = oteReceiver->m_oteClass->m_location->m_instanceSpec;
		// The compiler generates poor code here if we access the InstanceSpecification::m_fixedFields bit field directly
		// so we do the bit manipulations directly to guide the compiler into generating more efficient asm.
		// This does mean we are using internal knowledge here that the fixedFields bitfield is left-shifted 1, and that
		// SmallIntegers are also left-shifted 1 with the bottom bit set
		Oop value = ((bytesSize >> 1) - (instSpec.m_value & InstanceSpecification::FixedFieldsMask)) | 1;
		*sp = value;
		return sp;
	}
	else
	{
		size_t shift = static_cast<size_t>(ObjectMemory::GetBytesElementSize(reinterpret_cast<BytesOTE*>(oteReceiver)));
		*sp = integerObjectOf(bytesSize >> shift);

		return sp;
	}
}

// Primitive to speed up #isKindOf: (so we don't have to implement too many #isXXXXX methods,
// which are nasty, requiring a change to Object for each).
Oop* PRIMCALL Interpreter::primitiveIsKindOf(Oop* const sp, primargcount_t)
{
	Oop arg = *sp;
	// Nothing can be a kind of SmallInteger instance
	if (!ObjectMemoryIsIntegerObject(arg))
	{
		Oop receiver = *(sp - 1);
		BehaviorOTE* oteArg = reinterpret_cast<BehaviorOTE*>(arg);
		BehaviorOTE* oteClass = !ObjectMemoryIsIntegerObject(receiver)
			? reinterpret_cast<OTE*>(receiver)->m_oteClass
			: Pointers.ClassSmallInteger;
		while (oteClass != oteArg)
		{
			// Small optimisation to terminate when 'class' body is null, as this is true for nil
			ST::Behavior* pBehavior = oteClass->m_location;
			if (pBehavior == nullptr)
			{
				*(sp - 1) = reinterpret_cast<Oop>(Pointers.False);
				return sp - 1;
			}
			oteClass = oteClass->m_location->m_superclass;
		};

		*(sp - 1) = reinterpret_cast<Oop>(Pointers.True);
		return sp - 1;
	}

	*(sp - 1) = reinterpret_cast<Oop>(Pointers.False);
	return sp - 1;
}

// Does not use successFlag, and returns a clean stack because can only succeed if
// argument is a positive SmallInteger
Oop* PRIMCALL Interpreter::primitiveResize(Oop* const sp, primargcount_t)
{
	Oop integerPointer = *sp;

	if (!ObjectMemoryIsIntegerObject(integerPointer))
		return primitiveFailure(_PrimitiveFailureCode::InvalidParameter1);	// Size not a positive SmallInteger

	SmallInteger newSize = ObjectMemoryIntegerValueOf(integerPointer);
	if (newSize < 0)
		return primitiveFailure(_PrimitiveFailureCode::InvalidParameter1);

	Oop oopReceiver = *(sp - 1);
	if (ObjectMemoryIsIntegerObject(oopReceiver))
		return primitiveFailure(_PrimitiveFailureCode::ObjectTypeMismatch);
	OTE* oteReceiver = reinterpret_cast<OTE*>(oopReceiver);

	if (oteReceiver->isPointers())
	{
		Behavior* behavior = oteReceiver->m_oteClass->m_location;
		if (!behavior->isIndexable())
			return primitiveFailure(_PrimitiveFailureCode::ObjectTypeMismatch);

		size_t newPointerSize = static_cast<size_t>(newSize) + behavior->fixedFields();

		ptrdiff_t currentPointerSize = oteReceiver->pointersSizeForUpdate();
		if (currentPointerSize == (ptrdiff_t)newPointerSize)
		{
			// No change, succeed
			return sp - 1;
		}

		if (currentPointerSize < 0)
		{
			// Immutable
			return primitiveFailure(_PrimitiveFailureCode::AccessViolation);
		}

		// Changing size of mutable pointer object
		bool bCountDownRemoved = reinterpret_cast<OTE*>(Interpreter::actualActiveProcessPointer()) != oteReceiver;
		VariantObject* pNew = ObjectMemory::resize(reinterpret_cast<PointersOTE*>(oteReceiver),
			newPointerSize,
			bCountDownRemoved);
		if (pNew == nullptr)
		{
			return primitiveFailure(_PrimitiveFailureCode::NoMemory);
		}
	}
	else
	{
		ptrdiff_t currentByteSize = oteReceiver->bytesSizeForUpdate();
		if (currentByteSize == static_cast<ptrdiff_t>(newSize))
		{
			// No change, succeed
			return sp - 1;
		}

		if (currentByteSize < 0)
		{
			// Immutable
			return primitiveFailure(_PrimitiveFailureCode::AccessViolation);
		}

		// Changing size of mutable byte object
		VariantByteObject* pNew = ObjectMemory::resize(reinterpret_cast<BytesOTE*>(oteReceiver), newSize);
		if (pNew == nullptr && newSize != 0)
		{
			return primitiveFailure(_PrimitiveFailureCode::NoMemory);
		}
	}

	return sp - 1;
}

Oop* PRIMCALL Interpreter::primitiveChangeBehavior(Oop* const sp, primargcount_t)
{
	// Receiver becomes an instance of the class specified as the argument - neither
	// receiver or arg may be SmallIntegers, and the shape of the receiver's current class
	// must be identical to its new class.

	Oop arg = *sp;
	if (!ObjectMemoryIsIntegerObject(arg))
	{
		BehaviorOTE* oteClassArg = reinterpret_cast<BehaviorOTE*>(arg);

		// We must determine if the argument is a Class - get the head strap out and
		// then remember :
		//	A class' class is an instance of Metaclass (e.g. if we send #class to
		//	to Object, then we get the Metaclass instance 'Object class') THEREFORE
		// The class of the class of a Class is Metaclass!

		if (oteClassArg->m_oteClass->m_oteClass == Pointers.ClassMetaclass)
		{
			// We have established that the argument is indeed a Class object, now lets examine the receiver

			Oop receiver = *(sp - 1);
			if (!ObjectMemoryIsIntegerObject(receiver))
			{
				// The receiver is a non - immediate object
				OTE* oteReceiver = reinterpret_cast<OTE*>(receiver);
				if (oteReceiver->m_oteClass != oteClassArg)
				{
					// We must check class shapes the same, so compare instance spec. of receivers class with that of new class by xor'ing together
					// and then checking if any of the important shape bits are different
					if (hasCompatibleShape(oteReceiver, oteClassArg->m_location))
					{
						ObjectMemory::storePointerWithValue(reinterpret_cast<OTE*&>(oteReceiver->m_oteClass), reinterpret_cast<OTE*>(oteClassArg));
						return sp - 1;
					}
				}
				else
				{
					// No change
					return sp - 1;
				}

				// Shapes differ in significant ways
				return primitiveFailure(_PrimitiveFailureCode::ObjectTypeMismatch);
			}
			else
			{
				if (oteClassArg != Pointers.ClassSmallInteger)
				{
					// The receiver is a SmallInteger, and can be mutated to a variable byte object
					// which we have to allocate
					if (!oteClassArg->m_location->m_instanceSpec.m_pointers)
					{
						BytesOTE* oteBytes = ObjectMemory::newByteObject<false, false>(oteClassArg, sizeof(SmallUinteger));
						oteClassArg->countUp();
						*reinterpret_cast<SmallUinteger*>(oteBytes->m_location->m_fields) = ObjectMemoryIntegerValueOf(receiver);

						// We've created a new object, so must replace the receiver at stack top
						*(sp - 1) = reinterpret_cast<Oop>(oteBytes);
						ObjectMemory::AddToZct(reinterpret_cast<OTE*>(oteBytes));
						return sp - 1;
					}
				}
				else
				{
					// No change
					return sp - 1;
				}

				// Can't change class of SmallInteger to a pointer object class
				return primitiveFailure(_PrimitiveFailureCode::ObjectTypeMismatch);
			}
		}
		// Arg is not a class
		return primitiveFailure(_PrimitiveFailureCode::InvalidParameter1);
	}
	// Arg is a SmallInteger (not a class)
	return primitiveFailure(_PrimitiveFailureCode::InvalidParameter1);
}

boolean Interpreter::hasCompatibleShape(OTE* oteReceiver, ST::Behavior* argClass)
{
	BehaviorOTE* oteReceiverClass = oteReceiver->m_oteClass;
	Behavior* receiverClass = oteReceiverClass->m_location;

	InstanceSpecification sourceClassShape = receiverClass->m_instanceSpec;
	InstanceSpecification targetClassShape = argClass->m_instanceSpec;
	SmallUinteger diff = (sourceClassShape.m_value ^ targetClassShape.m_value) & ~InstanceSpecification::IndirectMask;

	if (diff == 0) return true;	// Exact match (ignoring indirection bit)

	diff &= ~(InstanceSpecification::FixedFieldsMask| InstanceSpecification::IndexableMask);
	if (diff == 0)
	{
		// Only the number of fixed fields or indexability is being changed. This is OK if:
		//	- target class is fixed size and that size is the same as the current size
		//	- target class is indexable, and the current size is sufficient to at least cover all its fixed fields
		// Whether the source is indexable or fixed not does not actually matter
		size_t pointerSize = oteReceiver->pointersSize();
		return targetClassShape.m_indexable
			? pointerSize >= targetClassShape.m_fixedFields
			: pointerSize == targetClassShape.m_fixedFields;
	}

	return false;
}

Oop* PRIMCALL Interpreter::primitiveExtraInstanceSpec(Oop* const sp, primargcount_t)
{
	BehaviorOTE* oteClass = reinterpret_cast<BehaviorOTE*>(*sp);
	*sp = (oteClass->m_location->m_instanceSpec.m_value >> 15) | 1;
	return sp;
}

// Set the special behavior bits of an object according to the mask
// Takes a SmallInteger argument, of which only the low order word is significant.
// The high order byte of the low order word specifies the AND mask, used to mask out bits,
// The low order byte of the low order word specifies the OR mask, used to mask in bits.
// The current value of the special behavior bits is then answered.
// The primitive ensures that the current values of bits which may affect the stability of the
// system cannot be modified.
// To query the current value of the special bits, pass in 16rFF00.
Oop* PRIMCALL Interpreter::primitiveSetSpecialBehavior(Oop* const sp, primargcount_t)
{
	Oop oopMask = *sp;
	if (ObjectMemoryIsIntegerObject(oopMask))
	{
		SmallInteger mask = ObjectMemoryIntegerValueOf(oopMask);
		Oop oopReceiver = *(sp - 1);
		if (!ObjectMemoryIsIntegerObject(oopReceiver))
		{
			static const uint8_t criticalPointerObjectFlags = static_cast<uint8_t>(OTEFlags::PointerMask | OTEFlags::MarkMask | OTEFlags::FreeMask | OTEFlags::SpaceMask);
			static const uint8_t criticalByteObjectFlags = static_cast<uint8_t>(OTEFlags::PointerMask | OTEFlags::MarkMask | OTEFlags::FreeMask | OTEFlags::SpaceMask | OTEFlags::WeakOrZMask);

			OTE* oteReceiver = reinterpret_cast<OTE*>(oopReceiver);

			// Ensure the masks cannot affect the critical bits of the flags
			// the AND mask, must have the pointer, mark, and free bits set, to keep these bits
			// the OR mask, must have those bits reset so as not to add them
			uint8_t criticalFlags = oteReceiver->m_flags.m_pointer ? criticalPointerObjectFlags : criticalByteObjectFlags;
			uint8_t andMask = (mask >> 8) | criticalFlags;
			uint8_t orMask = mask & static_cast<uint8_t>(~criticalFlags);

			uint8_t oldFlags = oteReceiver->m_ubFlags;
			oteReceiver->m_ubFlags = (oldFlags & andMask) | orMask;

			ASSERT(oteReceiver->isNullTerminated() == oteReceiver->m_oteClass->m_location->m_instanceSpec.m_nullTerminated);

			*(sp - 1) = ObjectMemoryIntegerObjectOf(oldFlags);
			return sp - 1;
		}
		else
		{
			// SmallIntegers can't have special behavior
			return primitiveFailure(_PrimitiveFailureCode::ObjectTypeMismatch);
		}
	}
	else
	{
		// Mask is not a SmallInteger
		return primitiveFailure(_PrimitiveFailureCode::InvalidParameter1);
	}
}

#pragma code_seg(PROCESS_SEG)

// Remove a request from the last request queue, nil if none pending. Fails if argument is not an
// array of the correct length to receiver the popped Queue entry (currently 2 objects)
// Answers nil if the queue is empty, or the argument if an entry was successfully popped into it
Oop* PRIMCALL Interpreter::primitiveDeQBereavement(Oop* const sp, primargcount_t)
{
	Oop argPointer = *sp;
	if (ObjectMemoryIsIntegerObject(argPointer))
		return primitiveFailure(_PrimitiveFailureCode::InvalidParameter1);

	PointersOTE* oteArray = reinterpret_cast<PointersOTE*>(argPointer);
	VariantObject* array = oteArray->m_location;
	if (oteArray->m_oteClass != Pointers.ClassArray ||
		oteArray->pointersSize() != OopsPerBereavementQEntry)
		return primitiveFailure(_PrimitiveFailureCode::InvalidParameter1);

	// dequeueBereaved returns Pointers.True or Pointers.False
	OTE* answer = dequeueBereaved(array);
	*(sp-1) = reinterpret_cast<Oop>(answer);
	return sp-1;
}

///////////////////////////////////
// Clearing down the method cache is a very fast operation, so there is nothing
// to be gained at the moment from doing it more selectively (except that
// method lookups must be recached, so every time a method is installed, the
// system starts from scratch again).
// A more selective approach would require clearing down all entries that match
// a certain selector for a specified class and all its subclasses, because of the
// caching of inherited methods. Removing all entries for a specific method is
// not sufficient since this would not cater for the addition of methods when
// these override
#pragma code_seg(PRIM_SEG)

void Interpreter::flushCaches()
{
#ifdef _DEBUG
	DumpMethodCacheStats();
#endif

	ZeroMemory(methodCache, sizeof(methodCache));
}

Oop* PRIMCALL Interpreter::primitiveFlushCache(Oop* const sp, primargcount_t)
{
#ifdef _DEBUG
	DumpCacheStats();
#endif
	flushCaches();
	return sp;
}

// Separate atPut primitive is needed to write to the stack because the active process
// stack is not reference counted.
Oop* PRIMCALL Interpreter::primitiveStackAtPut(Oop* const sp, primargcount_t)
{
	Oop indexPointer = *(sp-1);
	if (!ObjectMemoryIsIntegerObject(indexPointer))
		return primitiveFailure(_PrimitiveFailureCode::InvalidParameter1);

	SmallInteger index = ObjectMemoryIntegerValueOf(indexPointer);
	if (index < 1)
		return primitiveFailure(_PrimitiveFailureCode::OutOfBounds);

	resizeActiveProcess();

	ProcessOTE* oteReceiver = reinterpret_cast<ProcessOTE*>(*(sp-2));
	Process* receiverProcess = static_cast<Process*>(oteReceiver->m_location);
	if (static_cast<size_t>(index) > receiverProcess->stackSize(oteReceiver))
			return primitiveFailure(_PrimitiveFailureCode::OutOfBounds);

	Oop argPointer = *sp;
	Oop oopExisting = receiverProcess->m_stack[index-1];

	// No ref. counting required writing to active process stack
	if (oteReceiver != m_registers.m_oteActiveProcess)
	{
		ObjectMemory::countUp(argPointer);
		ObjectMemory::countDown(oopExisting);
	}

	receiverProcess->m_stack[index-1] = argPointer;
	*(sp-2) = argPointer;
	return sp-2;
}

Oop* PRIMCALL Interpreter::primitiveIndexOfSP(Oop* const sp, primargcount_t)
{
	ProcessOTE* oteReceiver = reinterpret_cast<ProcessOTE*>(*(sp - 1));
	Oop oopArg = *sp;
	if (ObjectMemoryIsIntegerObject(oopArg))
	{
		Oop* address = reinterpret_cast<Oop*>(oopArg - 1);
		Process* proc = oteReceiver->m_location;
		if (address >= proc->m_stack && address < proc->m_stack + oteReceiver->getWordSize())
		{
			Oop index = (static_cast<uintptr_t>(address - proc->m_stack) << 1) + OnePointer;
			*(sp - 1) = index;
			return sp - 1;
		}
	}

	return primitiveFailure(_PrimitiveFailureCode::InvalidParameter1);
}

// Don't care what effect on stack is!!
[[noreturn]] void PRIMCALL Interpreter::primitiveQuit(Oop* const sp, primargcount_t)
{
	Oop argPointer = *sp;
	exitSmalltalk(ObjectMemoryIntegerValueOf(argPointer));
}

Oop* PRIMCALL Interpreter::primitiveReplacePointers(Oop* const sp, primargcount_t)
{
	Oop integerPointer = *sp;
	if (!ObjectMemoryIsIntegerObject(integerPointer))
		return primitiveFailure(_PrimitiveFailureCode::InvalidParameter4);	// startAt is not an integer
	SmallInteger startAt = ObjectMemoryIntegerValueOf(integerPointer);

	integerPointer = *(sp-1);
	if (!ObjectMemoryIsIntegerObject(integerPointer))
		return primitiveFailure(_PrimitiveFailureCode::InvalidParameter3);	// stop is not an integer
	SmallInteger stop = ObjectMemoryIntegerValueOf(integerPointer);

	integerPointer = *(sp-2);
	if (!ObjectMemoryIsIntegerObject(integerPointer))
		return primitiveFailure(_PrimitiveFailureCode::InvalidParameter2);	// start is not an integer
	SmallInteger start = ObjectMemoryIntegerValueOf(integerPointer);

	PointersOTE* argPointer = reinterpret_cast<PointersOTE*>(*(sp-3));
	if (ObjectMemoryIsIntegerObject(argPointer) || !argPointer->isPointers())
		return primitiveFailure(_PrimitiveFailureCode::InvalidParameter1);	// Argument MUST be pointer object

	if (stop >= start)
	{
		if (startAt < 1 || start < 1)
			return primitiveFailure(_PrimitiveFailureCode::OutOfBounds);		// Out-of-bounds

		// Empty move if stop before start, is considered valid regardless (strange but true)
		// this is the convention adopted by most implementations.

		// We can test that we're not going to write off the end of the argument
		auto length = argPointer->pointersSizeForUpdate();

		auto toOffset = argPointer->m_oteClass->m_location->fixedFields();

		// Adjust to zero-based indices into variable fields of target
		stop = stop - 1 + toOffset;
		start = start - 1 + toOffset;

		if (stop >= length)
			return primitiveFailure(_PrimitiveFailureCode::OutOfBounds);		// Bounds error (or object is immutable so size < 0)

		VariantObject* arg = reinterpret_cast<PointersOTE*>(argPointer)->m_location;
		Oop* pTo = arg->m_fields;

		PointersOTE* receiverPointer = reinterpret_cast<PointersOTE*>(*(sp-4));

		size_t fromSize = receiverPointer->pointersSize();
		auto fromOffset = receiverPointer->m_oteClass->m_location->fixedFields();
		// Adjust to zero based index into variable fields of source
		startAt = startAt - 1 + fromOffset;

		auto stopAt = startAt + stop - start;
		if (stopAt >= static_cast<ptrdiff_t>(fromSize))
			return primitiveFailure(_PrimitiveFailureCode::OutOfBounds);

		// Only works for pointer objects
		ASSERT(receiverPointer->isPointers());
		VariantObject* receiverObject = receiverPointer->m_location;

		Oop* pFrom = receiverObject->m_fields;

		// Overlapping upwards move?
		if (argPointer == receiverPointer && startAt < start)
		{
			// Need to do backwards
			for (auto i = stop - start; i >= 0; i--)
			{
				ObjectMemory::storePointerWithValue(pTo[start + i], pFrom[startAt + i]);
			}
		}
		else
		{
			// Do forwards
			for (auto i = 0; i <= stop - start; i++)
			{
				ObjectMemory::storePointerWithValue(pTo[start + i], pFrom[startAt + i]);
			}
		}
	}

	// Answers the argument by moving it down over the receiver
	*(sp-4) = reinterpret_cast<Oop>(argPointer);
	return sp-4;
}

Oop* PRIMCALL Interpreter::primitiveBasicAt(Oop* const sp, const primargcount_t argCount)
{
	Oop* newSp = sp - argCount;
	OTE* oteReceiver = reinterpret_cast<OTE*>(*newSp);
	Oop oopIndex = *(newSp + 1);

	if (ObjectMemoryIsIntegerObject(oopIndex))
	{
		SmallInteger index = ObjectMemoryIntegerValueOf(oopIndex) - 1;
		if (oteReceiver->m_flags.m_pointer)
		{
			size_t size = oteReceiver->pointersSize();
			const auto fixedFields = oteReceiver->m_oteClass->m_location->fixedFields();
			VariantObject* pointerObj = reinterpret_cast<PointersOTE*>(oteReceiver)->m_location;

			if (index >= 0 && static_cast<size_t>(index) + fixedFields < size)
			{
				Oop field = pointerObj->m_fields[index + fixedFields];
				*newSp = field;
				return newSp;
			}
			else
			{
				// Out of bounds
				return primitiveFailure(oteReceiver->m_oteClass->m_location->isIndexable() ? _PrimitiveFailureCode::OutOfBounds : _PrimitiveFailureCode::ObjectTypeMismatch);
			}
		}
		else
		{
			switch (ObjectMemory::GetBytesElementSize(reinterpret_cast<BytesOTE*>(oteReceiver)))
			{
			case ByteElementSize::Bytes:
				if (static_cast<size_t>(index) < oteReceiver->bytesSize())
				{
					uint8_t value = reinterpret_cast<BytesOTE*>(oteReceiver)->m_location->m_fields[index];
					*newSp = ObjectMemoryIntegerObjectOf(value);
					return newSp;
				}
				break;

			case ByteElementSize::Words:
				if (static_cast<size_t>(index) < (oteReceiver->bytesSize() / 2))
				{
					uint16_t value = reinterpret_cast<WordsOTE*>(oteReceiver)->m_location->m_fields[index];
					*newSp = ObjectMemoryIntegerObjectOf(value);
					return newSp;
				}
				break;

			case ByteElementSize::Quads:
				if (static_cast<size_t>(index) < (oteReceiver->bytesSize() / 4))
				{
					uint32_t value = reinterpret_cast<QuadsOTE*>(oteReceiver)->m_location->m_fields[index];
					StoreUnsigned32()(newSp, value);
					return newSp;
				}
				break;

			default:
				__assume(false);
				return primitiveFailure(_PrimitiveFailureCode::AssertionFailure);
			}

			// Out of bounds
			return primitiveFailure(_PrimitiveFailureCode::OutOfBounds);
		}
	}
	else
	{
		// Index not a smallinteger
		return primitiveFailure(_PrimitiveFailureCode::InvalidParameter1);
	}
}

Oop* PRIMCALL Interpreter::primitiveBasicAtPut(Oop* const sp, primargcount_t)
{
	Oop* const newSp = sp - 2;
	OTE* oteReceiver = reinterpret_cast<OTE*>(*newSp);
	Oop oopIndex = *(sp - 1);

	if (ObjectMemoryIsIntegerObject(oopIndex))
	{
		SmallInteger index = ObjectMemoryIntegerValueOf(oopIndex) - 1;
		if (index >= 0)
		{
			if (oteReceiver->m_flags.m_pointer)
			{
				// Store into pointer object

				const auto size = oteReceiver->pointersSizeForUpdate();
				const auto fixedFields = oteReceiver->m_oteClass->m_location->fixedFields();
				VariantObject* pointerObj = reinterpret_cast<PointersOTE*>(oteReceiver)->m_location;

				if (index + fixedFields < size)
				{
					Oop newValue = *sp;
					ObjectMemory::countUp(newValue);
					Oop oldValue = pointerObj->m_fields[index + fixedFields];
					pointerObj->m_fields[index + fixedFields] = newValue;
					ObjectMemory::countDown(oldValue);
					*newSp = newValue;
					return newSp;
				}
				else
				{
					// Out of bounds, not indexable, or immutable
					return primitiveFailure(size < 0
						? _PrimitiveFailureCode::AccessViolation
						: oteReceiver->m_oteClass->m_location->isIndexable()
							? _PrimitiveFailureCode::OutOfBounds
							: _PrimitiveFailureCode::ObjectTypeMismatch);
				}
			}
			else
			{
				// Store into byte object

				Oop oopValue = *sp;
				if (ObjectMemoryIsIntegerObject(oopValue))
				{
					const SmallUinteger newValue = ObjectMemoryIntegerValueOf(oopValue);
					const auto size = oteReceiver->bytesSizeForUpdate();

					switch (ObjectMemory::GetBytesElementSize(reinterpret_cast<BytesOTE*>(oteReceiver)))
					{
					case ByteElementSize::Bytes:
						if (newValue <= UINT8_MAX)
						{
							if (index < size)
							{
								reinterpret_cast<BytesOTE*>(oteReceiver)->m_location->m_fields[index] = static_cast<uint8_t>(newValue);
								*newSp = oopValue;
								return newSp;
							}
							else
							{
								return primitiveFailure(size < 0 ? _PrimitiveFailureCode::AccessViolation : _PrimitiveFailureCode::OutOfBounds);
							}
						}
						else
							return primitiveFailure(_PrimitiveFailureCode::IntegerOutOfRange);

					case ByteElementSize::Words:
						if (newValue <= UINT16_MAX)
						{
							if (index < (size / 2))
							{
								reinterpret_cast<WordsOTE*>(oteReceiver)->m_location->m_fields[index] = static_cast<uint16_t>(newValue);
								*newSp = oopValue;
								return newSp;
							}
							else
							{
								return primitiveFailure(size < 0 ? _PrimitiveFailureCode::AccessViolation : _PrimitiveFailureCode::OutOfBounds);
							}
						}
						else
							return primitiveFailure(_PrimitiveFailureCode::IntegerOutOfRange);

					case ByteElementSize::Quads:
						if (index < (size / 4))
						{
							reinterpret_cast<QuadsOTE*>(oteReceiver)->m_location->m_fields[index] = static_cast<uint32_t>(newValue);
							*newSp = oopValue;
							return newSp;
						}
						else
						{
							return primitiveFailure(size < 0 ? _PrimitiveFailureCode::AccessViolation : _PrimitiveFailureCode::OutOfBounds);
						}

					default:
						__assume(false);
						// Invalid encoding length
						return primitiveFailure(_PrimitiveFailureCode::AssertionFailure);
					}
				}
				// Not a SmallInteger value to store
				return primitiveFailure(_PrimitiveFailureCode::InvalidParameter2);
			}
		}
		// Index is not a positive SmallInteger
		return primitiveFailure(_PrimitiveFailureCode::OutOfBounds);
	}
	// Index not a smallinteger
	return primitiveFailure(_PrimitiveFailureCode::InvalidParameter1);
}

Oop* PRIMCALL Interpreter::primitiveInstVarAt(Oop* const sp, primargcount_t)
{
	Oop* const newSp = sp - 1;
	Oop oopIndex = *sp;
	OTE* oteReceiver = reinterpret_cast<OTE*>(*newSp);

	if (ObjectMemoryIsIntegerObject(oopIndex))
	{
		SmallInteger index = ObjectMemoryIntegerValueOf(oopIndex) - 1;
		if (oteReceiver->m_flags.m_pointer)
		{
			size_t size = oteReceiver->pointersSize();
			VariantObject* pointerObj = reinterpret_cast<PointersOTE*>(oteReceiver)->m_location;

			if (static_cast<size_t>(index) < size)
			{
				Oop field = pointerObj->m_fields[index];
				*newSp = field;
				return newSp;
			}
			// Out of bounds
			return primitiveFailure(_PrimitiveFailureCode::OutOfBounds);
		}
		else
		{
			switch (ObjectMemory::GetBytesElementSize(reinterpret_cast<BytesOTE*>(oteReceiver)))
			{
			case ByteElementSize::Bytes:
				if (static_cast<size_t>(index) < oteReceiver->bytesSize())
				{
					uint8_t value = reinterpret_cast<BytesOTE*>(oteReceiver)->m_location->m_fields[index];
					*newSp = ObjectMemoryIntegerObjectOf(value);
					return newSp;
				}
				break;

			case ByteElementSize::Words:
				if (static_cast<size_t>(index) < (oteReceiver->bytesSize() / 2))
				{
					uint16_t value = reinterpret_cast<WordsOTE*>(oteReceiver)->m_location->m_fields[index];
					*newSp = ObjectMemoryIntegerObjectOf(value);
					return newSp;
				}
				break;

			case ByteElementSize::Quads:
				if (static_cast<size_t>(index) < (oteReceiver->bytesSize() / 4))
				{
					uint32_t value = reinterpret_cast<QuadsOTE*>(oteReceiver)->m_location->m_fields[index];
					StoreUnsigned32()(newSp, value);
					return newSp;
				}
				break;

			default:
				__assume(false);
				return primitiveFailure(_PrimitiveFailureCode::AssertionFailure);
			}

			// Out of bounds
			return primitiveFailure(_PrimitiveFailureCode::OutOfBounds);
		}
	}
	// Index not a smallinteger
	return primitiveFailure(_PrimitiveFailureCode::InvalidParameter1);
}

Oop* PRIMCALL Interpreter::primitiveInstVarAtPut(Oop* const sp, primargcount_t)
{
	Oop* const newSp = sp - 2;
	OTE* oteReceiver = reinterpret_cast<OTE*>(*newSp);
	Oop oopIndex = *(sp - 1);

	if (ObjectMemoryIsIntegerObject(oopIndex))
	{
		SmallInteger index = ObjectMemoryIntegerValueOf(oopIndex) - 1;
		if (index >= 0)
		{
			if (oteReceiver->m_flags.m_pointer)
			{
				// Store into pointer object

				ptrdiff_t size = oteReceiver->pointersSizeForUpdate();
				VariantObject* pointerObj = reinterpret_cast<PointersOTE*>(oteReceiver)->m_location;

				if (index < size)
				{
					Oop newValue = *sp;
					ObjectMemory::countUp(newValue);
					Oop oldValue = pointerObj->m_fields[index];
					pointerObj->m_fields[index] = newValue;
					ObjectMemory::countDown(oldValue);
					*newSp = newValue;
					return newSp;
				}
				else
				{
					// Out of bounds or immutable
					return primitiveFailure(size < 0 ? _PrimitiveFailureCode::AccessViolation : _PrimitiveFailureCode::OutOfBounds);
				}
			}
			else
			{
				// Store into byte object

				Oop oopValue = *sp;
				if (ObjectMemoryIsIntegerObject(oopValue))
				{
					const SmallUinteger newValue = ObjectMemoryIntegerValueOf(oopValue);
					const ptrdiff_t size = oteReceiver->bytesSizeForUpdate();

					switch (ObjectMemory::GetBytesElementSize(reinterpret_cast<BytesOTE*>(oteReceiver)))
					{
					case ByteElementSize::Bytes:
						if (newValue <= UINT8_MAX)
						{
							if (index < size)
							{
								reinterpret_cast<BytesOTE*>(oteReceiver)->m_location->m_fields[index] = static_cast<uint8_t>(newValue);
								*newSp = oopValue;
								return newSp;
							}
							else
							{
								// Out of bounds or immutable
								return primitiveFailure(size < 0 ? _PrimitiveFailureCode::AccessViolation : _PrimitiveFailureCode::OutOfBounds);
							}
						}
						return primitiveFailure(_PrimitiveFailureCode::IntegerOutOfRange);

					case ByteElementSize::Words:
						if (newValue <= UINT16_MAX)
						{
							if (index < (size / 2))
							{
								reinterpret_cast<WordsOTE*>(oteReceiver)->m_location->m_fields[index] = static_cast<uint16_t>(newValue);
								*newSp = oopValue;
								return newSp;
							}
							else
							{
								// Out of bounds or immutable
								return primitiveFailure(size < 0 ? _PrimitiveFailureCode::AccessViolation : _PrimitiveFailureCode::OutOfBounds);
							}
						}
						return primitiveFailure(_PrimitiveFailureCode::IntegerOutOfRange);

					case ByteElementSize::Quads:
						if (index < (size / 4))
						{
							reinterpret_cast<QuadsOTE*>(oteReceiver)->m_location->m_fields[index] = static_cast<uint32_t>(newValue);
							*newSp = oopValue;
							return newSp;
						}
						else
						{
							// Out of bounds or immutable
							return primitiveFailure(size < 0 ? _PrimitiveFailureCode::AccessViolation : _PrimitiveFailureCode::OutOfBounds);
						}

					default:
						__assume(false);
						return primitiveFailure(_PrimitiveFailureCode::AssertionFailure);
					}
				}
				// Not a SmallInteger
				return primitiveFailure(_PrimitiveFailureCode::InvalidParameter2);
			}
		}
		// Negative index
		return primitiveFailure(_PrimitiveFailureCode::OutOfBounds);
	}

	// Index not a smallinteger
	return primitiveFailure(_PrimitiveFailureCode::InvalidParameter1);
}

Oop* PRIMCALL Interpreter::primitiveGetImmutable(Oop* const sp, primargcount_t)
{
	Oop receiver = *sp;
	*sp = reinterpret_cast<Oop>(ObjectMemoryIsIntegerObject(receiver) || reinterpret_cast<OTE*>(receiver)->isImmutable() ? Pointers.True : Pointers.False);
	return sp;
}

Oop* PRIMCALL Interpreter::primitiveSetImmutable(Oop* const sp, primargcount_t)
{
	if (*sp == reinterpret_cast<Oop>(Pointers.True))
	{
		Oop receiver = *(sp - 1);

		if (!ObjectMemoryIsIntegerObject(receiver))
		{
			OTE* ote = reinterpret_cast<OTE*>(receiver);
			*(sp - 1) = reinterpret_cast<Oop>(ote->isImmutable() ? Pointers.True : Pointers.False);
			ote->beImmutable();
		}
		else
		{
			*(sp - 1) = reinterpret_cast<Oop>(Pointers.True);
		}
		return sp - 1;
	}
	else
	{
		Oop receiver = *(sp - 1);

		// Marking object as mutable - cannot do this for SmallIntegers as these are always immutable
		if (!ObjectMemoryIsIntegerObject(receiver))
		{
			OTE* ote = reinterpret_cast<OTE*>(receiver);
			*(sp - 1) = reinterpret_cast<Oop>(ote->isImmutable() ? Pointers.True : Pointers.False);
			ote->beMutable();
			return sp - 1;
		}
		else
			return primitiveFailure(_PrimitiveFailureCode::ObjectTypeMismatch);
	}
}

Oop* PRIMCALL Interpreter::primitiveDeQForFinalize(Oop* const sp, primargcount_t)
{
	// Dequeue an entry from the finalization queue, and answer it.Answers nil if the queue is empty
	OTE* ote = dequeueForFinalization();
	*sp = reinterpret_cast<Oop>(ote);
	ote->countDown();
	return sp;
}

Oop* PRIMCALL Interpreter::primitiveBecome(Oop* const sp, primargcount_t)
{
	Oop	arg = *sp;
	if (!ObjectMemoryIsIntegerObject(arg))
	{
		OTE* oteArg = reinterpret_cast<OTE*>(arg);
		if (!ObjectMemory::isPermanent(oteArg))
		{
			Oop receiver = *(sp - 1);
			if (!ObjectMemoryIsIntegerObject(receiver))
			{
				OTE* oteReceiver = reinterpret_cast<OTE*>(receiver);
				if (!ObjectMemory::isPermanent(oteReceiver))
				{
					// THIS MUST BE CHANGED IF OTE LAYOUT CHANGED.
					// Note that we swap the location pointer(obviously), the class pointer(as we
					// aren't swapping the class), and flags. All belong with the object.
					// We don't swap the identity hash or count, as these belong with the pointer (identity)

					// Exchange body pointers
					std::swap(oteReceiver->m_location, oteArg->m_location);
					// Exchange class pointers
					std::swap(oteReceiver->m_oteClass, oteArg->m_oteClass);
					// Exchange object sizes(I think it is right to swap immutability bit over too ? )
					std::swap(oteReceiver->m_size, oteArg->m_size);
					// Exchange first 8 bits of flags(exclude identityHash and ref.count)
					std::swap(oteReceiver->m_ubFlags, oteArg->m_ubFlags);

					return sp - 1;
				}
			}
			// Invalid receiver
			return primitiveFailure(_PrimitiveFailureCode::ObjectTypeMismatch);
		}
	}

	// Invalid arg
	return primitiveFailure(_PrimitiveFailureCode::InvalidParameter1);
}


text:
import expect from 'expect'
import createReducer from '../../src/reducers/index'
import createServerReducer from '../../src/reducers/server'

describe('reducers', () => {
  describe('async', () => {
    it('should add the passed reducer to the list', () => {
      const asyncReducers = {
        test: () => ({})
      }

      const reducer = createReducer(asyncReducers)
      expect(reducer(undefined, {
        type: 'TEST'
      }).ladb).toIncludeKey('test')
    })

    it('should create the server reducer', () => {
      const reducer = createServerReducer()
      const state = reducer(undefined, {
        type: 'TEST'
      })

      expect(state.ladb).toIncludeKey('ageGroup')
      expect(state.ladb).toIncludeKey('toplist')
      expect(state.ladb).toIncludeKey('competitionList')
      expect(state.ladb).toIncludeKey('competitionDetails')
      expect(state.ladb).toIncludeKey('comparison')
    })
  })
})

redpajama_set_name: RedPajamaGithub


text:
package org.apache.camel.component.file.stress;

import java.util.Random;

import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.junit.Ignore;

@Ignore("Manual test")
public class FileAsyncStressReadLockNoneTest extends FileAsyncStressTest {

    @Override
    protected RouteBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                // leverage the fact that we can limit to max 50 files per poll
                // this will result in polling again and potentially picking up files
                // that already are in progress
                from("file:target/data/filestress?maxMessagesPerPoll=50&readLock=none").routeId("foo").noAutoStartup()
                    .threads(10)
                    .process(new Processor() {
                        public void process(Exchange exchange) throws Exception {
                            // simulate some work with random time to complete
                            Random ran = new Random();
                            int delay = ran.nextInt(250) + 10;
                            Thread.sleep(delay);
                        }
                    }).to("mock:result");
            }
        };
    }

}


text:
<?php
include ('header.php');
if (!file_exists('include/recaptcha_keys.php')) {
    die("No reCAPTCHA keys found");
}
require ('include/recaptcha_keys.php'); // Keep our private key (+ pubkey but that's not dangerous) in an uncommitted file
?>

Request an Interview

<?php

// Modified by Nick Mooney, Jan 13 2014
// Original credit to http://chrisplaneta.com/freebies/php_contact_form_script_with_recaptcha/

//If the form is submitted:
if(isset($_POST['submitted'])) {

//load recaptcha file
require_once('include/recaptchalib.php');

	//check recaptcha fields
	$resp = recaptcha_check_answer ($privatekey,
								$_SERVER["REMOTE_ADDR"],
								$_POST["recaptcha_challenge_field"],
								$_POST["recaptcha_response_field"]);

	//Check to see if the invisible field has been filled in
	if(trim($_POST['checking']) !== '') {
		$blindError = true;
	} else {

		//Check to make sure that a contact name has been entered
		$authorName = (filter_var($_POST['formAuthor'], FILTER_SANITIZE_STRING));
		if ($authorName == ""){
			$authorError = true;
			$hasError = true;
		}else{
			$formAuthor = $authorName;
		};

		//Check to make sure sure that a valid email address is submitted
		$authorEmail = (filter_var($_POST['formEmail'], FILTER_SANITIZE_EMAIL));
		if (!(filter_var($authorEmail, FILTER_VALIDATE_EMAIL))){
			$emailError = true;
			$hasError = true;
		} else{
			$formEmail = $authorEmail;
		};

		//Check to make sure the subject of the message has been entered
		$msgSubject = (filter_var($_POST['formSubject'], FILTER_SANITIZE_STRING));
		if ($msgSubject == ""){
			$subjectError = true;
			$hasError = true;
		}else{
			$formSubject = $msgSubject;
		};

		//Check to make sure content has been entered
		$msgContent = (filter_var($_POST['formContent'], FILTER_SANITIZE_STRING));
		if ($msgContent == ""){
			$commentError = true;
			$hasError = true;
		}else{
			$formContent = $msgContent;
		};

		// if all the fields have been entered correctly and there are no recaptcha errors build an email message
		if (($resp->is_valid) && (!isset($hasError))) {
			$emailTo = 'sunnyking9999@gmail.com'; // here you must enter the email address you want the email sent to
			$subject = 'Peercoin interview request from: ' . $formAuthor . ' | ' . $formSubject; // This is how the subject of the email will look like
			$body = "Email: $formEmail \n\nContent: $formContent  \n\n$formAuthor"; // This is the body of the email
			$headers = 'From: <'.$formEmail.'>' . "\r\n" . 'Reply-To: ' . $formEmail . "\r\n" . 'CC: john.manglaviti@gmail.com' . "\r\n" . 'Return-Path: ' . $formEmail; // Email headers

			//send email
			mail($emailTo, $subject, $body, $headers);

			// set a variable that confirms that an email has been sent
			$emailSent = true;
		}

		// if there are errors in captcha fields set an error variable
		if (!($resp->is_valid)){
			$captchaErrorMsg = true;
		}
	}
} ?>

<?php // if the page the variable "email sent" is set to true show confirmation instead of the form
if(isset($emailSent) && $emailSent == true) { ?>

		Your interview request was sent successfully.

<?php } else
// if there are errors in the form show a message
if(isset($hasError) || isset($blindError)) { ?>

There was an error submitting the form. Please check all the marked fields.

	<?php }
	// if there are recaptcha errors show a message
	if ($captchaErrorMsg){ ?>

Captcha error. Please, type the check-words again.

	<?php }
	// here, you set what the recaptcha module should look like
	// possible options: red, white, blackglass and clean
	// more infor on customisation can be found here: http://code.google.com/intl/pl-PL/apis/recaptcha/docs/customization.html
	?>

	<?php
	// this is where the form starts
	// action attribute should contain url of the page with this form
	// more on that you can read here: http://www.w3schools.com/TAGS/att_form_action.asp
	?>

					<form id="contactForm" action="" method="post">

									Name

								<input class="requiredField <?php if($authorError) { echo 'formError'; } ?>" type="text" name="formAuthor" id="formAuthor" value="<?php if(isset($_POST['formAuthor'])) echo htmlspecialchars($_POST['formAuthor']);?>" size="40" />

									Email

								<input class="requiredField <?php if($emailError) { echo 'formError'; } ?>" type="text" name="formEmail" id="formEmail" value="<?php if(isset($_POST['formEmail'])) echo htmlspecialchars($_POST['formEmail']);?>" size="40" />

									Subject

								<input class="requiredField <?php if($subjectError) { echo 'formError'; } ?>" type="text" name="formSubject" id="formSubject" value="<?php if(isset($_POST['formSubject'])) echo htmlspecialchars($_POST['formSubject']);?>" size="40" />

								Message

							<textarea class="requiredField <?php if($commentError) { echo 'formError'; } ?>" id="formContent" name="formContent" cols="40" rows="5"><?php if(isset($_POST['formContent'])) { echo htmlspecialchars(stripslashes($_POST['formContent'])); } ?></textarea>
							<?php
							// this field is visible only to robots and screenreaders
							// if it is filled in it means that a human hasn't submitted this form thus it will be rejected
							?>

									If you want to submit this form, do not enter anything in this field

								<input type="text" name="checking" id="checking" value="<?php if(isset($_POST['checking']))  echo htmlspecialchars($_POST['checking']);?>" />

						<?php
							// load recaptcha file
							require_once('include/recaptchalib.php');
							// display recaptcha test fields
							echo recaptcha_get_html($publickey);
						?>
						<input type="hidden" name="submitted" id="submitted" value="true" />
						<?php // submit button ?>
						<input type="submit" value="Send Message" tabindex="5" id="submit" name="submit">
					</form>
					<?php } ?>
					</script>

<?php include ('footer.php'); ?>


text:
package net.wigle.wigleandroid;

import android.annotation.SuppressLint;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ListView;

import net.wigle.wigleandroid.background.ApiDownloader;
import net.wigle.wigleandroid.background.ApiListener;
import net.wigle.wigleandroid.background.DownloadHandler;
import net.wigle.wigleandroid.model.NewsItem;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Locale;

public class NewsFragment extends Fragment {
    private static final int MSG_NEWS_DONE = 100;

    // {"success": true,"results": [
    // {"link":"http://wigle.net/phpbb/viewtopic.php?p=8783",
    // "subject":"250 Million Wifi Networks",
    // "postDate":"Sat Apr 30 15:31:41 2016",
    // "story":"Major congrats to user 'redlukas' can say "quarter billion"",
    // "storyId":"8783",
    // "more":false,
    // "userName":"bobzilla"}
    private static final String RESULT_LIST_KEY = "results";

    private static final String KEY_SUBJECT = "subject";
    private static final String KEY_POST = "story";
    private static final String KEY_DATE_TIME = "postDate";
    private static final String KEY_POSTER = "userName";
    private static final String KEY_LINK = "link";

    private static final String[] ALL_ROW_KEYS = new String[] {
            KEY_SUBJECT, KEY_POST, KEY_DATE_TIME, KEY_POSTER, KEY_LINK,
        };

    private NumberFormat numberFormat;
    private NewsListAdapter listAdapter;

    /** Called when the activity is first created. */
    @Override
    public void onCreate( final Bundle savedInstanceState ) {
        MainActivity.info("NEWS: onCreate");
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
        // set language
        MainActivity.setLocale(getActivity());

        // media volume
        getActivity().setVolumeControlStream(AudioManager.STREAM_MUSIC);

        numberFormat = NumberFormat.getNumberInstance(Locale.US);
        if (numberFormat instanceof DecimalFormat) {
            numberFormat.setMinimumFractionDigits(0);
            numberFormat.setMaximumFractionDigits(2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        final int orientation = getResources().getConfiguration().orientation;
        MainActivity.info("NEWS: onCreateView. orientation: " + orientation);
        final LinearLayout rootView = (LinearLayout) inflater.inflate(R.layout.news, container, false);
        setupListView(rootView);

        final NewsDownloadHandler handler = new NewsDownloadHandler(rootView, numberFormat,
                getActivity().getPackageName(), getResources());
        handler.setNewsListAdapter(listAdapter);
        final ApiDownloader task = new ApiDownloader(getActivity(), ListFragment.lameStatic.dbHelper,
                "news-cache.json", MainActivity.NEWS_URL, false, false, false,
                ApiDownloader.REQUEST_GET,
                new ApiListener() {
                    @Override
                    public void requestComplete(final JSONObject json, final boolean isCache) {
                        handleNews(json, handler);
                    }
                });
        try {
            task.startDownload(this);
        } catch (WiGLEAuthException waex) {
            //unauthenticated call - should never trip
            MainActivity.warn("Authentication error on news load (should not happen)", waex);
        }

        return rootView;
    }

    private void setupListView(final View view) {
        if (listAdapter == null) {
            listAdapter = new NewsListAdapter(getActivity(), R.layout.uploadrow);
        }
        // always set our current list adapter
        final ListView listView = (ListView) view.findViewById(R.id.news_list_view);
        listView.setAdapter(listAdapter);

    }

    private final static class NewsDownloadHandler extends DownloadHandler {
        private NewsListAdapter newsListAdapter;

        private NewsDownloadHandler(final View view, final NumberFormat numberFormat, final String packageName,
                                    final Resources resources) {
            super(view, numberFormat, packageName, resources);
        }

        public void setNewsListAdapter(final NewsListAdapter newsListAdapter) {
            this.newsListAdapter = newsListAdapter;
        }

        @SuppressLint("SetTextI18n")
        @Override
        public void handleMessage(final Message msg) {
            final Bundle bundle = msg.getData();

            final ArrayList<Parcelable> results = bundle.getParcelableArrayList(RESULT_LIST_KEY);
            // MainActivity.info("handleMessage. results: " + results);
            if (msg.what == MSG_NEWS_DONE && results != null && newsListAdapter != null) {
                newsListAdapter.clear();
                for (final Parcelable result : results) {
                    if (result instanceof Bundle) {
                        final Bundle row = (Bundle) result;
                        final NewsItem upload = new NewsItem(row.getString(KEY_SUBJECT), row.getString(KEY_POST),
                                row.getString(KEY_POSTER), row.getString(KEY_DATE_TIME), row.getString(KEY_LINK));
                        newsListAdapter.add(upload);
                    }
                }
            }
        }
    }

    private void handleNews(final JSONObject json, final Handler handler) {
        MainActivity.info("handleNews");

        if (json == null) {
            MainActivity.info("handleNews null json, returning");
            return;
        }

        final Bundle bundle = new Bundle();
        try {
            final JSONArray list = json.getJSONArray(RESULT_LIST_KEY);
            final ArrayList<Parcelable> resultList = new ArrayList<>(list.length());
            for (int i = 0; i < list.length(); i++) {
                final JSONObject row = list.getJSONObject(i);
                final Bundle rowBundle = new Bundle();
                for (final String key : ALL_ROW_KEYS) {
                    String value = row.getString(key);
                    if (KEY_POST.equals(key)) {
                        value = value.replace("\\n", "\n");
                        value = value.replace(""", "\"");
                        value = value.replace("&", "&");
                        value = value.replaceAll("<.*?>", "");
                    }
                    rowBundle.putString(key, value);
                }
                resultList.add(rowBundle);
            }
            bundle.putParcelableArrayList(RESULT_LIST_KEY, resultList);
        } catch (final JSONException ex) {
            MainActivity.error("json error: " + ex, ex);
        } catch (final Exception e) {
            MainActivity.error("news error: " + e, e);
        }

        final Message message = new Message();
        message.setData(bundle);
        message.what = MSG_NEWS_DONE;
        handler.sendMessage(message);
    }

    @Override
    public void onDestroy() {
        MainActivity.info( "NEWS: onDestroy" );
        super.onDestroy();
    }

    @Override
    public void onResume() {
        MainActivity.info("NEWS: onResume");
        super.onResume();
        getActivity().setTitle(R.string.news_app_name);
    }

    @Override
    public void onStart() {
        MainActivity.info( "NEWS: onStart" );
        super.onStart();
    }

    @Override
    public void onPause() {
        MainActivity.info( "NEWS: onPause" );
        super.onPause();
    }

    @Override
    public void onStop() {
        MainActivity.info( "NEWS: onStop" );
        super.onStop();
    }

    @Override
    public void onConfigurationChanged( final Configuration newConfig ) {
        MainActivity.info("NEWS: config changed");
        super.onConfigurationChanged( newConfig );
    }

    /* Creates the menu items */
    @Override
    public void onCreateOptionsMenu (final Menu menu, final MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
    }

    /* Handles item selections */
    @Override
    public boolean onOptionsItemSelected( final MenuItem item ) {
        return false;
    }

}


text:
import {CONST, Type, isPresent} from 'angular2/src/facade/lang';
import {RouteDefinition} from './route_definition';
export {RouteDefinition} from './route_definition';

/**
 * The `RouteConfig` decorator defines routes for a given component.
 *
 * It takes an array of {@link RouteDefinition}s.
 */
@CONST()
export class RouteConfig {
  constructor(public configs: RouteDefinition[]) {}
}

/**
 * `Route` is a type of {@link RouteDefinition} used to route a path to a component.
 *
 * It has the following properties:
 * - `path` is a string that uses the route matcher DSL.
 * - `component` a component type.
 * - `name` is an optional `CamelCase` string representing the name of the route.
 * - `data` is an optional property of any type representing arbitrary route metadata for the given
 * route. It is injectable via {@link RouteData}.
 *
 * ### Example
 * ```
 * import {RouteConfig} from 'angular2/router';
 *
 * @RouteConfig([
 *   {path: '/home', component: HomeCmp, name: 'HomeCmp' }
 * ])
 * class MyApp {}
 * ```
 */
@CONST()
export class Route implements RouteDefinition {
  data: {[key: string]: any};
  path: string;
  component: Type;
  name: string;
  // added next three properties to work around https://github.com/Microsoft/TypeScript/issues/4107
  aux: string = null;
  loader: Function = null;
  redirectTo: string = null;
  constructor({path, component, name,
               data}: {path: string, component: Type, name?: string, data?: {[key: string]: any}}) {
    this.path = path;
    this.component = component;
    this.name = name;
    this.data = data;
  }
}

/**
 * `AuxRoute` is a type of {@link RouteDefinition} used to define an auxiliary route.
 *
 * It takes an object with the following properties:
 * - `path` is a string that uses the route matcher DSL.
 * - `component` a component type.
 * - `name` is an optional `CamelCase` string representing the name of the route.
 * - `data` is an optional property of any type representing arbitrary route metadata for the given
 * route. It is injectable via {@link RouteData}.
 *
 * ### Example
 * ```
 * import {RouteConfig, AuxRoute} from 'angular2/router';
 *
 * @RouteConfig([
 *   new AuxRoute({path: '/home', component: HomeCmp})
 * ])
 * class MyApp {}
 * ```
 */
@CONST()
export class AuxRoute implements RouteDefinition {
  data: {[key: string]: any} = null;
  path: string;
  component: Type;
  name: string;
  // added next three properties to work around https://github.com/Microsoft/TypeScript/issues/4107
  aux: string = null;
  loader: Function = null;
  redirectTo: string = null;
  constructor({path, component, name}: {path: string, component: Type, name?: string}) {
    this.path = path;
    this.component = component;
    this.name = name;
  }
}

/**
 * `AsyncRoute` is a type of {@link RouteDefinition} used to route a path to an asynchronously
 * loaded component.
 *
 * It has the following properties:
 * - `path` is a string that uses the route matcher DSL.
 * - `loader` is a function that returns a promise that resolves to a component.
 * - `name` is an optional `CamelCase` string representing the name of the route.
 * - `data` is an optional property of any type representing arbitrary route metadata for the given
 * route. It is injectable via {@link RouteData}.
 *
 * ### Example
 * ```
 * import {RouteConfig} from 'angular2/router';
 *
 * @RouteConfig([
 *   {path: '/home', loader: () => Promise.resolve(MyLoadedCmp), name: 'MyLoadedCmp'}
 * ])
 * class MyApp {}
 * ```
 */
@CONST()
export class AsyncRoute implements RouteDefinition {
  data: {[key: string]: any};
  path: string;
  loader: Function;
  name: string;
  aux: string = null;
  constructor({path, loader, name, data}:
                  {path: string, loader: Function, name?: string, data?: {[key: string]: any}}) {
    this.path = path;
    this.loader = loader;
    this.name = name;
    this.data = data;
  }
}

/**
 * `Redirect` is a type of {@link RouteDefinition} used to route a path to an asynchronously loaded
 * component.
 *
 * It has the following properties:
 * - `path` is a string that uses the route matcher DSL.
 * - `redirectTo` is a string representing the new URL to be matched against.
 *
 * ### Example
 * ```
 * import {RouteConfig} from 'angular2/router';
 *
 * @RouteConfig([
 *   {path: '/', redirectTo: '/home'},
 *   {path: '/home', component: HomeCmp}
 * ])
 * class MyApp {}
 * ```
 */
@CONST()
export class Redirect implements RouteDefinition {
  path: string;
  redirectTo: string;
  name: string = null;
  // added next three properties to work around https://github.com/Microsoft/TypeScript/issues/4107
  loader: Function = null;
  data: any = null;
  aux: string = null;
  constructor({path, redirectTo}: {path: string, redirectTo: string}) {
    this.path = path;
    this.redirectTo = redirectTo;
  }
}


text:
import re

from datetime import datetime, timedelta, date
import calendar

def get_sunday(offset_mins):
  now    = datetime.utcnow() - timedelta(minutes=offset_mins)
  sunday = datetime(*now.timetuple()[0:3])
  while sunday.weekday() != calendar.SUNDAY:
    sunday -= timedelta(days=1)
  return sunday

def get_this_week_range(offset_mins=0):
  sunday = get_sunday(offset_mins)
  return (sunday + timedelta(minutes=offset_mins), sunday + timedelta(days=7, minutes=offset_mins))

def get_last_week_range(offset_mins=0):
  sunday = get_sunday(offset_mins)
  return (sunday - timedelta(days=7) + timedelta(minutes=offset_mins), sunday + timedelta(minutes=offset_mins))

def get_today_range(offset_mins=0):
  now   = datetime.utcnow() - timedelta(minutes=offset_mins)
  today = datetime(*now.timetuple()[0:3])
  return (today + timedelta(minutes=offset_mins), today + timedelta(hours=24, minutes=offset_mins))

def get_yesterday_range(offset_mins=0):
  now   = datetime.utcnow() - timedelta(minutes=offset_mins)
  today = datetime(*now.timetuple()[0:3])
  return (today - timedelta(hours=24) + timedelta(minutes=offset_mins), today + timedelta(minutes=offset_mins))

HUMAN_RANGES = (
  {
    'name':  'This week',
    'slug':  'this-week',
    'range': get_this_week_range
  },
  {
    'name':  'Last week',
    'slug':  'last-week',
    'range': get_last_week_range
  },
  {
    'name':  'Today',
    'slug':  'today',
    'range': get_today_range
  },
  {
    'name':  'Yesterday',
    'slug':  'yesterday',
    'range': get_yesterday_range
  },
)

RE_TODAY    = re.compile(r'^today$', re.I)
RE_TOMORROW = re.compile(r'^tom{1,2}or{1,2}ow$', re.I)
RE_DAY      = re.compile(r'^(mon|tue|wed|thu|fri|sat|sun)\w*$', re.I)
RE_SPLIT    = re.compile(r'[^a-z0-9]+', re.I)

def parse_month(month_string):
  for i in range(1,13):
    if date(2008, i, 1).strftime('%B')[0:3].lower() in month_string.lower():
      return i

  return None

def parse_datetime(date_string):
  """Turns a string like 2009-06-24 04:30:24.906035 into a datetime."""
  if not date_string or not isinstance(date_string, (str,unicode)):
    return None

  digits = [int(p) for p in re.findall(r'\d+', date_string)]
  try:
    date = datetime(*digits[:7])
    return date
  except:
    pass

  return None

def parse_date(date_string, offset_mins=0, output_utc=False):
  if not date_string:
    return None

  date_string = date_string.strip()
  if len(date_string) == 0:
    return None

  now   = datetime.utcnow() - timedelta(minutes=offset_mins)
  today = datetime(*now.timetuple()[0:3])

  value = None

  if RE_TODAY.match(date_string):
    value = today

  elif RE_TOMORROW.match(date_string):
    value = today + timedelta(days=1)

  elif RE_DAY.match(date_string):
    day = RE_DAY.match(date_string).groups()[0].lower()
    next_day = today + timedelta(days=1)
    while next_day.strftime("%a").lower() != day:
      next_day += timedelta(days=1)
    value = next_day

  else:
    parts = RE_SPLIT.split(date_string)
    digits = [int(p)    for p in parts if re.match(r'^\d+$', p)]
    words =  [p.lower() for p in parts if re.match(r'^[a-z]+$', p.lower())]
    parts = digits + words

    if (len(parts) == 2 or len(parts) == 3) and len(words) <= 1:
      m, d, y = None, None, None

      if words:
        m = parse_month(words.pop())

      while digits:
        max_d = max(digits)
        if max_d > 31 and not y:
          y = max_d
          digits.remove(y)
          continue
        elif max_d > 12 and not d:
          d = max_d
          digits.remove(d)
          continue

        break

      digits.reverse()

      if digits and not m:
        m = digits.pop()
      if digits and not d:
        d = digits.pop()
      if digits and not y:
        y = digits.pop()

      try:
        if y:
          if y < 100 and y > 50:
            y += 1900
          elif y <= 50:
            y += 2000
          elif y < 1950:
            y = None

        else:
          y = now.timetuple()[0]
          if datetime(y, m, d) < today:
            y += 1

        value = datetime(y, m, d)

      except:
        pass

  if value and output_utc:
    value += timedelta(minutes=offset_mins)

  return value


text:
pdf417_ex6.php
<link rel="stylesheet" href="../phphl.css" type="text/css">

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35

<?php // content="text/plain; charset=utf-8"
require_once('jpgraph/pdf417/jpgraph_pdf417.php');

$data1 = '12345';
$data2 = 'Abcdef';
$data3 = '6789';

// Manually specify several encodation schema
$data = array(
    array(USE_NC,$data1),
    array(USE_TC,$data2),
    array(USE_NC,$data3));

//$data = "12345Abcdef6789";

// Setup some symbolic names for barcode specification

$columns = 8;   // Use 8 data (payload) columns
$modwidth = 2;  // Use 2 pixel module width
$errlevel = 2;  // Use error level 2
$showtext = true;  // Show human readable string

try {
    // Create a new encoder and backend to generate PNG images
    $encoder = new PDF417Barcode($columns,$errlevel);
    $backend = PDF417BackendFactory::Create(BACKEND_IMAGE,$encoder);

    $backend->SetModuleWidth($modwidth);
    $backend->NoText(!$showtext);
    $backend->Stroke($data);
}
catch(JpGraphException $e) {
    echo 'PDF417 Error: '.$e->GetMessage();
}
?>


text:
layout: post
title:  "Download Latest Jekyll"
description: "Download Latest Jekyll"
date:   2013-08-30 12:17:47
categories: ruby
tags: [jekyll]
---

Jekyll is a simple, blog aware, static site generator. It takes a template directory (representing the raw form of a website),
runs it through Textile or Markdown and Liquid converters, and spits out a complete, static website suitable for serving with Apache or your favorite web server.
This is also the engine behind
[GitHub Pages](http://pages.github.com) which you can use to host your project's page or blog right here from GitHub.

## Getting Started

* [Install](http://jekyllrb.com/docs/installation/ "Installing jekyll") the gem
* Read up about its [Usage](http://jekyllrb.com/docs/usage/ "Usage") and [Configuration](http://jekyllrb.com/docs/configuration/ "Configuration")
* Take a gander at some existing [Sites](http://wiki.github.com/mojombo/jekyll/sites "Sites")
* Fork and [Contribute](https://github.com/mojombo/jekyll/blob/master/CONTRIBUTING.md "Contribute") your own modifications
* Have questions? Post them on the [Mailing List](http://groups.google.com/group/jekyll-rb "Mailing List")

## Diving In

* [Migrate](http://jekyllrb.com/docs/migrations/ "Migrate") from your previous system
* Learn how the [YAML Front Matter](http://jekyllrb.com/docs/frontmatter/ "YAML Front Matter") works
* Put information on your site with [Variables](http://jekyllrb.com/docs/variables/ "Variables")
* Customize the [Permalinks](http://jekyllrb.com/docs/permalinks/ "Permalinks") your posts are generated with
* Use the built-in [Liquid Extensions](http://jekyllrb.com/docs/templates/ "Liquid Extensions") to make your life easier
* Use custom [Plugins](http://jekyllrb.com/docs/plugins/ "Plugins") to generate content specific to your site

## Runtime Dependencies

* Classifier: Generating related posts (Ruby)
* Directory Watcher: Auto-regeneration of sites (Ruby)
* Kramdown: Markdown-superset converter (Ruby)
* Liquid: Templating system (Ruby)
* Maruku: Default markdown engine (Ruby)

## Developer Dependencies

* RDiscount: Discount Markdown Processor (Ruby)
* RedCloth: Textile support (Ruby)
* RedGreen: Nicer test output (Ruby)
* RR: Mocking (Ruby)
* Shoulda: Test framework (Ruby)

## License

See [LICENSE](https://github.com/mojombo/jekyll/blob/master/LICENSE "LICENSE")


text:
> GitHub flavored syntax theme for Atom.

![GitHub Theme](http://miwurster.github.io/atom-github-theme/screenshot.png "GitHub Theme")


text:
import rabbitpy

url = 'amqp://guest:guest@localhost:5672/%2F'
connection = rabbitpy.Connection(url)
channel = connection.channel()
queue = rabbitpy.Queue(channel, 'example')

while len(queue) > 0:
    message = queue.get()
    print('Message:')
    print(' ID: %s' % message.properties['message_id'])
    print(' Time: %s' % message.properties['timestamp'].isoformat())
    print(' Body: %s' % message.body)
    message.ack()

    print('There are %i more messages in the queue' % len(queue))


text:
\subsection{Developers Using AdaptUI}
\label{sec:developers}

Before introducing the results obtained from working with final users (as
consumers of adapted user interfaces), an experiment with developers has been
performed. This experiment aims to evaluate the provided \acp{api}, and also to
compare the differences between performing a configuration of the user interface
in Android with and without AdaptUI. Thus, developers with experience in both
Android development and semantics are involved.

As AdaptUI provides an \ac{api} conceptually divided in two (see
Section~\ref{sec:application_layer}), this experiment has been fragmented
accordingly. The experiment, consisting in 6 steps and with a 20 minutes duration,
has been carried out as follows:

\begin{enumerate}
  \item First, the developer is introduced to the AdaptUI framework through a brief
  explanation of AdaptUI's goals, virtues and boundaries. Both \acp{api} are
  described and explained to them, and the \acp{api} descriptions are given in a
  printed version, as they appear in Table~\ref{tbl:api_adaptation} and
  Table~\ref{tbl:api_knowledge}.

  \item Secondly, a Java project built with the Eclipse \acs{ide} is presented.
  This project uses the AdaptUI framework as an imported library. The main class
  of this Java application instantiates AdaptUI and initializes the environment.
  Besides, several \textit{TODO} tasks with the corresponding instructions are
  given for the developer to complete. This class is summarized through
  Listing~\ref{lst:default_knowledge_experiment}. These tasks include:
  \begin{itemize}
    \item The creation of a new class.
    \item The creation of a new instance of the previously created class.
    \item Adding a new datatype property with the corresponding value to the
    new instance.
    \item Adding a new object property to the new instance, involving several
    classes\footnote{As the developer might not know how the AdaptUIOnt ontology
    is structured, a brief explanation is given using Protégé.}.
    \item The creation of a new rule, involving at least three classes (including
    the created class), and the previous mentioned datatype and object properties.
  \end{itemize}

  \newpage

  \inputminted[linenos=true, fontsize=\footnotesize, frame=lines]{java}{5_experiments_and_results/default_knowledge_experiment.java}
  \captionof{listing}{The default main class with the corresponding tasks to
  be accomplished by the developer.\label{lst:default_knowledge_experiment}}

  \item Once the corresponding knowledge modifications are made, the resulting
  ontology is stored. Developers are requested to check the changes in the ontology
  using Protégé. Figure~\ref{fig:protege} shows an example of a modified ontology
  by a participating developer. Hence, the developer is allowed to check if the
  changes made in the Java main class using the AdaptUI framework have been
  correctly represented in the ontology. If any errors are found, the process is
  revised.

  \begin{figure}
  \centering
  \includegraphics[width=0.85\textwidth]{protege.pdf}
  \caption{A test ontology modified by one of the participating developers.
  The modifications are highlighted in red. Several classes have been added.
  Also the \textit{viewBackgroundColor} for the \textit{Button} only instance
  has been modified.}
  \label{fig:protege}
  \end{figure}

  \item After the modification of the ontology, the AdaptUIDemo Android project
  is presented to the developer. This project's main activity shows a text view,
  an edit text and a button. The goal of this part of the experiment is to evaluate
  how the developer uses the adaptation \ac{api} to dynamically modify these views.
  The changes performed in the ontology in the previous steps are taken into account.
  In order to make this application to use the new modified version of the ontology,
  an \acs{adb} command is needed. This command pushes the required file from the
  current computer disk to the desired Android folder. Listing~\ref{lst:adb_push}
  shows how the command \acs{adb} push command works.

  \inputminted[linenos=true, fontsize=\footnotesize, frame=lines]{java}{5_experiments_and_results/adb_push.java}
  \captionof{listing}{The \ac{adb} push command. The first parameter specifies
  the location of the file to be sent to the device. The second parameter points
  at the absolute location in the device. \label{lst:adb_push}}

  \item Next, once the developer checks that the adaptation to the views shown
  in the demo application matches the modifications performed with the knowledge
  \ac{api}, the developer is asked to use the adaptation \ac{api} through an
  Android project. Similar to the first case, the developer is asked to complete
  several tasks (see Listing~\ref{lst:default_adaptation_experiment}).

  \inputminted[linenos=true, fontsize=\footnotesize, frame=lines]{java}{5_experiments_and_results/default_adaptation_experiment.java}
  \captionof{listing}{The default Android version with the corresponding tasks to
  be completed by the developer. These tasks include adapting the background and
  text colour of a button, its size and the background colour of the whole activity\label{lst:default_adaptation_experiment}}

  \item Finally, the developer uses the Capabilities Collector to adapt several
  views as a user. As the last task of the Capabilities Collector is to store the
  required values in the ontology through the Semantic Modeller, the developer
  is able to check these changes again in the AdaptUIDemo application.

\end{enumerate}

% The following sections aim to give more details about the experiments defined
% above.
%
% \subsubsection{Using the knowledge editor \ac{api}}
% \label{sec:knowledge_editor_api}
%
% The knowledge editor \ac{api} provides a set of methods to modify the knowledge
% stored in the ontology. Imported as a library from a Java project, this \ac{api}
% allows to add and remove classes, individuals, object and datatype properties,
% and rules. In this experiment developers are asked to modify the ontology by
% adding new concepts to be used by the adaptation \ac{api}.
% Listing~\ref{lst:adaptui_add_knowledge} shows an example of how developers can
% modify the knowledge stored in the ontology.
%
% \inputminted[linenos=true, fontsize=\footnotesize, frame=lines]{java}{5_experiments_and_results/adaptui_add_knowledge.java}
% \captionof{listing}{Modifying the knowledge represented in the ontology through the knowledge \ac{api}.\label{lst:adaptui_add_knowledge}}
%
% \subsubsection{Using adaptation \ac{api}}
% \label{sec:adaptation_api_experiment}
%
% As mentioned in Section~\ref{sec:adaptation_api}, the adaptation \ac{api} provides
% a set of methods whose purpose is to facilitate the adaptation process for
% developers. The purpose of this part of the experiment is to check developer's
% feedback when dealing with the AdaptUI framework by collecting their opinions.
% To do so, the experiment presents an Android application developed with the
% Eclipse\footnote{https://eclipse.org/} \ac{ide}. It includes a layout configuration
% \ac{xml} file with the corresponding declaration of several user interface views
% (see Listing~\ref{lst:default_layout}), and also an \textit{onCreate} main method,
% shown in Listing~\ref{lst:default_oncreate} (the default aspect of the application
% is illustrated through Figure~\ref{fig:default_layout}). The developers
% participating in this experiment are guided through a brief explanation of the
% available adaptation \ac{api} methods. Once they are aware of the possibilities
% the framework provides, they are asked to modify the aspect of the listed views.
%
% \inputminted[linenos=true, fontsize=\footnotesize, frame=lines]{xml}{5_experiments_and_results/default_layout.xml}
% \captionof{listing}{The default layout defining a grid layout, a text view,
% a button and an edit text.\label{lst:default_layout}}
%
% \inputminted[linenos=true, fontsize=\footnotesize, frame=lines]{java}{5_experiments_and_results/default_oncreate.java}
% \captionof{listing}{The default \textit{onCreate} method.\label{lst:default_oncreate}}
%
% \begin{figure}
% \centering
% \includegraphics[width=0.25\textwidth]{default_layout.png}
% \caption{The corresponding user interface considering the layout specified in
% Listing~\ref{lst:default_layout}.}
% \label{fig:default_layout}
% \end{figure}
%
% Obviously, in order to adapt the application, developers need a copy of the
% AdaptUIOnt ontology, in which the corresponding values for the adaptation are
% semantically represented. Hence, developers are asked to install the Capabilities
% Collector in their Android devices. Thus, they can add new knowledge to the ontology.
%
% Listing~\ref{lst:default_oncreate} shows the presented \textit{onCreate} method,
% which defines the views listed in Listing~\ref{lst:default_layout}. Using AdaptUI
% developers reach the \textit{onCreate} shown in Listing~\ref{lst:adaptui_oncreate},
% which includes the corresponding calls to the provided adaptation \ac{api}.
%
% \inputminted[linenos=true, fontsize=\footnotesize, frame=lines]{java}{5_experiments_and_results/adaptui_oncreate.java}
% \captionof{listing}{The AdaptUI \textit{onCreate} method.\label{lst:adaptui_oncreate}}
%
% Thus, the resulting adapted user interface is illustrated by Figure~\ref{fig:adapted_layout}.
% While Figure~\ref{fig:default_layout} shows a default disposition and configuration
% of the user interface items described in Listing~\ref{lst:default_layout}, in this
% case they have been adapted according to Listing~\ref{lst:adaptui_oncreate}.
%
% \begin{figure}
% \centering
% \includegraphics[width=0.25\textwidth]{adapted_layout.png}
% \caption{The corresponding user interface considering the layout specified in
% Listing~\ref{lst:adaptui_oncreate}.}
% \label{fig:adapted_layout}
% \end{figure}

\subsubsection{Results and Conclusions}
\label{sec:api_results}

The resulting experiences with the provided \acp{api} have been collected through
a simple questionnaire. It is a very straightforward questionnaire, not based on
any standard. Its purpose is to find out if the participating developers miss
any possible feature and to gather their feedback about AdaptUI. The
questionnaire is formed by the following questions:

\begin{enumerate}
 \item \#Q1: How useful do you find the AdaptUI framework for developing adaptive
 user interfaces?\footnote{This question requires the user to select a value from
 a 1 to 5 scale, 1 meaning \textit{not much} and 5 meaning \textit{very much}.}
 \item \#Q2: Do you miss any additional functionality?
 \item \#Q3: If so, please specify the functionality you would add to the
 framework/\ac{api}.
 \item \#Q4: Would you improve any \ac{api} feature?
 \item \#Q5: If so, which one and how?
 \item \#Q6: Would you make AdaptUI part of your future applications (if you
 plan to use adaptive interfaces)?
 \item \#Q7: Comments.
\end{enumerate}

The developers' responses are gathered in Table~\ref{tbl:developers_responses}
and Table~\ref{tbl:developers_responses_2}. The results show that the participating
developers have found the AdaptUI \ac{api} very useful. The comments, as expected,
reveal that they would find it more useful if a \acs{oop} paradigm is followed.
In the current version the definition and modification of the knowledge and of
the adaptation is more declarative. These considerations are gathered in
Section~\ref{sec:future_work}.

\begin{table}
  \caption{Developers' responses to the questionnaire. As responses for questions
  \#Q3, \#Q5 and \#Q7 might be too long, their details are given in
  Table~\ref{tbl:developers_responses_2}. If a response for any of these questions
  is given by the developer an asterisk symbol(*) is shown in the corresponding
  cell.}
 \label{tbl:developers_responses}
\footnotesize
\centering
 \begin{tabular}{l l l l l l l l}
  \hline
  \textbf{\#Developer} 	& \textbf{\#Q1} & \textbf{\#Q2} & \textbf{\#Q3} & \textbf{\#Q4} & \textbf{\#Q5} & \textbf{\#Q6} & \textbf{\#Q7} \\
  \hline
  \#1			& 4		& Yes		& * 		& Yes	 	& - 		& Yes 		& - \\
  \#2			& 5		& No		& - 		& Yes		& *		& Yes		& - \\
  \#3			& 5		& No		& - 		& No		& -		& Yes		& - \\
  \#4			& 4		& No		& - 		& Yes		& *		& Yes		& - \\
  \#5			& 4		& No		& - 		& Yes		& *		& Yes		& * \\
  \hline
\end{tabular}
\end{table}

\begin{table}
  \caption{Developers' responses to questions \#Q3, \#Q5 and \#Q7.}
 \label{tbl:developers_responses_2}
\footnotesize
\centering
 \begin{tabular}{l l l l l l l l}
  \hline
  \textbf{\#Developer} 	& \textbf{\#Q3} 		& \textbf{\#Q5} 	& \textbf{\#Q7}	\\
  \hline
  \#1			& To be able to define more	& -			& -		\\
			& than one configuration for 	& 			& 		\\
			& the same view.		& 			& 		\\
  \#2			& -				& \acs{oop} paradigm.	& -		\\
  \#3			& -				& -			& -		\\
  \#4			& - 				& Pass the object to	& \acs{oop} paradigm.	\\
			&				& the adaptation method & 		\\
			&				& as parameter.		& 		\\
  \#5			& -				& Pass the object to	& This is my first \\
			& 				& the adaptation method	& experience with  \\
			& 				& as parameter.		& ontologies, and I've \\
			&				&			& found it satisfactory. \\
  \hline
\end{tabular}
\end{table}


text:
==============

Dynabic .Net SDK

###The Starter Kit gives you access to the vast majority of features exposed by Dynabic Billing. Below is given a list containing the most prominent of these features:
 1.  Create, edit and retrieve Dynabic Billing Customers
 2.  Create, edit, retrieve and delete Dynabic Billing Products
 3.  Create, edit, retrieve and delete Subscriptions to Dynabic Products
 4.  Retrieve a list of Transactions for a specific Customer, Site or Subscription
 5.  Retrieve a list of Statements for a Subscription
 6.  Retrieve Reports that reflect the evolution of key parameters such as Product signups, Subscriptions count, Revenues and so on
 7.  You will also be able to set up webhooks in order to quickly find out about any changes in your subscriptions.


text:
var e = module.exports;
var env = e.env = require("../environment");

e.dependencies   = require("../dependencies");
e.util           = require('./util');

e.logger         = require("./logger");
e.Channel        = require("./channel").Channel;
e.ClientPool     = require("./client_pool").ClientPool;
e.ClientPoolStats= require("./client_pool").ClientPoolStats;
e.MessageList    = require("./message_list").MessageList;
e.Auth           = require("./authentication").Auth;
e.ParameterAuthentication = require("./parameter_authentication");
e.mongoose       = require('./db');
e.MetaUser       = require("./meta_user");
e.MetaUserManager= require("./meta_user_manager");
e.roles          = require("./roles");
e.Account        = require("./models/account");
e.AccountManager = require("./account_manager");
e.User           = require("./models/user");
e.ClientConnectors=require("./client_connectors");
e.ChannelManager = require('./channel_manager');
e.Expirer        = require('./expirer');
e.SocketIO       = e.dependencies.socketio;
e.Helpers        = {
	Assets:          require('./helpers/assets')
};
e.App            = require("./app");
e.middleware     = {
};
// TODO: The above model references should be phased out in preference of these
e.models         = {
	 Account:         require("./models/account")
	,User:            require("./models/user")
	,Room:            require("./models/room")
	,AccountStats:    require("./models/account_stats")
}
e.monitors       = {
	 PopularChannels: require('./monitors/popular_channels.js')
	,AppState:        require('./monitors/app_state_monitor.js')
	,NamespaceStats:  require('./monitors/namespace_stats.js')
}
e.loggers        = {
	 ChannelLogger:   require('./loggers/channel_logger.js')
	,AppStateLogger:  require('./loggers/app_state_logger.js')
	,LoggerCreator:   require('./loggers/logger_creator.js')
}
e.controllers    = {
	 Accounts:        require('./controllers/accounts.js')
	,Admin:           require('./controllers/admin.js')
	,Namespace:       require('./controllers/namespace.js')
	,Search:          require('./controllers/search.js')
	,Profile:         require('./controllers/profile.js')
}
e.errors         = require('./errors');
e.fail           = function(msg){throw msg};


text:
module.exports = {

  // middleware options
  // see: https://github.com/expressjs/session
  secret: 'ee589575f6c1fd6cb8fca521c5987498',
  resave: true,
  rolling: false,
  saveUninitialized: true

  // cookie: {
  //   path: '/',
  //   httpOnly: true,
  //   secure: false,
  //   maxAge: null
  // }

  // session store options (depends on store type)
  // store: {}

};


text:
package com.zaradai.gluon.client;

import com.google.common.util.concurrent.Service;
import com.zaradai.gluon.MicroService;

public interface Client extends Service {
    <Rep, Req> MicroService<Req, Rep> newService(String serviceName);
}


text:
from __future__ import print_function
import datetime, os, subprocess, sys, tempfile

from uncompyle6 import verify, IS_PYPY
from xdis.code import iscode
from uncompyle6.disas import check_object_path
from uncompyle6.semantics import pysource
from uncompyle6.parser import ParserError
from uncompyle6.version import VERSION
from uncompyle6.linenumbers import line_number_mapping

from xdis.load import load_module

def decompile(
        bytecode_version, co, out=None, showasm=None, showast=False,
        timestamp=None, showgrammar=False, code_objects={},
        source_size=None, is_pypy=False, magic_int=None):
    """
    ingests and deparses a given code block 'co'
    """
    assert iscode(co)

    # store final output stream for case of error
    real_out = out or sys.stdout
    co_pypy_str = 'PyPy ' if is_pypy else ''
    run_pypy_str = 'PyPy ' if IS_PYPY else ''
    print('# uncompyle6 version %s\n'
          '# %sPython bytecode %s%s\n# Decompiled from: %sPython %s' %
          (VERSION, co_pypy_str, bytecode_version,
           " (%d)" % magic_int if magic_int else "",
           run_pypy_str, '\n# '.join(sys.version.split('\n'))),
           file=real_out)
    if co.co_filename:
        print('# Embedded file name: %s' % co.co_filename,
              file=real_out)
    if timestamp:
        print('# Compiled at: %s' % datetime.datetime.fromtimestamp(timestamp),
              file=real_out)
    if source_size:
        print('# Size of source mod 2**32: %d bytes' % source_size,
               file=real_out)

    try:
        pysource.deparse_code(bytecode_version, co, out, showasm, showast,
                              showgrammar, code_objects=code_objects,
                              is_pypy=is_pypy)
    except pysource.SourceWalkerError as e:
        # deparsing failed
        raise pysource.SourceWalkerError(str(e))

# For compatiblity
uncompyle = decompile

def decompile_file(filename, outstream=None, showasm=None, showast=False,
                   showgrammar=False):
    """
    decompile Python byte-code file (.pyc)
    """

    filename = check_object_path(filename)
    code_objects = {}
    (version, timestamp, magic_int, co, is_pypy,
     source_size) = load_module(filename, code_objects)

    if type(co) == list:
        for con in co:
            decompile(version, con, outstream, showasm, showast,
                      timestamp, showgrammar, code_objects=code_objects,
                      is_pypy=is_pypy, magic_int=magic_int)
    else:
        decompile(version, co, outstream, showasm, showast,
                  timestamp, showgrammar,
                  code_objects=code_objects, source_size=source_size,
                  is_pypy=is_pypy, magic_int=magic_int)
    co = None

# For compatiblity
uncompyle_file = decompile_file

# FIXME: combine into an options parameter
def main(in_base, out_base, files, codes, outfile=None,
         showasm=None, showast=False, do_verify=False,
         showgrammar=False, raise_on_error=False,
         do_linemaps=False):
    """
    in_base	base directory for input files
    out_base	base directory for output files (ignored when
    files	list of filenames to be uncompyled (relative to src_base)
    outfile	write output to this filename (overwrites out_base)

    For redirecting output to
    - <filename>		outfile=<filename> (out_base is ignored)
    - files below out_base	out_base=...
    - stdout			out_base=None, outfile=None
    """
    def _get_outstream(outfile):
        dir = os.path.dirname(outfile)
        failed_file = outfile + '_failed'
        if os.path.exists(failed_file):
            os.remove(failed_file)
        try:
            os.makedirs(dir)
        except OSError:
            pass
        return open(outfile, 'w')

    tot_files = okay_files = failed_files = verify_failed_files = 0

    for filename in files:
        infile = os.path.join(in_base, filename)
        if not os.path.exists(infile):
            sys.stderr.write("File '%s' doesn't exist. Skipped\n"
                             % infile)
            continue

        # print (infile, file=sys.stderr)

        if outfile: # outfile was given as parameter
            outstream = _get_outstream(outfile)
        elif out_base is None:
            outstream = sys.stdout
            if do_linemaps or do_verify:
                prefix = os.path.basename(filename)
                if prefix.endswith('.py'):
                    prefix = prefix[:-len('.py')]
                junk, outfile = tempfile.mkstemp(suffix=".py",
                                             prefix=prefix)
                # Unbuffer output if possible
                buffering = -1 if sys.stdout.isatty() else 0
                sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', buffering)
                tee = subprocess.Popen(["tee", outfile], stdin=subprocess.PIPE)
                os.dup2(tee.stdin.fileno(), sys.stdout.fileno())
                os.dup2(tee.stdin.fileno(), sys.stderr.fileno())
        else:
            if filename.endswith('.pyc'):
                outfile = os.path.join(out_base, filename[0:-1])
            else:
                outfile = os.path.join(out_base, filename) + '_dis'
            outstream = _get_outstream(outfile)
        # print(outfile, file=sys.stderr)

        # Try to uncompile the input file
        try:
            decompile_file(infile, outstream, showasm, showast, showgrammar)
            tot_files += 1
        except (ValueError, SyntaxError, ParserError, pysource.SourceWalkerError) as e:
            sys.stdout.write("\n")
            sys.stderr.write("\n# file %s\n# %s\n" % (infile, e))
            failed_files += 1
        except KeyboardInterrupt:
            if outfile:
                outstream.close()
                os.remove(outfile)
            sys.stdout.write("\n")
            sys.stderr.write("\nLast file: %s   " % (infile))
            raise
        # except:
        #     failed_files += 1
        #     if outfile:
        #         outstream.close()
        #         os.rename(outfile, outfile + '_failed')
        #     else:
        #         sys.stderr.write("\n# %s" % sys.exc_info()[1])
        #         sys.stderr.write("\n# Can't uncompile %s\n" % infile)
        else: # uncompile successful
            if outfile:
                if do_linemaps:
                    mapping = line_number_mapping(infile, outfile)
                    outstream.write("\n\n## Line number correspondences\n")
                    import pprint
                    s = pprint.pformat(mapping, indent=2, width=80)
                    s2 = '##' + '\n##'.join(s.split("\n")) + "\n"
                    outstream.write(s2)
                outstream.close()

                if do_verify:
                    weak_verify = do_verify == 'weak'
                    try:
                        msg = verify.compare_code_with_srcfile(infile, outfile, weak_verify=weak_verify)
                        if not outfile:
                            if not msg:
                                print('\n# okay decompiling %s' % infile)
                                okay_files += 1
                            else:
                                print('\n# %s\n\t%s', infile, msg)
                    except verify.VerifyCmpError as e:
                        print(e)
                        verify_failed_files += 1
                        os.rename(outfile, outfile + '_unverified')
                        sys.stderr.write("### Error Verifying %s\n" % filename)
                        sys.stderr.write(str(e) + "\n")
                        if not outfile:
                            if raise_on_error:
                                raise
                            pass
                        pass
                pass
            elif do_verify:
                sys.stderr.write("\n### uncompile successful, but no file to compare against\n")
                pass
            else:
                okay_files += 1
                if not outfile:
                    mess = '\n# okay decompiling'
                    # mem_usage = __memUsage()
                    print(mess, infile)
        if outfile:
            sys.stdout.write("%s\r" %
                             status_msg(do_verify, tot_files, okay_files, failed_files, verify_failed_files))
            sys.stdout.flush()
    if outfile:
        sys.stdout.write("\n")
        sys.stdout.flush()
    return (tot_files, okay_files, failed_files, verify_failed_files)

# ---- main ----

if sys.platform.startswith('linux') and os.uname()[2][:2] in ['2.', '3.', '4.']:
    def __memUsage():
        mi = open('/proc/self/stat', 'r')
        mu = mi.readline().split()[22]
        mi.close()
        return int(mu) / 1000000
else:
    def __memUsage():
        return ''

def status_msg(do_verify, tot_files, okay_files, failed_files,
               verify_failed_files):
    if tot_files == 1:
        if failed_files:
            return "\n# decompile failed"
        elif verify_failed_files:
            return "\n# decompile verify failed"
        else:
            return "\n# Successfully decompiled file"
            pass
        pass
    mess = "decompiled %i files: %i okay, %i failed" % (tot_files, okay_files, failed_files)
    if do_verify:
        mess += (", %i verify failed" % verify_failed_files)
    return mess


text:
var cronJob = require('cron').CronJob,
    hipqus = require('./hipqus.js'),
    D  = require('./disqus-config.js');

var lastTimestamp = null;

new cronJob('*/10 * * * * *', function (){

    D.disqus.request('posts/list', D.disqus_options, function(data) {

        if(data.error){
            console.log('Something went wrong...');
            console.log(data);
        }else{
            var response = JSON.parse(data).response;

            if(!lastTimestamp){
                // initializing lastTimestamp with most recent comment date
                lastTimestamp = new Date(response[0].createdAt);
            }else{
                var mostRecentTimestamp = null;
                for(var i=0; i < response.length; i++){
                    var postDate = new Date(response[i].createdAt);
                    if(postDate > lastTimestamp){
                        hipqus.buildMessage(response[i]);
                        if(!mostRecentTimestamp){
                            mostRecentTimestamp = postDate;
                        }
                    }else{
                        console.log('Nothing new to send. Last comment timestamp: ' + lastTimestamp.toISOString());
                        break;
                    }
                }
                if(mostRecentTimestamp){
                    lastTimestamp = mostRecentTimestamp;
                }
            }
        }
    });

}, null, true, null);


text:
#ifndef ATL_AST_ACCESS_HPP
#define ATL_AST_ACCESS_HPP

#include <atl/utility.hpp>
#include <atl/is.hpp>
#include <atl/wrap.hpp>
#include <atl/gc/marked.hpp>

#include <atl/print.hpp>

#include <cassert>
#include <memory>

/* Small Ast helpers with minimal external dependencies */
namespace atl
{
	struct AstSubscripter
	{
		Any value;
		AstSubscripter(Any const& in)
			: value(in)
		{ assert(!is<AstData>(in)); }
		AstSubscripter(Ast& value_) : value(wrap(value_)) {}
		AstSubscripter() = delete;

		AstSubscripter operator[](off_t pos)
		{ return AstSubscripter(unwrap<Ast>(value)[pos]); }
	};

	template<class T>
	AstSubscripter subscripter(T&& ast)
	{ return AstSubscripter(ast); }

	AstSubscripter inner_subscript(AstSubscripter ast, size_t pos)
	{ return ast[pos]; }

	template<class ... Args>
	AstSubscripter inner_subscript(AstSubscripter ast, size_t pos, Args ... rest)
	{ return inner_subscript(ast[pos], rest...); }

	template<class T, class ... Args>
	Any subscript(T&& ast, Args ... args)
	{ return inner_subscript(ast, args...).value; }

	Range<Ast::flat_iterator> flat_ast(Ast& ast)
	{ return make_range(ast.flat_begin(), ast.flat_end()); }

	bool operator!=(Ast const& aa_tree, Ast const& bb_tree);

	bool operator==(Ast const& aa_tree, Ast const& bb_tree)
	{
		auto aa = aa_tree.begin(),
			bb = bb_tree.begin();

		while((aa != aa_tree.end()) && (bb != bb_tree.end()))
			{
				if(aa->_tag != bb->_tag)
					{ return false; }

				switch(aa->_tag)
					{
					case tag<AstData>::value:
						{
							if(Ast(const_cast<AstData*>(reinterpret_cast<AstData const*>(aa.pointer())))
							   != Ast(const_cast<AstData*>(reinterpret_cast<AstData const*>(bb.pointer()))))
								{ return false; }
							break;
						}
					case tag<Ast>::value:
						{
							if(reinterpret_cast<Ast const&>(aa)
							   != reinterpret_cast<Ast const&>(bb))
								{ return false; }
							break;
						}
					case tag<Symbol>::value:
						{
							if(reinterpret_cast<Symbol*>(aa->value)->name
							   != reinterpret_cast<Symbol*>(bb->value)->name)
								{ return false; }
							break;
						}
					default:
						if(*bb != *aa)
							{ return false; }
					}

				++bb;
				++aa;
			}

		if((bb != bb_tree.end()) || (aa != aa_tree.end()))
			{ return false; }
		return true;
	}

	bool operator!=(Ast const& aa_tree, Ast const& bb_tree)
	{ return !(aa_tree == bb_tree); }

	// Generic interface for traversing an Ast.  Derived classes can
	// do whatever transforms make sense.
	struct WalkAst
	{
		typedef std::unique_ptr<WalkAst> WalkerPtr;

		virtual ~WalkAst() {}

		virtual tag_t tag()=0;
		virtual Any value()=0;

		virtual bool has_value()=0;
		bool at_end() { return !has_value(); }

		virtual bool at_begin()=0;

		virtual void next()=0;

		virtual bool is_subex()=0;

		virtual void down()=0;

		virtual void up()=0;

		struct SubexRAII
		{
			WalkAst& walker;
			SubexRAII(WalkAst& walker_)
				: walker(walker_)
			{ walker.down(); }

			~SubexRAII()
			{ walker.up(); }
		};

		SubexRAII walk_subex()
		{ return SubexRAII(*this); }

		virtual WalkerPtr clone() const=0;

		// Set the state of this to match the state of other.  Raise
		// WrongType if other's static type is different.
		virtual void reset(WalkAst const& other)=0;

		template<class T>
		WalkerPtr _clone(T const* ptr) const { return WalkerPtr(new T(*ptr)); }

		// Returns an iterator which indicates the walkers current
		// position in the Ast.
		virtual Ast::iterator here()=0;

		// Returns the subex at the position we have walked to.
		// Undefined if we are not on a sub-expression.
		virtual Ast::Subex subex()=0;
	};

	struct WalkAstIterator
		: public WalkAst
	{
		Ast::iterator begin, itr, end;
		std::vector<Ast::Subex> stack;

		WalkAstIterator(Ast::iterator const& begin_, Ast::iterator const& end_)
			: begin(begin_), itr(begin_), end(end_)
		{}

		virtual ~WalkAstIterator() override {}

		virtual bool has_value() override { return itr != end; }

		virtual bool at_begin() override { return itr == begin; }

		virtual Any value() override
		{
			if(!has_value())
				{
					throw RangeError
						("WalkAstIterator can't get value past this->end");
				}
			return *itr;
		}
		virtual tag_t tag() override { return itr.tag(); }

		virtual void next() override { ++itr; }

		virtual bool is_subex() override
		{ return itr.is<AstData>() || itr.is<Ast>(); }

		virtual void down() override
		{
			stack.emplace_back(itr, end);
			std::tie(itr, end) = atl::subex(itr);
		}

		virtual void up() override
		{
			std::tie(itr, end) = stack.back();
			stack.pop_back();
		}

		Ast::Subex _range()
		{
			auto any = value();
			switch(any._tag)
				{
				case atl::tag<Ast>::value:
					return unwrap<Ast>(any).subex();
					break;
				case atl::tag<AstData>::value:
					return Ast(&explicit_unwrap<AstData>(any)).subex();
					break;
				default:
					throw WrongTypeError("WalkAstIterator not on a sub-expression");
				}
		}

		virtual WalkerPtr clone() const override { return _clone(this); }

		virtual void reset(WalkAst const& raw_other) override
		{
			auto const& other = dynamic_cast<WalkAstIterator const&>(raw_other);
			itr = other.itr;
			end = other.end;
		}

		virtual Ast::iterator here() override { return itr; }
		virtual Ast::Subex subex() override { return atl::subex(itr); }
	};

	WalkAstIterator walk(Ast::iterator const& itr, Ast::iterator const& end)
	{ return WalkAstIterator(itr, end); }

	WalkAstIterator walk(Ast& ast)
	{ return WalkAstIterator(ast.begin(), ast.end()); }

	WalkAstIterator walk(Marked<Ast>& ast)
	{ return walk(*ast); }

	WalkAstIterator walk(Ast::Subex& ast)
	{ return walk(std::get<0>(ast), std::get<1>(ast)); }

	WalkAstIterator walk(Ast::Subex&& ast) { return walk(ast); }

	namespace printer
	{
		struct PrintWalker : public Printer
		{
			WalkAst::WalkerPtr walker;

			PrintWalker(WalkAst const& walker_)
				: walker(walker_.clone())
			{}

			void _dispatch(WalkAst& walker, std::ostream& out) const
			{
				if(walker.is_subex())
					{
						auto inner = walker.walk_subex();
						_ast(walker, out);
					}
				else
					{ print_atom(walker.value(), out); }
			}

			void _ast(WalkAst& walker, std::ostream& out) const
			{
				out << "(";
				if(walker.has_value())
					{
						_dispatch(walker, out);
						walker.next();
						for(; walker.has_value(); walker.next())
							{
								out << " ";
								_dispatch(walker, out);
							}
					}
				out << ")";
			}

			virtual std::ostream& print(std::ostream& out) const override
			{
				auto clone = walker->clone();
				_ast(*clone, out);
				return out;
			}
		};

		PrintWalker walker(WalkAst const& walker)
		{ return PrintWalker(walker); }
	}
}

#endif


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Test
{
    public class MyComponent
    {
        //TODO!!!
    }
}


text:
import backoff
import pytest
import requests

@backoff.on_exception(backoff.expo,
                      (requests.exceptions.Timeout,
                       requests.exceptions.ConnectionError),
                      max_tries=2)
def _get_request(example_container):
    return requests.get("http://{url}/".format(url=example_container))

def test__works(example_container):
    result = _get_request(example_container)
    assert result.json() == {"status": "alive"}

@pytest.mark.skip(reason="For demonstrating log output on failure")
def test__error(example_container):
    raise Exception("oh no!")