text:
#ifndef __APEXSHAREDSERIALIZATION_H__
#define __APEXSHAREDSERIALIZATION_H__

#include "NxApex.h"
#include "ApexStream.h"
#include "ApexString.h"
#include "ApexSharedUtils.h"
#include "NiApexSDK.h"
#include "NxParameterized.h"

namespace physx
{
namespace apex
{

struct ApexStreamVersion
{
	enum Enum
	{
		First = 0,
		ConsolidatedSubmeshes = 1,
		TriangleFlags = 2,
		ConvexHull_VolumeStreamed = 3,
		AddedDestrucibleDeformation = 4,
		RemovedParticleSizeFromDestructibleParameters = 5,
		TriangleFlagsChangedToExtraDataIndex = 6,
		ConvexHull_EdgesStreamed = 7,
		AddedDestrucibleDebrisParamaters = 8,
		DestrucibleDebrisParamatersHaveLODRange = 9,
		UniversalNamedAssetHeader = 10,
		ClothMeshBindPoses = 10, // PH: This is not a mistake, this enum was added in another branch while other enums were added in //trunk
		VariableVertexData = 11,
		SoftBodyNormalsStreamed = 11, // PH: This is not a mistake, this enum was added in another branch while other enums were added in //trunk
		UsingApexMaterialLibrary_and_NoFlagsInNxRenderTriangle = 12,
		AddingTextureTypeInformationToVertexFormat = 13,
		SoftBodyNormalsInTetraLink = 14,
		ClothingVertexFlagsStreamed = 15,
		ConvexHullModifiedForEfficientCollisionTests = 16,
		RenderMeshAssetRedesign = 17,
		FixedSerializationAfterRenderMeshAssetRedesign = 18,
		AddedRenderCullModeToRenderMeshAsset = 19,
		AddedTextureUVOriginField = 19,	// BRG: merge conflict
		AddedDynamicVertexBufferField = 20,
		RenderMeshAssetBufferOverrunFix = 21,
		CleanupOfApexRenderMesh = 22,
		RemovedTextureTypeInformationFromVertexFormat = 23,
		AddedDestructibleFlag_FormExtendedStructures = 24,
		MarkingDestructibleChunksWithFlagToDenoteUnfracturableDescendant = 25,
		AddedValidBoundsToDestructibleParameters = 26,
		ReducingAssetUponDeserializationForReducedLOD = 27,
		AddedDustMeshParticleFactoryNameToDestructibleAsset = 28,
		AddedChunkSurfaceTracesToDestructibleAsset = 29,
		AddedInteriorSubmeshIndexToDestructibleAsset = 30,
		AddedMaxChunkSpeedAndMassScaleExponentToDestructibleAsset = 31,
		AddedGrbVolumeLimit = 32,
		Removing_rollSign_and_rollAxis_fromAPI = 33,
		AddedFractureImpulseScale = 34,
		AddedMissingRuntimeFlagsAndAlsoTraceSetAverageNormalToDestructibleAssetStream = 35,
		CachingChunkOverlapDataInDestructibleAsset = 36,
		AddedRotationCaps = 37,
		AddedImpactVelocityThreshold = 37, // SJB: Trust me, this should be 37
		ChangedVertexColorFormatToReal = 38,
		AddedEssentialDepthParameter = 39,
		AddedSeparateBoneBufferFlagToRenderMeshAsset = 40,
		DoNotNormalizeBoneWeightsOnLoad = 41, // PH: This is a change for deserialization only, we don't need to do additional processing when newer than this
		MovedChunkSurfaceNormalFromTraceSetToChunk = 41,
		FlattenedVertexBuffer = 42,
		RemovedSubmeshTriangleStruct = 43,
		DestructibleAssetRearrangementForParameterization = 44,
		AddedDestructibleMaterialStrength = 45,
		ExposedChunkNeighborPadding = 46,
		ChangedVertexFormat = 47,
		UnifiedCustomAndStandardSemantics = 48,
		AddedAdjacentPlanesToConvexHullStream = 49,
		//	Always add a new version just before this line

		Count,
		Current = Count - 1
	};
};

/*****************************************************************************/
//	Non-versioned data (e.g. basic types) may use the << and >> operators
//	defined in ApexStream.h.  This file contains (de)serialization for
//	versioned data.
//
//	Serialization version is written "upstream" by a versioned parent object.
//	To add the version number to the streamed data for an object, record this
//	change in the ApexStreamVersion enum, and add the line:
//		stream << (physx::PxU32)ApexStreamVersion_Current;
//	to the serialize function.
//
//  Serialization signature:
//		void serialize( physx::PxFileBuf& stream, const typename& object )
//
//	Deserialization signature:
//		void deserialize( physx::PxFileBuf& stream, physx::PxU32 version, typename& object )
/*****************************************************************************/

// Template foo
PX_INLINE void serialize(physx::PxFileBuf& stream, const NxExplicitRenderTriangle& t);
PX_INLINE void deserialize(physx::PxFileBuf& stream, physx::PxU32 version, NxExplicitRenderTriangle& t);
PX_INLINE void serialize(physx::PxFileBuf& stream, const NxVertexUV& uv);
PX_INLINE void deserialize(physx::PxFileBuf& stream, physx::PxU32 version, NxVertexUV& uv);
PX_INLINE void serialize(physx::PxFileBuf& stream, const NxVertex& v);
PX_INLINE void deserialize(physx::PxFileBuf& stream, physx::PxU32 version, NxVertex& v);
PX_INLINE void serialize(physx::PxFileBuf& stream, const ApexSimpleString& s);
PX_INLINE void deserialize(physx::PxFileBuf& stream, physx::PxU32 version, ApexSimpleString& s);
PX_INLINE void serialize(physx::PxFileBuf& stream,
                         physx::PxU32 headerVersion,
                         const NxParameterized::Interface* param,
                         NxParameterized::Handle& childHandle);
PX_INLINE void serialize(physx::PxFileBuf& stream,
                         physx::PxU32 headerVersion,
                         const NxParameterized::Interface* param,
                         const char* memberName,
                         NxParameterized::Handle* structHandle = NULL);
PX_INLINE void deserialize(physx::PxFileBuf& stream,
                           physx::PxU32 headerVersion,
                           NxParameterized::Interface* param,
                           NxParameterized::Handle& childHandle);
PX_INLINE void deserialize(physx::PxFileBuf& stream,
                           physx::PxU32 headerVersion,
                           NxParameterized::Interface* param,
                           const char* memberName,
                           NxParameterized::Handle* structHandle = NULL);

// Utility to write an APEX asset stream header
PX_INLINE void serializeCurrentApexStreamVersion(physx::PxFileBuf& stream, const ApexSimpleString& assetTypeName, physx::PxU32 assetVersion)
{
	stream << (physx::PxU32)ApexStreamVersion::Current;
	serialize(stream, assetTypeName);
	stream << assetVersion;
}

// Utility to read version header from the start of an APEX asset stream
PX_INLINE ApexStreamVersion::Enum deserializeApexStreamVersion(physx::PxFileBuf& stream, const ApexSimpleString& assetTypeName, physx::PxU32& assetVersion)
{
	physx::PxU32 headerVersion;
	stream >> headerVersion;
	if (headerVersion > ApexStreamVersion::Current)
	{
		APEX_INTERNAL_ERROR("Stream version (%d) is newer than this library (%d)", headerVersion, ApexStreamVersion::Current);
		PX_ALWAYS_ASSERT();
	}
	else if (headerVersion >= ApexStreamVersion::UniversalNamedAssetHeader)
	{
		ApexSimpleString streamedName;
		deserialize(stream, headerVersion, streamedName);
		if (streamedName == assetTypeName)
		{
			stream >> assetVersion;
		}
		else
		{
			APEX_INTERNAL_ERROR("Asset type name mismatch.  File <%s> != asset name <%s>",
			                    assetTypeName.c_str(), streamedName.c_str());
			PX_ALWAYS_ASSERT();
		}
	}
	return (ApexStreamVersion::Enum)headerVersion;
}

// Utility to read version header from the start of an APEX asset stream, when the type is unknown
PX_INLINE ApexStreamVersion::Enum deserializeGenericApexStreamVersion(physx::PxFileBuf& stream, ApexSimpleString& outAssetTypeName, physx::PxU32& outAssetVersion)
{
	physx::PxU32 headerVersion;
	stream >> headerVersion;

	if (headerVersion > ApexStreamVersion::Current)
	{
		APEX_INTERNAL_ERROR("Stream version (%d) is newer than this library (%d)", headerVersion, ApexStreamVersion::Current);
		PX_ALWAYS_ASSERT();
	}
	else if (headerVersion >= ApexStreamVersion::UniversalNamedAssetHeader)
	{
		ApexSimpleString streamedName;
		deserialize(stream, headerVersion, outAssetTypeName);
		stream >> outAssetVersion;
	}
	else
	{
		APEX_INTERNAL_ERROR("Stream version (%d) does not contain a universal named asset header, " \
		                    "use a specific asset creation method to load this asset", headerVersion);
		PX_ALWAYS_ASSERT();
	}
	return (ApexStreamVersion::Enum)headerVersion;
}

// Versioned wrappers for non-versioned data
template <class T> PX_INLINE void serialize(physx::PxFileBuf& stream, const T& t)
{
	stream << t;
}

template <class T> PX_INLINE void deserialize(physx::PxFileBuf& stream, physx::PxU32 version, T& t)
{
	PX_UNUSED(version);
	stream >> t;
}

// physx::Array<T>
template <class T> PX_INLINE void serialize(physx::PxFileBuf& stream, const physx::Array<T>& array)
{
	const physx::PxU32 size = array.size();
	stream << size;
	for (physx::PxU32 i = 0; i < size; ++i)
	{
		serialize(stream, array[i]);
	}
}

template <class T> PX_INLINE void deserialize(physx::PxFileBuf& stream, physx::PxU32 version, physx::Array<T>& array)
{
	physx::PxU32 size;
	stream >> size;
	array.resize(size);
	for (physx::PxU32 i = 0; i < size; ++i)
	{
		deserialize(stream, version, array[i]);
	}
}

// Several serialized objects have multiple associated versions
template <class T> PX_INLINE void deserialize(physx::PxFileBuf& stream, physx::PxU32 version0, physx::PxU32 version1, physx::Array<T>& array)
{
	physx::PxU32 size;
	stream >> size;
	array.resize(size);
	for (physx::PxU32 i = 0; i < size; ++i)
	{
		deserialize(stream, version0, version1, array[i]);
	}
}

// NxVertexUV
PX_INLINE void serialize(physx::PxFileBuf& stream, const NxVertexUV& uv)
{
	stream << uv.u << uv.v;
}

PX_INLINE void deserialize(physx::PxFileBuf& stream, physx::PxU32 version, NxVertexUV& uv)
{
	// original version
	PX_UNUSED(version);
	stream >> uv.u >> uv.v;
}

// NxVertexColor
PX_INLINE void serialize(physx::PxFileBuf& stream, const NxVertexColor& c)
{
	stream << c.r << c.g << c.b << c.a;
}

PX_INLINE void deserialize(physx::PxFileBuf& stream, physx::PxU32 version, NxVertexColor& c)
{
	// original version
	PX_UNUSED(version);
	stream >> c.r >> c.g >> c.b >> c.a;
}

// NxVertex
PX_INLINE void serialize(physx::PxFileBuf& stream, const NxVertex& v)
{
	//
	stream << v.position << v.normal << v.tangent << v.binormal;
	serialize(stream, v.uv[0]);
	serialize(stream, v.uv[1]);
	serialize(stream, v.uv[2]);
	serialize(stream, v.uv[3]);
	serialize(stream, v.color);
	for (physx::PxU32 i = 0; i < 4; i++)
	{
		stream << v.boneIndices[i];
		stream << v.boneWeights[i];
	}
}

PX_INLINE void deserialize(physx::PxFileBuf& stream, physx::PxU32 version, NxVertex& v)
{
	if (version < ApexStreamVersion::RenderMeshAssetRedesign)
	{
		// set all other indices and weights to 0
		v.boneWeights[0] = 1.0f;
		for (physx::PxU32 i = 1; i < 4; i++)
		{
			v.boneIndices[i] = 0;
			v.boneWeights[i] = 0.0f;
		}
	}

	if (version >= ApexStreamVersion::VariableVertexData)
	{
		stream >> v.position >> v.normal >> v.tangent >> v.binormal;
		deserialize(stream, version, v.uv[0]);
		deserialize(stream, version, v.uv[1]);
		deserialize(stream, version, v.uv[2]);
		deserialize(stream, version, v.uv[3]);
		if (version >= ApexStreamVersion::ChangedVertexColorFormatToReal)
		{
			deserialize(stream, version, v.color);
		}
		else
		{
			physx::PxU32 intColor;
			stream >> intColor;
			v.color = NxVertexColor(PxColorRGBA((PxU8)(intColor & 255), (PxU8)((intColor >> 8) & 255), (PxU8)((intColor >> 16) & 255), (PxU8)(intColor >> 24)));
		}
		if (version >= ApexStreamVersion::RenderMeshAssetRedesign)
		{
			for (physx::PxU32 i = 0; i < 4; i++)
			{
				stream >> v.boneIndices[i];
				stream >> v.boneWeights[i];
			}
			if (version < ApexStreamVersion::RenderMeshAssetBufferOverrunFix)
			{
				physx::PxU16 dummyU16;
				physx::PxF32 dummyF32;
				for (physx::PxU32 i = 0; i < 4; i++)
				{
					stream >> dummyU16;
					stream >> dummyF32;
				}
			}
		}
		else
		{
			physx::PxU32 boneIndex;
			stream >> boneIndex;
			v.boneIndices[0] = (physx::PxU16)boneIndex;
		}
	}
	else
	{
		stream >> v.position >> v.normal >> v.tangent >> v.binormal >> v.uv[0][0] >> v.uv[0][1];
		physx::PxU32 intColor;
		stream >> intColor;
		v.color = NxVertexColor(PxColorRGBA((PxU8)(intColor & 255), (PxU8)((intColor >> 8) & 255), (PxU8)((intColor >> 16) & 255), (PxU8)(intColor >> 24)));
		stream >> v.boneIndices[0];
	}
}

// NxExplicitRenderTriangle
PX_INLINE void serialize(physx::PxFileBuf& stream, const NxExplicitRenderTriangle& t)
{
	serialize(stream, t.vertices[0]);
	serialize(stream, t.vertices[1]);
	serialize(stream, t.vertices[2]);
	stream << t.submeshIndex << t.smoothingMask << t.extraDataIndex;
}

PX_INLINE void deserialize(physx::PxFileBuf& stream, physx::PxU32 version, NxExplicitRenderTriangle& t)
{
	deserialize(stream, version, t.vertices[0]);
	deserialize(stream, version, t.vertices[1]);
	deserialize(stream, version, t.vertices[2]);
	stream >> t.submeshIndex >> t.smoothingMask;
	if (version >= ApexStreamVersion::TriangleFlagsChangedToExtraDataIndex)
	{
		stream >> t.extraDataIndex;
	}
	else
	{
		if (version >= ApexStreamVersion::TriangleFlags)
		{
			physx::PxU32 deadData;
			stream >> deadData;
		}
		t.extraDataIndex = 0xFFFFFFFF;
	}
}

// ApexSimpleString
PX_INLINE void serialize(physx::PxFileBuf& stream, const ApexSimpleString& s)
{
	s.serialize(stream);
	//stream << s.len();
	//stream.storeBuffer( s.c_str(), s.len() );
}

PX_INLINE void deserialize(physx::PxFileBuf& stream, physx::PxU32 version, ApexSimpleString& s)
{
	PX_UNUSED(version);
	s.deserialize(stream);
}

// ConvexHull
PX_INLINE void serialize(physx::PxFileBuf& stream, const ConvexHull& h)
{
	if (h.mParams == NULL)
	{
		PX_ASSERT(!"Attempting to serialize a ConvexHull with NULL NxParameters.");
		return;
	}

	Array<PxVec3>	vertices;
	Array<physx::PxPlane>	uniquePlanes;
	Array<PxU32>	edges;
	Array<PxU32>	adjacentFaces;
	Array<PxF32>	widths;

	NxParameterized::Handle handle(*h.mParams);

	// vertices
	vertices.resize((physx::PxU32)h.mParams->vertices.arraySizes[0]);
	h.mParams->getParameterHandle("vertices", handle);
	h.mParams->getParamVec3Array(handle, vertices.begin(), (physx::PxI32)vertices.size());
	serialize(stream, vertices);

	// uniquePlanes
	uniquePlanes.resize((physx::PxU32)h.mParams->uniquePlanes.arraySizes[0]);
	for (physx::PxU32 i = 0; i < (physx::PxU32)h.mParams->uniquePlanes.arraySizes[0]; ++i)
	{
		ConvexHullParametersNS::Plane_Type& plane = h.mParams->uniquePlanes.buf[i];
		uniquePlanes[i] = physx::PxPlane(plane.normal, plane.d);
	}
	serialize(stream, uniquePlanes);

	// bounds
	stream << h.mParams->bounds;

	// volume
	stream << h.mParams->volume;

	// edges
	edges.resize((physx::PxU32)h.mParams->edges.arraySizes[0]);
	h.mParams->getParameterHandle("edges", handle);
	h.mParams->getParamU32Array(handle, edges.begin(), (physx::PxI32)edges.size());
	serialize(stream, edges);

	// adjacentFaces
	adjacentFaces.resize((physx::PxU32)h.mParams->adjacentFaces.arraySizes[0]);
	h.mParams->getParameterHandle("adjacentFaces", handle);
	h.mParams->getParamU32Array(handle, adjacentFaces.begin(), (physx::PxI32)adjacentFaces.size());
	serialize(stream, adjacentFaces);

	// widths
	widths.resize((physx::PxU32)h.mParams->widths.arraySizes[0]);
	h.mParams->getParameterHandle("widths", handle);
	h.mParams->getParamF32Array(handle, widths.begin(), (physx::PxI32)widths.size());
	serialize(stream, widths);

	// unique direction count
	stream << h.mParams->uniqueEdgeDirectionCount;

	// plane count
	stream << h.mParams->planeCount;
}

PX_INLINE void deserialize(physx::PxFileBuf& stream, physx::PxU32 version, ConvexHull& h)
{
	if (h.mParams == NULL)
	{
		h.init();
	}

	Array<PxVec3>	vertices;
	Array<physx::PxPlane>	uniquePlanes;
	Array<PxU32>	edges;
	Array<PxU32>	adjacentFaces;
	Array<PxF32>	widths;

	NxParameterized::Handle handle(*h.mParams);

	// vertices
	deserialize(stream, version, vertices);
	h.mParams->getParameterHandle("vertices", handle);
	h.mParams->resizeArray(handle, (physx::PxI32)vertices.size());
	h.mParams->setParamVec3Array(handle, vertices.begin(), (physx::PxI32)vertices.size());

	// uniquePlanes
	deserialize(stream, version, uniquePlanes);
	h.mParams->getParameterHandle("uniquePlanes", handle);
	h.mParams->resizeArray(handle, (physx::PxI32)uniquePlanes.size());
	for (physx::PxU32 i = 0; i < uniquePlanes.size(); ++i)
	{
		physx::PxPlane& plane = uniquePlanes[i];
		ConvexHullParametersNS::Plane_Type& paramPlane = h.mParams->uniquePlanes.buf[i];
		paramPlane.normal = plane.n;
		paramPlane.d = plane.d;
	}

	// bounds
	stream >> h.mParams->bounds;

	// volume
	if (version >= ApexStreamVersion::ConvexHull_VolumeStreamed)
	{
		stream >> h.mParams->volume;
	}

	bool needsRebuild = false;

	if (version >= ApexStreamVersion::ConvexHull_EdgesStreamed)
	{
		// edges
		deserialize(stream, version, edges);
		h.mParams->getParameterHandle("edges", handle);
		h.mParams->resizeArray(handle, (physx::PxI32)edges.size());
		h.mParams->setParamU32Array(handle, edges.begin(), (physx::PxI32)edges.size());

		if (version >= ApexStreamVersion::AddedAdjacentPlanesToConvexHullStream)
		{
			// adjacentFaces
			deserialize(stream, version, adjacentFaces);
			h.mParams->getParameterHandle("adjacentFaces", handle);
			h.mParams->resizeArray(handle, (physx::PxI32)adjacentFaces.size());
			h.mParams->setParamU32Array(handle, adjacentFaces.begin(), (physx::PxI32)adjacentFaces.size());
		}
		else
		{
			needsRebuild = true;
		}

		if (version >= ApexStreamVersion::ConvexHullModifiedForEfficientCollisionTests)
		{
			// widths
			deserialize(stream, version, widths);
			h.mParams->getParameterHandle("widths", handle);
			h.mParams->resizeArray(handle, (physx::PxI32)widths.size());
			h.mParams->setParamF32Array(handle, widths.begin(), (physx::PxI32)widths.size());

			// unique direction count
			stream >> h.mParams->uniqueEdgeDirectionCount;

			// plane count
			stream >> h.mParams->planeCount;
		}
		else
		{
			// Fix up
			// Ouch - rebuilding!
			// \todo - issue load performance warning
			h.buildFromPoints(vertices.begin(), vertices.size(), sizeof(physx::PxVec3));
		}
	}
	else
	{
		needsRebuild = true;
	}

	if (needsRebuild)
	{
		// Ouch - rebuilding!
		// \todo - issue load performance warning
		h.buildFromPoints(vertices.begin(), vertices.size(), sizeof(physx::PxVec3));
	}
}

// PxParamerized F32, U32, string, enum, and named ref
PX_INLINE void serialize(physx::PxFileBuf& stream,
                         physx::PxU32 headerVersion,
                         const NxParameterized::Interface* param,
                         NxParameterized::Handle& childHandle)
{
	PX_UNUSED(headerVersion);
	PX_UNUSED(param);
	PX_ASSERT(childHandle.getConstInterface() == param);

	ApexSimpleString tmpString;

	if (childHandle.parameterDefinition()->type() == NxParameterized::TYPE_REF)
	{
		// named reference (we should check that it is not INCLUDED)

		NxParameterized::Interface* childParamPtr = 0;

		// just in case it wasn't initialized
		//if( param->initParamRef(childHandle, NULL, true) != NxParameterized::ERROR_NONE )
		//{
		//	return;
		//}

		childHandle.getParamRef(childParamPtr);

		if (!childParamPtr)  //Special case hack...
		{
			childHandle.initParamRef(NULL, true);
			childHandle.getParamRef(childParamPtr);
		}

		if (childParamPtr)
		{
			tmpString = childParamPtr->className();
			tmpString.serialize(stream);

			tmpString = childParamPtr->name();
			tmpString.serialize(stream);
		}
	}
	else if (childHandle.parameterDefinition()->type() == NxParameterized::TYPE_STRING)
	{
		const char* str;
		childHandle.getParamString(str);
		tmpString = str;
		tmpString.serialize(stream);
	}
	else if (childHandle.parameterDefinition()->type() == NxParameterized::TYPE_ENUM)
	{
		const char* str;
		childHandle.getParamEnum(str);
		tmpString = str;
		tmpString.serialize(stream);
	}
	else
	{
		switch (childHandle.parameterDefinition()->type())
		{
		case NxParameterized::TYPE_VEC3:
		{
			physx::PxVec3 d;
			childHandle.getParamVec3(d);
			stream << d;
			break;
		}
		case NxParameterized::TYPE_F32:
		{
			physx::PxF32 d;
			childHandle.getParamF32(d);
			stream << d;
			break;
		}
		case NxParameterized::TYPE_U32:
		{
			physx::PxU32 d;
			childHandle.getParamU32(d);
			stream << d;
			break;
		}
		case NxParameterized::TYPE_BOOL:
		{
			bool d;
			childHandle.getParamBool(d);
			if (d)
			{
				stream.storeByte((physx::PxU8)1);
			}
			else
			{
				stream.storeByte((physx::PxU8)0);
			}
			break;
		}
		default:
			PX_ALWAYS_ASSERT();
		}
	}
}

PX_INLINE void serialize(physx::PxFileBuf& stream,
                         physx::PxU32 headerVersion,
                         const NxParameterized::Interface* param,
                         const char* memberName,
                         NxParameterized::Handle* structHandle)
{
	PX_UNUSED(headerVersion);

	NxParameterized::Handle childHandle(*param);
	if (structHandle)
	{
		structHandle->getChildHandle(param, memberName, childHandle);
	}
	else
	{
		param->getParameterHandle(memberName, childHandle);
	}

	serialize(stream, headerVersion, param, childHandle);
}

// PxParamerized F32, U32, string, enum, and named ref
// PxParamerized F32, U32, string, enum, and named ref
PX_INLINE void deserialize(physx::PxFileBuf& stream,
                           physx::PxU32 headerVersion,
                           NxParameterized::Interface* param,
                           NxParameterized::Handle& childHandle)
{
	PX_UNUSED(param);
	PX_ASSERT(childHandle.getConstInterface() == param);
	ApexSimpleString tmpString;

	if (childHandle.parameterDefinition()->type() == NxParameterized::TYPE_REF)
	{
		deserialize(stream, headerVersion, tmpString);

		// named reference (we should check that it is not INCLUDED
		NxParameterized::Interface* childParamPtr = 0;

		// tmpString is the className (asset authorable name)
		childHandle.initParamRef(tmpString.c_str(), true);
		childHandle.getParamRef(childParamPtr);

		PX_ASSERT(childParamPtr);
		if (childParamPtr)
		{
			deserialize(stream, headerVersion, tmpString);
			childParamPtr->setName(tmpString.c_str());
		}

	}
	else if (childHandle.parameterDefinition()->type() == NxParameterized::TYPE_STRING)
	{
		deserialize(stream, headerVersion, tmpString);
		childHandle.setParamString(tmpString.c_str());
	}
	else if (childHandle.parameterDefinition()->type() == NxParameterized::TYPE_ENUM)
	{
		deserialize(stream, headerVersion, tmpString);
		if (childHandle.setParamEnum(tmpString.c_str()) != NxParameterized::ERROR_NONE)
		{
			APEX_DEBUG_WARNING("NxParameterized ENUM value not correct: %s, substituting: %s", \
			                   tmpString.c_str(), childHandle.parameterDefinition()->enumVal(0));

			childHandle.setParamEnum(childHandle.parameterDefinition()->enumVal(0));
		}

	}
	else
	{
		switch (childHandle.parameterDefinition()->type())
		{
		case NxParameterized::TYPE_VEC3:
		{
			physx::PxVec3 d;
			stream >> d;
			childHandle.setParamVec3(d);
			break;
		}
		case NxParameterized::TYPE_F32:
		{
			physx::PxF32 d;
			stream >> d;
			childHandle.setParamF32(d);
			break;
		}
		case NxParameterized::TYPE_U32:
		{
			physx::PxU32 d;
			stream >> d;
			childHandle.setParamU32(d);
			break;
		}
		case NxParameterized::TYPE_BOOL:
		{
			bool d;
			physx::PxU8 value = stream.readByte();
			if (value)
			{
				d = true;
			}
			else
			{
				d = false;
			}

			childHandle.setParamBool(d);
			break;
		}
		default:
			PX_ALWAYS_ASSERT();
		}
	}

}

PX_INLINE void deserialize(physx::PxFileBuf& stream,
                           physx::PxU32 headerVersion,
                           NxParameterized::Interface* param,
                           const char* memberName,
                           NxParameterized::Handle* structHandle)
{
	NxParameterized::Handle childHandle(*param);
	if (structHandle)
	{
		structHandle->getChildHandle(param, memberName, childHandle);
	}
	else
	{
		param->getParameterHandle(memberName, childHandle);
	}

	deserialize(stream, headerVersion, param, childHandle);
}

}
} // end namespace physx::apex

#endif	// __APEXSHAREDSERIALIZATIONHELPERS_H__


text:
@interface EKNKnobFloatEditor () <EKNEventTrampolineKeyHandler>

@property (strong, nonatomic) IBOutlet NSTextField* field;
@property (strong, nonatomic) IBOutlet NSTextField* fieldName;

@end

@implementation EKNKnobFloatEditor

@synthesize delegate = _delegate;
@synthesize info = _info;

- (void)setInfo:(EKNKnobInfo *)info {
    _info = info;
    self.field.floatValue = [info.value floatValue];
    self.fieldName.stringValue = info.label;
}

- (IBAction)textFieldChanged:(id)sender {
    [self valueChangedToFloat:self.field.floatValue];
}

- (void)valueChangedToFloat:(CGFloat)value {
    self.info.value = [NSNumber numberWithFloat:value];
    [self.delegate propertyEditor:self changedKnob:self.info];
}

- (void)incrementByAmount:(CGFloat)amount {
    CGFloat value = self.field.floatValue + amount;
    self.field.floatValue = value;
    [self valueChangedToFloat:value];
}

- (void)keyDown:(NSEvent *)theEvent {
    NSString* character = [theEvent charactersIgnoringModifiers];
    unichar code = [character characterAtIndex:0];
    switch (code) {
        case NSDownArrowFunctionKey:
        case NSLeftArrowFunctionKey:
            [self incrementByAmount:-1];
            break;
        case NSUpArrowFunctionKey:
        case NSRightArrowFunctionKey:
            [self incrementByAmount:1];
            break;
        default:
            break;
    }
}

- (IBAction)stepperPressed:(NSStepper*)stepper {
    [self incrementByAmount:stepper.floatValue];
    stepper.floatValue = 0;
}

@end

redpajama_set_name: RedPajamaGithub


text:
package groovy.util;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by codingbaby on 2017/5/12.
 */
public class DataUtils {

    private static ThreadLocal<Map<String, SimpleDateFormat>> dateFormatMap = new ThreadLocal<Map<String, SimpleDateFormat>>() {
        @Override
        public Map<String, SimpleDateFormat> initialValue() {
            return new HashMap<String, SimpleDateFormat>();
        }
    };

    private static SimpleDateFormat getSimpleDateFormat(String format) {
        Map<String, SimpleDateFormat> map = dateFormatMap.get();
        SimpleDateFormat simpleDateFormat = map.get(format);
        if (simpleDateFormat == null) {
            simpleDateFormat = new SimpleDateFormat(format);
            map.put(format, simpleDateFormat);
        }
        return simpleDateFormat;
    }

    public static String format(Date date, String format) {
        if (date == null)
            return "";
        return getSimpleDateFormat(format).format(date);
    }

}


text:
package com.jterm.katie.tictactoe;

import java.util.ArrayList;
import java.util.Collection;

public class User {
    private String username;
    private String email;
    private int wins;
    private ArrayList<String> games;

    public User() {
    }

    public User(String username, String email) {
        this.username = username;
        this.email = email;
        wins = 0;
        games = new ArrayList<>();
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getEmail() {
        return email;
    }

    public int getWins() {
        return wins;
    }

    public void setWins(int wins) {
        this.wins = wins;
    }

    public ArrayList<String> getGames() {
        return games;
    }

    public void setGames(ArrayList<String> currentGames) {
        this.games = currentGames;
    }
}


text:
/* global $, BoardModel,parseUrl,BoardView */
$(function () {

    var params = parseUrl(document.location.search);
    var boardModel = new BoardModel({
        playersCount: +(window.playersCount || params.playersCount || 0),
        botsCount: +(window.botsCount || params.botsCount || 0),
        roomId: window.roomId,
        playerId: window.playerId
    });
    new BoardView({
        model: boardModel
    });
});


text:
package com.harreke.easyapp.controllerlayout;

import android.content.Context;
import android.graphics.Rect;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;

import com.harreke.easyapp.animator.viewanimator.ViewAnimator;
import com.harreke.easyapp.injection.Injection;

/**
 由Harreke于2015/9/10创建
 */
public abstract class ControllerWidget implements IControllerWidget {
    private ViewAnimator mAnimator;
    private AppearanceAnimation mAppearanceAnimation = AppearanceAnimation.Slide;
    /**
     是否自动响应显示/隐藏

     注:自动响应显示/隐藏的意思为接受并执行ControllerLayout的全局命令{@link ControllerLayout#show(boolean)}或{@link ControllerLayout#hide(boolean)}

     若允许自动相应,ControllerLayout广播{@link ControllerLayout#hide(boolean)}命令时,该控件会自动执行显示/隐藏操作
     若禁止自动响应,则则必须由代码调用该控件的{@link #show(boolean)}或{@link #hide(boolean)}来手动显示/隐藏
     */
    private AutoResponse mAutoResponse = AutoResponse.Show_Hide;
    private ControllerLayout mContainer = null;
    private boolean mEnabled = true;
    /**
     是否在全屏模式下显示
     */
    private FullScreenResponse mFullScreenResponse = FullScreenResponse.FullScreen;
    private int mGravity;
    /**
     是否响应屏幕锁定
     */
    private LockResponse mLockResponse = LockResponse.Unlock;
    private Rect mMarginRect = new Rect();
    private Rect mPaddingFixRect = new Rect(0, 0, 0, 0);
    private boolean mShowing = true;
    /**
     控制控件的视图
     */
    private View mView;
    private Runnable mMeasureRunnable = new Runnable() {
        @Override
        public void run() {
            onPrepared();
        }
    };

    public ControllerWidget(@NonNull ControllerLayout controllerLayout, int layoutId) {
        FrameLayout.LayoutParams params;

        mView = LayoutInflater.from(controllerLayout.getContext()).inflate(layoutId, controllerLayout, false);
        Injection.inject(this, mView);
        params = (FrameLayout.LayoutParams) mView.getLayoutParams();
        mGravity = params.gravity;
        mMarginRect.set(params.leftMargin, params.topMargin, params.rightMargin, params.bottomMargin);
        mView.setVisibility(View.INVISIBLE);
        mAnimator = ViewAnimator.animate(mView);
    }

    public final void fixPadding(int left, int top, int right, int bottom) {
        mPaddingFixRect.set(left, top, right, bottom);
    }

    public final void fixPaddingBottom(int bottom) {
        mPaddingFixRect.bottom = bottom;
    }

    public final void fixPaddingLeft(int left) {
        mPaddingFixRect.left = left;
    }

    public final void fixPaddingRight(int right) {
        mPaddingFixRect.right = right;
    }

    public final void fixPaddingTop(int top) {
        mPaddingFixRect.top = top;
    }

    @Override
    public final ViewAnimator getAnimator() {
        return mAnimator;
    }

    @NonNull
    @Override
    public final AppearanceAnimation getAppearanceAnimation() {
        return mAppearanceAnimation;
    }

    @NonNull
    @Override
    public final AutoResponse getAutoResponse() {
        return mAutoResponse;
    }

    @Nullable
    @Override
    public ControllerLayout getContainer() {
        return mContainer;
    }

    public final Context getContext() {
        return mView.getContext();
    }

    @NonNull
    @Override
    public final FullScreenResponse getFullScreenResponse() {
        return mFullScreenResponse;
    }

    @NonNull
    @Override
    public final LockResponse getLockResponse() {
        return mLockResponse;
    }

    @NonNull
    @Override
    public View getView() {
        return mView;
    }

    @Override
    public void hide(boolean animate) {
        if (mEnabled) {
            if (mContainer != null) {
                mShowing = false;
                onShowStatusChanged(false);
                setAnimator();
                mAnimator.reverse(animate);
            }
        }
    }

    @Override
    public final boolean isEnabled() {
        return mEnabled;
    }

    @Override
    public final boolean isShowing() {
        return mShowing;
    }

    @Override
    public void onAttached() {
        mContainer = (ControllerLayout) mView.getParent();
        mView.removeCallbacks(mMeasureRunnable);
        mView.post(mMeasureRunnable);
    }

    @Override
    public void onDetached() {
        mContainer = null;
        mView.removeCallbacks(mMeasureRunnable);
    }

    @Override
    public void onPrepared() {
        hide(false);
    }

    @Override
    public void onShowStatusChanged(boolean isShowing) {
    }

    private void setAnimator() {
        int viewWidth = mView.getMeasuredWidth();
        int viewHeight = mView.getMeasuredHeight();
        int containerWidth = mContainer.getMeasuredWidth();
        int containerHeight = mContainer.getMeasuredHeight();
        int horizontalGravity = mGravity & Gravity.HORIZONTAL_GRAVITY_MASK;
        int verticalGravity = mGravity & Gravity.VERTICAL_GRAVITY_MASK;

        mAnimator.clear();
        switch (mAppearanceAnimation) {
            case Alpha:
                mAnimator.alphaStart(0f).alphaEnd(1f);
                break;
            case Slide:
                if (horizontalGravity == Gravity.CENTER && verticalGravity == Gravity.CENTER) {
                    mAnimator.yStart(-viewHeight).yEnd(mMarginRect.top + mPaddingFixRect.top + (containerHeight - viewHeight) / 2);
                } else if (horizontalGravity == Gravity.NO_GRAVITY || horizontalGravity == Gravity.LEFT) {
                    mAnimator.xStart(-viewWidth).xEnd(mMarginRect.left + mPaddingFixRect.left);
                } else if (horizontalGravity == Gravity.RIGHT) {
                    mAnimator.xStart(containerWidth).xEnd(containerWidth - mMarginRect.right - mPaddingFixRect.right - viewWidth);
                } else if (verticalGravity == Gravity.NO_GRAVITY || verticalGravity == Gravity.TOP) {
                    mAnimator.yStart(-viewHeight).yEnd(mMarginRect.top + mPaddingFixRect.top);
                } else if (verticalGravity == Gravity.BOTTOM) {
                    mAnimator.yStart(containerHeight).yEnd(containerHeight - mMarginRect.bottom - mPaddingFixRect.bottom - viewHeight);
                }
                break;
        }
        mAnimator.visibilityStart(View.VISIBLE).visibilityReverseEnd(View.INVISIBLE);
    }

    public final void setAppearanceAnimation(@NonNull AppearanceAnimation appearanceAnimation) {
        mAppearanceAnimation = appearanceAnimation;
    }

    public final void setAutoResponse(@NonNull AutoResponse autoResponse) {
        mAutoResponse = autoResponse;
    }

    @Override
    public final void setEnabled(boolean enabled) {
        mEnabled = enabled;
    }

    public final void setFullScreenResponse(@NonNull FullScreenResponse fullScreenResponse) {
        mFullScreenResponse = fullScreenResponse;
    }

    public final void setLockResponse(@NonNull LockResponse lockResponse) {
        mLockResponse = lockResponse;
    }

    @Override
    public void show(boolean animate) {
        if (mEnabled) {
            if (mContainer != null) {
                mShowing = true;
                onShowStatusChanged(true);
                setAnimator();
                mAnimator.start(animate);
            }
        }
    }
}


text:
char** getLines(FILE* file) {
    int lines_to_allocate = 64;
    int line_size_to_allocate = 100;

    if (file==NULL) {
        fileError();
    }

    char** lines = (char**)malloc(sizeof(char*)*lines_to_allocate);
    if (lines==NULL) {
        memError();
    }

    int i;
    for (i = 0; 1; i++) {
        //do we need to allocate more lines?
        if (i >= lines_to_allocate) {
            lines_to_allocate = lines_to_allocate * 2;
            lines = (char**)realloc(lines,sizeof(char*)*lines_to_allocate);
            if (lines==NULL) {
                memError();
            }
        }

        //allocate line, and make sure we succeed
        lines[i] = malloc(line_size_to_allocate);
        if (lines[i]==NULL) {
            memError();
        }

        //break if done
        if (fgets(lines[i],line_size_to_allocate-1,file)==NULL) {
            break;
        }

        //remove newline
        int j;
        for (j = strlen(lines[i])-1; j >= 0 && (lines[i][j] == '\n' || lines[i][j] == '\r'); j--) {;}
        lines[i][j+1]='\0';
    }
    contentLines = i+1;

    //Set line after last to null for future loop terminations
    lines[contentLines] = NULL;

    return lines;
}

void importContent(char* path) {
    FILE* file;
    char** lines;
    Dir* root = NULL;

    printf("%s %s\n","Loading content from:",path);

    if (access(path, R_OK) == -1) {
        printf("\tNo content file exists, showing error.\n");
        startDir = newDirFromDecl("Nothing to show");
        return;
    }

    file = fopen(path,"r"); //add errorhandling here, missing folders give segfault
    lines = getLines(file);
    fclose(file);

    Dir* currDir = NULL;
    for (int i = 0; lines[i] != NULL; i++) {
        if (lines[i][0] == '#') {//it's a comment, do not consider following possibilities
        }

        else if (isActRef(lines[i])) {
            Act* act = newActFromRef(lines[i],currDir);
            addAct(act);
        }

        else if (isDirDecl(lines[i])) {
            Dir* dir = newDirFromDecl(lines[i]);
            dir = addDir(dir); //dir might be replaced with an already existing dir
            currDir = dir;
            if(root==NULL) {
                root = dir;
            }
        }

        else if (isDirRef(lines[i])) {
            Dir* dir = newDirFromRef(lines[i],currDir);
            addDir(dir);
        }

        free(lines[i]);
    }
    free(lines);

    printf("\tLoaded %i directories\n\tLoaded %i actions\n",savedDirs, savedActs);

	startDir = root;
}

int startsWithString(const char* check, const char* string) {
    int cLen = strlen(check);
    int sLen = strlen(string);
    if (cLen >= sLen) {
        return (strncmp(check,string,sLen))?0:1;
    } else {
        return 0;
    }
}

void assignConfigString(char** target, const char* source, const char* filter) {
    int sizeSource = strlen(source);
    int sizeFilter = strlen(filter);
    int sizeNew = sizeSource-sizeFilter;

    *target = (char*)malloc(sizeNew*sizeof(char));
    memcpy(*target,source+sizeFilter,sizeNew);
    (*target)[sizeNew] = '\0';
}

void assignConfigChar(char* target, const char* source, const char* filter) {
    int sizeFilter = strlen(filter);

    *target = source[sizeFilter];
}

void assignConfigInt(int* target, const char* source, const char* filter) {
    int sizeFilter = strlen(filter);

    *target = (int)strtol(source+sizeFilter,NULL,10);
}

void assignConfigHex(int* target, const char* source, const char* filter) {
    int sizeFilter = strlen(filter);

    *target = (int)strtol(source+sizeFilter,NULL,16);
}

void assignConfigBool(int* target, const char* source, const char* filter) {
    int sizeFilter = strlen(filter);

    *target = ((int)strtol(source+sizeFilter,NULL,10))?1:0;
}

void assignConfigXPos(xPos_enum_t* target, const char* source, const char* filter) {
    int sizeFilter = strlen(filter);

    switch(source[sizeFilter]) {
        case ('r'): *target=XRight; break;
        case ('m'): *target=XMid; break;
        case ('l'): *target=XLeft; break;
    }
}

void assignConfigYPos(yPos_enum_t* target, const char* source, const char* filter) {
    int sizeFilter = strlen(filter);

    switch(source[sizeFilter]) {
        case ('t'): *target=YTop; break;
        case ('m'): *target=YMid; break;
        case ('b'): *target=YBot; break;
    }
}

void importConfig(char* path) {
    FILE* file;
    char** lines;

    printf("%s %s\n","Loading config from:",path);

    if (access(path, R_OK) == -1) {
        printf("\tNo config file exists, using defaults.\n");
        return;
    }

    file = fopen(path,"r");
    lines = getLines(file);
    fclose(file);

    //config variables we accept
    static const char* fontString                = "font=";
    static const char* dirUpString               = "directoryUpKey=";
    static const char* actionIndicatorString     = "actionIndicator=";
    static const char* directoryIndicatorString  = "directoryIndicator=";
    static const char* startDirectoryString      = "startDirectory=";
    static const char* windowWidthString         = "windowWidth=";
    static const char* showKeyAsUpperString      = "showKeyAsUpper=";
    static const char* showMenuNamesString       = "showMenuNames=";
    static const char* showMenuNamesNestedString = "showMenuNamesNested=";
    static const char* foregroundColorString     = "foregroundColor=";
    static const char* backgroundColorString     = "backgroundColor=";
    static const char* topIndentString           = "topIndentation=";
    static const char* leftIndentString          = "leftIndentation=";
    static const char* bottomIndentString        = "bottomIndentation=";
    static const char* windowXOffsetString       = "windowXOffset=";
    static const char* windowYOffsetString       = "windowYOffset=";
    static const char* windowXPosString          = "windowXPosition=";
    static const char* windowYPosString          = "windowYPosition=";

    for (int i = 0; lines[i] != NULL; i++) {
        if (startsWithString(lines[i],fontString)) {
            assignConfigString(&(arguments.font),lines[i],fontString);
            printf("\tLoaded %.*s as: %s\n",(int)strlen(fontString)-1,fontString,arguments.font);
        }
        else if (startsWithString(lines[i],dirUpString)) {
            assignConfigChar(&(arguments.dirUpKey),lines[i],dirUpString);
            printf("\tLoaded %.*s as: %c\n",(int)strlen(dirUpString)-1,dirUpString,arguments.dirUpKey);

        }
        else if (startsWithString(lines[i],actionIndicatorString)) {
            assignConfigChar(&(arguments.actS),lines[i],actionIndicatorString);
            printf("\tLoaded %.*s as: %c\n",(int)strlen(actionIndicatorString)-1,actionIndicatorString,arguments.actS);

        }
        else if (startsWithString(lines[i],directoryIndicatorString)) {
            assignConfigChar(&(arguments.dirS),lines[i],directoryIndicatorString);
            printf("\tLoaded %.*s as: %c\n",(int)strlen(directoryIndicatorString)-1,directoryIndicatorString,arguments.dirS);
        }
        else if (startsWithString(lines[i],startDirectoryString)) {
            assignConfigString(&(arguments.startDir),lines[i],startDirectoryString);
            printf("\tLoaded %.*s as: %s\n",(int)strlen(startDirectoryString)-1,startDirectoryString,arguments.startDir);
        }
        else if (startsWithString(lines[i],windowWidthString)) {
            assignConfigInt(&(arguments.windowWidth),lines[i],windowWidthString);
            printf("\tLoaded %.*s as: %i\n",(int)strlen(windowWidthString)-1,windowWidthString,arguments.windowWidth);
        }
        else if (startsWithString(lines[i],showKeyAsUpperString)) {
            assignConfigBool(&(arguments.keyAsUpper),lines[i],showKeyAsUpperString);
            printf("\tLoaded %.*s as: %i\n",(int)strlen(showKeyAsUpperString)-1,showKeyAsUpperString,arguments.keyAsUpper);
        }
        else if (startsWithString(lines[i],showMenuNamesString)) {
            assignConfigBool(&(arguments.showMenuNames),lines[i],showMenuNamesString);
            printf("\tLoaded %.*s as: %i\n",(int)strlen(showMenuNamesString)-1,showMenuNamesString,arguments.showMenuNames);
        }
        else if (startsWithString(lines[i],showMenuNamesNestedString)) {
            assignConfigBool(&(arguments.showMenuNamesNested),lines[i],showMenuNamesNestedString);
            printf("\tLoaded %.*s as: %i\n",(int)strlen(showMenuNamesNestedString)-1,showMenuNamesNestedString,arguments.showMenuNamesNested);
        }
        else if (startsWithString(lines[i],foregroundColorString)) {
            assignConfigHex(&(arguments.fgColor),lines[i],foregroundColorString);
            printf("\tLoaded %.*s as: 0x%6.x\n",(int)strlen(foregroundColorString)-1,foregroundColorString,arguments.fgColor);
        }
        else if (startsWithString(lines[i],backgroundColorString)) {
            assignConfigHex(&(arguments.bgColor),lines[i],backgroundColorString);
            printf("\tLoaded %.*s as: 0x%6.x\n",(int)strlen(backgroundColorString)-1,backgroundColorString,arguments.bgColor);
        }
        else if (startsWithString(lines[i],topIndentString)) {
            assignConfigInt(&(arguments.topIndent),lines[i],topIndentString);
            printf("\tLoaded %.*s as: %i\n",(int)strlen(topIndentString)-1,topIndentString,arguments.topIndent);
        }
        else if (startsWithString(lines[i],leftIndentString)) {
            assignConfigInt(&(arguments.leftIndent),lines[i],leftIndentString);
            printf("\tLoaded %.*s as: %i\n",(int)strlen(leftIndentString)-1,leftIndentString,arguments.leftIndent);
        }
        else if (startsWithString(lines[i],bottomIndentString)) {
            assignConfigInt(&(arguments.botIndent),lines[i],bottomIndentString);
            printf("\tLoaded %.*s as: %i\n",(int)strlen(bottomIndentString)-1,bottomIndentString,arguments.botIndent);
        }
        else if (startsWithString(lines[i],windowXOffsetString)) {
            assignConfigInt(&(arguments.winXOffset),lines[i],windowXOffsetString);
            printf("\tLoaded %.*s as: %i\n",(int)strlen(windowXOffsetString)-1,windowXOffsetString,arguments.winXOffset);
        }
        else if (startsWithString(lines[i],windowYOffsetString)) {
            assignConfigInt(&(arguments.winYOffset),lines[i],windowYOffsetString);
            printf("\tLoaded %.*s as: %i\n",(int)strlen(windowYOffsetString)-1,windowYOffsetString,arguments.winYOffset);
        }
        else if (startsWithString(lines[i],windowXPosString)) {
            assignConfigXPos(&(arguments.winXPos),lines[i],windowXPosString);
            printf("\tLoaded %.*s as: %i\n",(int)strlen(windowXPosString)-1,windowXPosString,arguments.winXPos);
        }
        else if (startsWithString(lines[i],windowYPosString)) {
            assignConfigYPos(&(arguments.winYPos),lines[i],windowYPosString);
            printf("\tLoaded %.*s as: %i\n",(int)strlen(windowYPosString)-1,windowYPosString,arguments.winYPos);
        }

        free(lines[i]);
    }
    free(lines);
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<launch4jConfig>
  <dontWrapJar>false</dontWrapJar>
  <headerType>gui</headerType>
  <jar>F:\GitRepo\CSDNBlogDownloader\CSDNBlogDownloader\jar\CSDNBlogDownloaderV2.0.jar</jar>
  <outfile>F:\GitRepo\CSDNBlogDownloader\CSDNBlogDownloader\exe\CSDNBlogDownloaderV2.0.exe</outfile>
  <errTitle></errTitle>
  <cmdLine></cmdLine>
  <chdir>.</chdir>
  <priority>normal</priority>
  <downloadUrl>http://java.com/download</downloadUrl>
  <supportUrl></supportUrl>
  <stayAlive>false</stayAlive>
  <restartOnCrash>false</restartOnCrash>
  <manifest></manifest>
  <icon>C:\Users\user\Pictures\icon.ico</icon>
  <jre>
    <path></path>
    <bundledJre64Bit>false</bundledJre64Bit>
    <bundledJreAsFallback>false</bundledJreAsFallback>
    <minVersion>1.6.0</minVersion>
    <maxVersion></maxVersion>
    <jdkPreference>preferJre</jdkPreference>
    <runtimeBits>64/32</runtimeBits>
  </jre>
  <versionInfo>
    <fileVersion>2.0.0.0</fileVersion>
    <txtFileVersion>Geurney</txtFileVersion>
    <fileDescription>CSDN Blog Downloader</fileDescription>
    <copyright>Geurney</copyright>
    <productVersion>2.0.0.0</productVersion>
    <txtProductVersion>Geurney</txtProductVersion>
    <productName>CSDN Blog Downloader</productName>
    <companyName>Geurney</companyName>
    <internalName>CSDN Blog Downloader</internalName>
    <originalFilename>CSDNBlogDownloader.exe</originalFilename>
  </versionInfo>
</launch4jConfig>


text:
/**
 * Navigate forwards in the browser history, if possible.
 *
 * @see https://code.google.com/p/selenium/wiki/JsonWireProtocol#/session/:sessionId/forward
 * @type protocol
 *
 */

module.exports = function forward () {

    if(this.desiredCapabilities.browserName === 'safari') {

        /*!
         * helper for safaridriver which doesn not support forward
         * Reason: "Yikes! Safari history navigation does not work. We can go forward or back,
         * but once we do, we can no longer communicate with the page"
         */
        return this.execute('history.go(+1)').waitForExist('body', 5000);

    } else {

        var requestOptions = {
            path: '/session/:sessionId/forward',
            method: 'POST'
        };

        return this.requestHandler.create(requestOptions);

    }
};


text:
module Mongo
  class Cluster
    module Topology

      # Defines behavior for when a cluster is in sharded topology.
      #
      # @since 2.0.0
      class Sharded < Base
        include NoReplicaSetOptions

        # The display name for the topology.
        #
        # @since 2.0.0
        NAME = 'Sharded'.freeze

        # Get the display name.
        #
        # @example Get the display name.
        #   Sharded.display_name
        #
        # @return [ String ] The display name.
        #
        # @since 2.0.0
        def display_name
          self.class.name.gsub(/.*::/, '')
        end

        # @note This method is experimental and subject to change.
        #
        # @api experimental
        # @since 2.7.0
        def summary
          details = server_descriptions.keys.join(',')
          "#{display_name}[#{details}]"
        end

        # Determine if the topology would select a readable server for the
        # provided candidates and read preference.
        #
        # @example Is a readable server present?
        #   topology.has_readable_server?(cluster, server_selector)
        #
        # @param [ Cluster ] cluster The cluster.
        # @param [ ServerSelector ] server_selector The server
        #   selector.
        #
        # @return [ true ] A Sharded cluster always has a readable server.
        #
        # @since 2.4.0
        def has_readable_server?(cluster, server_selector = nil); true; end

        # Determine if the topology would select a writable server for the
        # provided candidates.
        #
        # @example Is a writable server present?
        #   topology.has_writable_server?(servers)
        #
        # @param [ Cluster ] cluster The cluster.
        #
        # @return [ true ] A Sharded cluster always has a writable server.
        #
        # @since 2.4.0
        def has_writable_server?(cluster); true; end

        # A sharded topology is not a replica set.
        #
        # @example Is the topology a replica set?
        #   Sharded.replica_set?
        #
        # @return [ false ] Always false.
        #
        # @since 2.0.0
        def replica_set?; false; end

        # Select appropriate servers for this topology.
        #
        # @example Select the servers.
        #   Sharded.servers(servers)
        #
        # @param [ Array<Server> ] servers The known servers.
        #
        # @return [ Array<Server> ] The mongos servers.
        #
        # @since 2.0.0
        def servers(servers)
          servers.select{ |server| server.mongos? }
        end

        # A sharded topology is sharded.
        #
        # @example Is the topology sharded?
        #   Sharded.sharded?
        #
        # @return [ true ] Always true.
        #
        # @since 2.0.0
        def sharded?; true; end

        # A sharded topology is not single.
        #
        # @example Is the topology single?
        #   Sharded.single?
        #
        # @return [ false ] Always false.
        #
        # @since 2.0.0
        def single?; false; end

        # A sharded topology is not unknown.
        #
        # @example Is the topology unknown?
        #   Sharded.unknown?
        #
        # @return [ false ] Always false.
        #
        # @since 2.0.0
        def unknown?; false; end
      end
    end
  end
end


text:
package org.osiam.resources.provisioning.update;

import java.util.List;
import java.util.Set;

import org.osiam.resources.converter.X509CertificateConverter;
import org.osiam.resources.scim.X509Certificate;
import org.osiam.storage.entities.UserEntity;
import org.osiam.storage.entities.X509CertificateEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.common.base.Strings;

/**
 * The X509CertificateUpdater provides the functionality to update the {@link X509CertificateEntity} of a UserEntity
 */
@Service
class X509CertificateUpdater {

    @Autowired
    private X509CertificateConverter x509CertificateConverter;

    /**
     * updates (adds new, delete, updates) the {@link X509CertificateEntity}'s of the given {@link UserEntity} based on
     * the given List of X509Certificate's
     *
     * @param x509Certificates
     *            list of X509Certificate's to be deleted, updated or added
     * @param userEntity
     *            user who needs to be updated
     * @param attributes
     *            all {@link X509CertificateEntity}'s will be deleted if this Set contains 'x509Certificates'
     */
    void update(List<X509Certificate> x509Certificates, UserEntity userEntity, Set<String> attributes) {

        if (attributes.contains("x509Certificates")) {
            userEntity.removeAllX509Certificates();
        }

        if (x509Certificates != null) {
            for (X509Certificate scimX509Certificate : x509Certificates) {
                X509CertificateEntity x509CertificateEntity = x509CertificateConverter.fromScim(scimX509Certificate);
                userEntity.removeX509Certificate(x509CertificateEntity); // we always have to remove the x509Certificate
                                                                         // the primary attribute has changed
                if (Strings.isNullOrEmpty(scimX509Certificate.getOperation())
                        || !scimX509Certificate.getOperation().equalsIgnoreCase("delete")) {

                    ensureOnlyOnePrimaryX509CertificateExists(x509CertificateEntity, userEntity.getX509Certificates());
                    userEntity.addX509Certificate(x509CertificateEntity);
                }
            }
        }
    }

    /**
     * if the given newX509Certificate is set to primary the primary attribute of all existing x509Certificate's in the
     * {@link UserEntity} will be removed
     *
     * @param newX509Certificate
     *            to be checked if it is primary
     * @param x509Certificates
     *            all existing x509Certificate's of the {@link UserEntity}
     */
    private void ensureOnlyOnePrimaryX509CertificateExists(X509CertificateEntity newX509Certificate,
            Set<X509CertificateEntity> x509Certificates) {
        if (newX509Certificate.isPrimary()) {
            for (X509CertificateEntity exisitngX509CertificateEntity : x509Certificates) {
                if (exisitngX509CertificateEntity.isPrimary()) {
                    exisitngX509CertificateEntity.setPrimary(false);
                }
            }
        }
    }

}


text:
import { Component, OnInit, Input, ViewEncapsulation } from '@angular/core';

@Component({
  selector: 'mv-footer',
  templateUrl: './footer.component.html',
  styleUrls: ['./footer.component.scss'],
  encapsulation: ViewEncapsulation.None,
})
export class FooterComponent implements OnInit {

  @Input() logo: string = '';

  constructor() { }

  ngOnInit() {
  }

}


text:
'use strict'

const deprecate = require('depd')('loopback-ds-computed-mixin')
const computed = require('./computed')

module.exports = function mixin(app) {
  app.loopback.modelBuilder.mixins.define = deprecate.function(app.loopback.modelBuilder.mixins.define,
    'app.modelBuilder.mixins.define: Use mixinSources instead')
  app.loopback.modelBuilder.mixins.define('Computed', computed)
}


text:
<?php

namespace Rareloop\Primer\Test\Twig;

use Mockery;
use PHPUnit\Framework\TestCase;
use Rareloop\Primer\FileSystemPatternProvider;
use Rareloop\Primer\Twig\PrimerLoader;

class PrimerLoaderTest extends TestCase
{
    use \Mockery\Adapter\Phpunit\MockeryPHPUnitIntegration;

    /** @test */
    public function can_test_that_a_template_exists()
    {
        $dataProvider = Mockery::mock(FileSystemPatternProvider::class);
        $dataProvider->shouldReceive('patternExists')->once()->with('components/misc/header')->andReturn(true);
        $loader = new PrimerLoader($dataProvider);

        $this->assertTrue($loader->exists('components/misc/header'));
    }

    /** @test */
    public function can_test_that_a_template_exists_does_not_exist()
    {
        $dataProvider = Mockery::mock(FileSystemPatternProvider::class);
        $dataProvider->shouldReceive('patternExists')->once()->with('components/misc/header')->andReturn(false);
        $loader = new PrimerLoader($dataProvider);

        $this->assertFalse($loader->exists('components/misc/header'));
    }

    /** @test */
    public function can_get_a_consistent_cache_key()
    {
        $dataProvider = Mockery::mock(FileSystemPatternProvider::class);
        $loader = new PrimerLoader($dataProvider);

        $this->assertSame($loader->getCacheKey('components/misc/header'), $loader->getCacheKey('components/misc/header'));
        $this->assertSame($loader->getCacheKey('components/misc/footer'), $loader->getCacheKey('components/misc/footer'));
        $this->assertNotSame($loader->getCacheKey('components/misc/header'), $loader->getCacheKey('components/misc/footer'));
    }

    /** @test */
    public function can_get_source_context()
    {
        $dataProvider = Mockery::mock(FileSystemPatternProvider::class);
        $dataProvider->shouldReceive('getPatternTemplate')->once()->with('components/misc/header')->andReturn('
Hello World
');
        $loader = new PrimerLoader($dataProvider);

        $source = $loader->getSourceContext('components/misc/header');

        $this->assertInstanceOf(\Twig\Source::class, $source);
        $this->assertSame('
Hello World
', $source->getCode());
        $this->assertSame('components/misc/header', $source->getName());
    }

    /** @test */
    public function isFresh_returns_false_if_cache_last_modified_is_later_than_template_last_modified()
    {
        $dataProvider = Mockery::mock(FileSystemPatternProvider::class);
        $dataProvider->shouldReceive('getPatternTemplateLastModified')->once()->with('components/misc/header')->andReturn(100);
        $loader = new PrimerLoader($dataProvider);

        $this->assertFalse($loader->isFresh('components/misc/header', 200));
    }

    /** @test */
    public function isFresh_returns_false_if_cache_last_modified_is_equal_to_template_last_modified()
    {
        $dataProvider = Mockery::mock(FileSystemPatternProvider::class);
        $dataProvider->shouldReceive('getPatternTemplateLastModified')->once()->with('components/misc/header')->andReturn(100);
        $loader = new PrimerLoader($dataProvider);

        $this->assertFalse($loader->isFresh('components/misc/header', 100));
    }

    /** @test */
    public function isFresh_returns_true_if_cache_last_modified_is_earlier_than_template_last_modified()
    {
        $dataProvider = Mockery::mock(FileSystemPatternProvider::class);
        $dataProvider->shouldReceive('getPatternTemplateLastModified')->once()->with('components/misc/header')->andReturn(200);
        $loader = new PrimerLoader($dataProvider);

        $this->assertTrue($loader->isFresh('components/misc/header', 100));
    }
}


text:
#pre-display_stuff *,
#debug_toolbar *
{
    margin: 0;
    padding: 0;
    text-align: left;
    color: black;
    background-color: transparent;
}
#pre-display_stuff
{
    font-size: 10pt !important;
    height: 0;
    width: 0;
    padding: 1ex;
    background-color: black;
    color: black;
    overflow: hidden;
    position: fixed;
    top: 0;
    left: 0;
    z-index: 99999; /* lot's of. */
    opacity: .2;
    -moz-border-radius: 1ex;
    -webkit-border-radius: 1ex;
    border-radius: 1ex;
    text-align: left;
}
#pre-display_stuff a
{
    color: blue !important;;
}
#pre-display_stuff #pre-display_stuff_switcher
{
    top: 0;
    left: 0;
    width: 2ex;
    height: 2ex;
    display: block;
    position: fixed;
    text-align: center;
    line-height: 2ex;
}

#pre-display_stuff.foo
{
    height: 70%;
    width: 90%;
    right: 0;
    left: 0;
    overflow: auto;
    background-color: white;
    opacity : 1;
    /*opacity: .9;*/
    border: silver solid thin;
}

#pre-display_stuff.foo #pre-display_stuff_content
{
    font-family: sans-serif;
    height: 100%;
    overflow: auto;
    margin: 0 1ex;
}

#pre-display_stuff_content .debug-output-block
{
    border-left: #ccc thin solid;
    border-width: 0 0 0 .25em;
    padding-left: 1ex;
    margin: 0 0 1em 0;
}
#pre-display_stuff_content .debug-output-block.extends-PagesController.is-displaying-ctrl
{   border-color: #7E18E3; }
#pre-display_stuff_content .debug-output-block.extends-PagesController.is-displaying-ctrl > h3
{          color: #7E18E3; }
#pre-display_stuff_content .debug-output-block.extends-PagesController,
#pre-display_stuff_content .debug-output-block.extends-Component
{   border-color: #1D1D1D; }
#pre-display_stuff_content .debug-output-block.extends-PagesController > h3,
#pre-display_stuff_content .debug-output-block.extends-Component       > h3
{          color: #1D1D1D; }
#pre-display_stuff_content .debug-output-block.extends-PermanentController
{   border-color: #979797; }
#pre-display_stuff_content .debug-output-block.extends-PermanentController > h3
{          color: #979797; }
#pre-display_stuff_content .debug-output-block.preparing
{   border-style: dotted; }
#pre-display_stuff_content .debug-output-block.launching
{   border-style: solid; }
#pre-display_stuff_content .debug-output-block.ctrl
{   border-left-width: .3em; }
#pre-display_stuff_content .debug-output-block
{   border-left-width: .15em; }
#pre-display_stuff_content .debug-output-block > h1,
#pre-display_stuff_content .debug-output-block > h2,
#pre-display_stuff_content .debug-output-block > h3,
#pre-display_stuff_content .debug-output-block > h4,
#pre-display_stuff_content .debug-output-block > h5,
#pre-display_stuff_content .debug-output-block > h6
{
    color: black;
    margin: 0;
    padding: 0;
    font-weight: bold;
}
#pre-display_stuff_content .debug-output-block > h1 { font-size: 1.3em; }
#pre-display_stuff_content .debug-output-block > h2 { font-size: 1.2em; }
#pre-display_stuff_content .debug-output-block > h3 { font-size: 1.1em; }
#pre-display_stuff_content .debug-output-block > h4 { font-size: 1.0em; }
#pre-display_stuff_content .debug-output-block > h5 { font-size: 0.9em; }
#pre-display_stuff_content .debug-output-block > h6 { font-size: 0.8em; }

#debug_toolbar
{
    font-size: 10pt !important;
    position: relative;
    text-align: left;
}
#debug_toolbar > *,
#debug_toolbar > * > h4
{
    display: inline;
}
#debug_toolbar h4
{
    padding: 0;
    margin: 0;
}
#debug_toolbar *
{
    color: black !important;
    background-color: inherit !important;
}
#debug_toolbar a
{
    color: blue !important;
}
#debug_toolbar dl#debug_info > dl,
#debug_toolbar dl#debug_info > dt,
#debug_toolbar dl#debug_info > dd
{
    padding: 0;
    margin: 0;
}
#debug_toolbar dl#debug_info > dt,
#debug_toolbar dl#debug_info > dd
{
    display: inline;
    font-size: .8em;
}
/*
#debug_toolbar dl#debug_info > dd:after
{
    content: ', ';
}
*/
#debug_toolbar #debug_toolbox
{
    position: absolute;
    top: 0;
    right: 0;
    text-align: right;
    line-height: 1.2em;
    height: 1.2em;
    margin: .2ex;
}
#debug_toolbar #debug_toolbox > h4
{
    height: 1.3em;
    display: inline;
    position: static;
    padding: 0;
    border: none;
    text-align: right;
}
#debug_toolbar #debug_toolbox > *
{
    display: none;
    background-color: #cca;
    border: thin solid #886;
    padding: 1ex;
    list-style: none;
    position: relative;
    top: -.1em; /* to be safe */
    z-index: 999;
}
#debug_toolbar #debug_toolbox:hover > *,
#debug_toolbar #debug_toolbox li > a
{
    display: block;
}

#foot_debug .errors_count
{
    position: fixed;
    z-index: 2147483647; /* I like to be on the top */
    bottom: 0;
    left: 0;
    background-color: white;
    color: black;
    padding: .5em;
    -webkit-border-top-right-radius: .5em;
    -moz-border-radius-topright: .5em;
    border-top-right-radius: .5em;
}
#foot_debug .errors_count dl,
#foot_debug .errors_count dl dt,
#foot_debug .errors_count dl dd
{
    padding: 0;
    margin: 0;
}
#foot_debug .errors_count dl dt,
#foot_debug .errors_count dl dd
{
    display: inline;
}
#foot_debug .errors_count dl dd
{
    padding: 0 1em 0 .5em;
    font-weight: bold;
}


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE194_Unexpected_Sign_Extension__listen_socket_malloc_81.h
Label Definition File: CWE194_Unexpected_Sign_Extension.label.xml
Template File: sources-sink-81.tmpl.h
*/
/*
 * @description
 * CWE: 194 Unexpected Sign Extension
 * BadSource: listen_socket Read data using a listen socket (server side)
 * GoodSource: Positive integer
 * Sinks: malloc
 *    BadSink : Allocate memory using malloc() with the size of data
 * Flow Variant: 81 Data flow: data passed in a parameter to an virtual method called via a reference
 *
 * */

#include "std_testcase.h"

namespace CWE194_Unexpected_Sign_Extension__listen_socket_malloc_81
{

class CWE194_Unexpected_Sign_Extension__listen_socket_malloc_81_base
{
public:
    /* pure virtual function */
    virtual void action(short data) const = 0;
};

#ifndef OMITBAD

class CWE194_Unexpected_Sign_Extension__listen_socket_malloc_81_bad : public CWE194_Unexpected_Sign_Extension__listen_socket_malloc_81_base
{
public:
    void action(short data) const;
};

#endif /* OMITBAD */

#ifndef OMITGOOD

class CWE194_Unexpected_Sign_Extension__listen_socket_malloc_81_goodG2B : public CWE194_Unexpected_Sign_Extension__listen_socket_malloc_81_base
{
public:
    void action(short data) const;
};

#endif /* OMITGOOD */

}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Uses of Package examples.behavior.world</title>
<meta name="date" content="2017-04-26">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Package
examples.behavior.world

Packages that use examples.behavior.world

Package
Description

examples.behavior

examples.behavior.fitness

examples.behavior.world

Classes in examples.behavior.world used by examples.behavior

Class and Description

Orientation

WorldMap

Classes in examples.behavior.world used by examples.behavior.fitness

Class and Description

Field

Orientation

WorldMap

Classes in examples.behavior.world used by examples.behavior.world

Class and Description

Field

Orientation

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
layout: kanji
v4: 1774
v6: 1912
kanji: 舞
keyword: dance
elements: dance, reclining, lying down, tub, sunglasses, dancing legs, ballerina, evening
strokes: 15
image: E8889E
on-yomi: ブ
kun-yomi: ま.う、-ま.う、まい
permalink: /rtk/舞/
prev: 潰
next: 無
---

1) [thegeezer3] 16-6-2007(228): The yakuza boss reclines in the oaken bathtub wearing his shades while his personal harem dances nakes for him.

2) [captal] 15-6-2008(120): I learned nothingness (#1775 無) first because it is a very common kanji. Probably easier to think of this kanji in that context. Attractive dancers should dance wearing nothing but sunglasses.

3) [aircawn] 3-6-2007(18): I imagine this big oaken tub as being full of grapes being squashed by the feet of the vinyard owners. Each wearing sunglasses and doing that Russian arms crossed dance and squishing all the grapes.

4) [spleenlol] 8-6-2010(14): See jump (#1409 踊). Renamed this kanji interpretive dance. (readapated thegeezer3) The yakuza boss reclines in the oaken bathtub wearing his タキ(tacky) sunglasses while his personal harem does an interpretive dance for him.

5) [usis35] 12-5-2012(13): Heisig, let's get this straight: NEW keywords: 曜 JUMP ex-leap (#1285 躍); 踊  DANCE=ODORI ex-jump (#1409 踊); 舞 KABUKI ex-dance (#1774 舞) (used in concepts related to dance, like stages, fluttering, etc.). So, KABUKI 歌舞伎 【かぶき】is the keyword here. STORY: We learn nothingness (#1775 無) first because it is a very common kanji. Then we go to see KABUKI en the EVENING wearing SUNGLASSES.


text:
"""Layer class and subclasses

A `Layer` has as size the whole drawable area (window or screen),
and knows how to draw itself. It can be semi transparent (having holes
and/or partial transparency in some/all places), allowing to see other layers
behind it. Layers are the ones defining appearance and behavior, so most
of your programming time will be spent coding Layer subclasses that do what
you need. The layer is where you define event handlers.
Events are propagated to layers (from front to back) until some layer catches
the event and accepts it.
"""

from __future__ import division, print_function, unicode_literals

__docformat__ = 'restructuredtext'

from cocos.director import *
from cocos import cocosnode
from cocos import scene

__all__ = [ 'Layer', 'MultiplexLayer']

class Layer(cocosnode.CocosNode, scene.EventHandlerMixin):
    """a CocosNode that automatically handles listening to director.window events"""

    #: if True the layer will listen to director.window events
    #: Default: False
    is_event_handler = False #: if true, the event handlers of this layer will be registered. defaults to false.

    def __init__( self ):
        super( Layer, self ).__init__()
        self.scheduled_layer = False
        x,y = director.get_window_size()
        self.transform_anchor_x = x // 2
        self.transform_anchor_y = y // 2

    def push_all_handlers(self):
        """ registers itself to receive director.window events and propagates
            the call to childs that are layers.
            class member is_event_handler must be True for this to work"""
        if self.is_event_handler:
            director.window.push_handlers( self )
        for child in self.get_children():
            if isinstance(child, Layer):
                child.push_all_handlers()

    def remove_all_handlers(self):
        """ de-registers itself to receive director.window events and propagates
            the call to childs that are layers.
            class member is_event_handler must be True for this to work"""
        if self.is_event_handler:
            director.window.remove_handlers( self )
        for child in self.get_children():
            if isinstance(child, Layer):
                child.remove_all_handlers()

    def on_enter(self):
        super(Layer, self).on_enter()

        scn = self.get_ancestor(scene.Scene)
        if not scn: return

        if scn._handlers_enabled:
            if self.is_event_handler:
                director.window.push_handlers( self )

    def on_exit(self):
        super(Layer, self).on_exit()

        scn = self.get_ancestor(scene.Scene)
        if not scn: return

        if scn._handlers_enabled:
            if self.is_event_handler:
                director.window.remove_handlers( self )

#
# MultiplexLayer
class MultiplexLayer( Layer ):
    """A Composite layer that only enables one layer at the time.

     This is useful, for example, when you have 3 or 4 menus, but you want to
     show one at the time"""

    def __init__( self, *layers ):
        super( MultiplexLayer, self ).__init__()

        self.layers = layers
        self.enabled_layer = 0

        self.add( self.layers[ self.enabled_layer ] )

    def switch_to( self, layer_number ):
        """Switches to another Layer that belongs to the Multiplexor.

        :Parameters:
            `layer_number` : Integer
                MUST be a number between 0 and the quantities of layers - 1.
                The running layer will receive an "on_exit()" call, and the
                new layer will receive an "on_enter()" call.
        """
        if layer_number < 0 or layer_number >= len( self.layers ):
            raise Exception("Multiplexlayer: Invalid layer number")

        # remove
        self.remove( self.layers[ self.enabled_layer ] )

        self.enabled_layer = layer_number
        self.add( self.layers[ self.enabled_layer ] )


text:
		    Select Injured Body Part

		John Doe

		Left Arm

		Broken Arm

	    <map name="bodymap" id="bodymap">
		<area alt="leftarm" title="leftarm"   href="/app/#/astronauts/{{ astronautId }}/bodyparts/leftarm/conditions" shape="rect" coords="2,94,219,272" />
		<area alt="rightarm" title="rightarm" href="/app/#/astronauts/{{ astronautId }}/bodyparts/rightarm/conditions" shape="rect" coords="333,95,540,285" />
		<area alt="leftleg" title="leftleg"   href="/app/#/astronauts/{{ astronautId }}/bodyparts/leftleg/conditions" shape="rect" coords="162,285,262,576" />
		<area alt="rightleg" title="rightleg" href="/app/#/astronauts/{{ astronautId }}/bodyparts/rightleg/conditions" shape="rect" coords="273,288,393,578" />
		<area alt="head" title="head"         href="/app/#/astronauts/{{ astronautId }}/bodyparts/head/conditions" shape="rect" coords="229,6,324,279" />
	    </map>


text:
<!doctype html>

    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <link rel="stylesheet" type="text/css" href="styles.css">
    <link href="https://fonts.googleapis.com/css?family=Quicksand" rel="stylesheet">

tab 1

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ex impedit necessitatibus
            omnis
            perspiciatis ut! Quisquam.Lorem ipsum dolor sit amet, consectetur adipisicing elit. Adipisci asperiores
            beatae
            delectus doloribus error fugiat illum iure nemo nesciunt quae quam repellat, repudiandae sint totam vel
            velit
            voluptas voluptates voluptatibus!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aliquid
            blanditiis
            commodi facilis nesciunt
            perferendis possimus reiciendis saepe sint vel velit! At error facilis molestias reprehenderit.

tab 2

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ad porro, praesentium? Aliquid amet beatae
            consequatur cumque, dolorem dolores ea exercitationem expedita fuga fugiat id illum ipsam maiores minima nam
            nobis non numquam perferendis perspiciatis quasi quo quos recusandae repellat, repellendus sapiente tempora
            veniam voluptatem. Repudiandae.Lorem ipsum dolor sit amet, consectetur adipisicing elit. Distinctio iure
            numquam
            provident, qui quia vel.Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aliquid blanditiis commodi
            facilis nesciunt
            perferendis possimus reiciendis saepe sint vel velit! At error facilis molestias reprehenderit.

tab 3

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Commodi ea esse eum fugit incidunt iste
            libero
            porro! Beatae cum rem similique temporibus vitae voluptas! Animi commodi consequuntur deserunt dolor
            eligendi
            id, necessitatibus rem repellendus reprehenderit!Lorem ipsum dolor sit amet, consectetur adipisicing elit.
            Ad
            distinctio ea excepturi hic maiores obcaecati omnis quia quibusdam quidem. Accusantium?Lorem ipsum dolor sit
            amet, consectetur adipisicing elit. Aliquid blanditiis commodi facilis nesciunt
            perferendis possimus reiciendis saepe sint vel velit! At error facilis molestias reprehenderit.


text:
class OldExam < ActiveRecord::Base
  belongs_to :old_folder

  validates :old_folder_id, presence: true
  validates :date, presence: true
  validates :title, presence: true
  validates :examiners, presence: true

  def self.search(search)
    if search.nil? || search.empty?
      joins(:old_folder)
          .order('old_folders.title ASC')
    else
      wild_card_search = "%#{search}%".gsub(' ', '%')
      prefix_search = "#{search}%"

      joins(:old_folder)
          .where('date LIKE ? OR old_exams.title LIKE ? OR old_exams.examiners LIKE ? OR old_folders.title LIKE ? ',
                 prefix_search, wild_card_search, wild_card_search, wild_card_search)
          .order('old_folders.title ASC')
    end
  end

  def self.existing_titles
    get_unique_field_values(:title)
  end

  def self.existing_examiners
    get_unique_field_values(:examiners)
  end

  def self.get_unique_field_values(symbol)
    select(symbol)
        .order(symbol)
        .map(&symbol)
        .uniq
  end

end


text:
package net.lipoyang.koshibridge;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.bluetooth.BluetoothGattCharacteristic;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.util.Log;
import android.os.Handler;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.util.Enumeration;

import com.uxxu.konashi.lib.Konashi;
import com.uxxu.konashi.lib.KonashiListener;
import com.uxxu.konashi.lib.KonashiManager;
import org.jdeferred.DoneCallback;
import org.jdeferred.FailCallback;
import info.izumin.android.bletia.BletiaException;

public class KoshiServerUI extends Activity implements Runnable, View.OnClickListener {

    // Konashi
    private KonashiManager mKonashiManager;
    // Bluetooth state
    public static final int STATE_DISCONNECTED = 0;
    public static final int STATE_CONNECTING = 1;
    public static final int STATE_CONNECTED = 2;
    private int btState = STATE_DISCONNECTED;

    // Widgets
    private Button buttonBleSearch;
    private Button buttonServerUpdate;
    private TextView textKoshianDev;
    private TextView textServerIp1;
    private TextView textServerIp2;
    private TextView textClientIp;
    private EditText editPortNum;

    // Debugging
    private static final String TAG = "KoshiBridge";
    private static final boolean DEBUGGING = true;
    private final KoshiServerUI self = this;

    // IP
    private static final int DEFAULT_PORT_NUM = 5678;
    private int portNum;
    private ServerSocket mServer;
    private Socket mClient;
    private BufferedReader reader;
    private BufferedWriter writer;
    int port = 8080;
    volatile Thread runner = null;
    Handler mHandler = new Handler();
    private boolean toQuit;
    private boolean toUpdate;
    private boolean isOpen;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_koshi_server_ui);
        if(DEBUGGING) Log.e(TAG, "++ ON CREATE ++");

        // Widgets
        buttonBleSearch = (Button)findViewById(R.id.buttonBleSearch);
        buttonServerUpdate = (Button)findViewById(R.id.buttonServerUpdate);
        buttonBleSearch.setOnClickListener(this);
        buttonServerUpdate.setOnClickListener(this);
        textKoshianDev = (TextView)findViewById(R.id.textKoshianDev);
        textServerIp1 = (TextView)findViewById(R.id.textServerIp1);
        textServerIp2 = (TextView)findViewById(R.id.textServerIp2);
        textClientIp = (TextView)findViewById(R.id.textClientIp);
        editPortNum = (EditText)findViewById(R.id.editPortNum);

        // Konashi
        mKonashiManager = new KonashiManager(getApplicationContext());

        // IP
        portNum = DEFAULT_PORT_NUM;
        editPortNum.setText(String.valueOf(portNum));
    }
    @Override
    public void onStart() {
        super.onStart();
        if(DEBUGGING) Log.e(TAG, "++ ON START ++");
    }
    @Override
    public synchronized void onResume() {
        super.onResume();
        if(DEBUGGING) Log.e(TAG, "+ ON RESUME +");

        // Konashi
        mKonashiManager.addListener(mKonashiListener);
        btState = mKonashiManager.isReady() ? STATE_CONNECTED : STATE_DISCONNECTED;
        viewBleConnection();

        // IP
        String[] ip = getIPAddress();
        textServerIp1.setText(ip[0]);
        textServerIp2.setText(ip[1]);
        //textServerIp1.setText(getIPAddress());
        toQuit = false;
        toUpdate = false;
        isOpen = false;
        //if(runner == null){
            runner = new Thread(this);
        //}
        runner.start();

        // Permittion
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestLocationPermission();
        }
    }
    @Override
    public synchronized void onPause() {
        // Konashi
        mKonashiManager.removeListener(mKonashiListener);

        // IP
        toQuit = true;

        super.onPause();
        if(DEBUGGING) Log.e(TAG, "- ON PAUSE -");
    }
    @Override
    public void onStop() {
        super.onStop();
        if(DEBUGGING) Log.e(TAG, "-- ON STOP --");
    }
    @Override
    public void onDestroy() {
        // Konashi
        new Thread(new Runnable() {
            @Override
            public void run() {
                if(mKonashiManager.isConnected()){
                    mKonashiManager.reset()
                            .then(new DoneCallback<BluetoothGattCharacteristic>() {
                                @Override
                                public void onDone(BluetoothGattCharacteristic result) {
                                    mKonashiManager.disconnect();
                                }
                            });
                }
            }
        }).start();
        super.onDestroy();
        if(DEBUGGING) Log.e(TAG, "--- ON DESTROY ---");
    }

    /**
     * Konashi's Event Listener
     */
    private final KonashiListener mKonashiListener = new KonashiListener() {
        @Override
        public void onConnect(KonashiManager manager) {
            // Connected!
            btState = STATE_CONNECTED;
            viewBleConnection();

            mKonashiManager.uartMode(Konashi.UART_ENABLE)
                    .then(new DoneCallback<BluetoothGattCharacteristic>() {
                        @Override
                        public void onDone(BluetoothGattCharacteristic result) {
                            mKonashiManager.uartBaudrate(Konashi.UART_RATE_38K4);

                            if(isOpen){
                                try{
                                    writer.write("onConnect ");
                                    writer.write(mKonashiManager.getPeripheralName());
                                    writer.newLine();
                                    writer.flush();
                                }
                                catch(IOException ex){
                                    ;
                                }
                            }
                        }
                    })
                    .fail(new FailCallback<BletiaException>() {
                        @Override
                        public void onFail(BletiaException result) {
                            Toast.makeText(self, result.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    });
        }
        @Override
        public void onDisconnect(KonashiManager manager) {
            // Disconnected!
            btState = STATE_DISCONNECTED;
            viewBleConnection();

            if(isOpen){
                try{
                    writer.write("onDisconnect");
                    writer.newLine();
                    writer.flush();
                }
                catch(IOException ex){
                    ;
                }
            }
        }
        @Override
        public void onError(KonashiManager manager, BletiaException e) {

        }
        @Override
        public void onUpdatePioOutput(KonashiManager manager, int value) {

        }
        @Override
        public void onUpdateUartRx(KonashiManager manager, byte[] value) {
            if(isOpen){
                try{
                    writer.write("onUpdateUartRx ");
                    writer.write(new String(value));
                    writer.newLine();
                    writer.flush();
                }
                catch(IOException ex){
                    ;
                }
            }
        }
        @Override
        public void onUpdateBatteryLevel(KonashiManager manager, int level) {

        }
        @Override
        public void onUpdateSpiMiso(KonashiManager manager, byte[] data){

        }
    };

    // This is just a last resort. Versiion 2 SDK has no onCancelKonashi
    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        if(hasFocus){
            Log.e(TAG, "onWindowFocusChanged [true]");
            String pName = mKonashiManager.getPeripheralName();
            Log.e(TAG, "pName = [" + pName + "]");

            if(btState == STATE_CONNECTING){
                if(mKonashiManager.getPeripheralName().equals("")){
                    btState = STATE_DISCONNECTED;
                    viewBleConnection();
                }
            }
        }
    }

    // On Clidk BUttons
    @Override
    public void onClick(View v) {
        // [BLE Device Search]
        if (v.getId() == R.id.buttonBleSearch) {
            // Connecting
            if(!mKonashiManager.isReady()){
                btState = STATE_CONNECTING;
                viewBleConnection();

                // search Koshian, and open a selection dialog
                mKonashiManager.find(this, true);
            }
            // Disconnecting
            else {
                // disconnect Koshian
                mKonashiManager.disconnect();
            }
        }
        // [Server Update]
        else if (v.getId() == R.id.buttonServerUpdate) {
            try{
                int val = Integer.parseInt(editPortNum.getText().toString());
                if(val<1024 || val>65535) throw new NumberFormatException();
                portNum = val;
                toUpdate = true;
            }
            catch(NumberFormatException ex)
            {
                Toast.makeText(this, "ポート番号が無効です", Toast.LENGTH_LONG).show();
            }
        }
    }

    // View BLE Connection
    private void viewBleConnection()
    {
        switch(btState){
            case STATE_CONNECTED:
                buttonBleSearch.setText("BLEデバイス切断");
                textKoshianDev.setText(mKonashiManager.getPeripheralName());
                break;
            case STATE_CONNECTING:
                buttonBleSearch.setText("BLEデバイス検索");
                textKoshianDev.setText("接続中...");
                break;
            case STATE_DISCONNECTED:
                buttonBleSearch.setText("BLEデバイス検索");
                textKoshianDev.setText("未接続");
                break;
        }
    }

    // Get IP Address
    private String[] getIPAddress(){
        String[] ip = new String[2];
        int ipCnt = 0;
        ip[0] = "---.---.---.---";
        ip[1] = "";

        try{
            for (Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
                interfaces.hasMoreElements();){
                NetworkInterface networkInterface = interfaces.nextElement();
                for (Enumeration<InetAddress> ipAddressEnum = networkInterface.getInetAddresses(); ipAddressEnum.hasMoreElements();){
                    InetAddress inetAddress = (InetAddress) ipAddressEnum.nextElement();
                    //---check that it is not a loopback address and it is ipv4---
                    if(!inetAddress.isLoopbackAddress() && (inetAddress instanceof Inet4Address)){
                        if(ipCnt == 0){
                            ip[0] = inetAddress.getHostAddress();
                            ipCnt++;
                        }
                        else if(ipCnt == 1){
                            ip[1] = inetAddress.getHostAddress();
                            return ip;
                        }
                        //return inetAddress.getHostAddress();
                    }
                }
            }
        }catch (SocketException ex){
            Log.e("getLocalIpv4Address", ex.toString());

        }
        //return "---.---.---.---";
        return ip;
    }

    @Override
    public void run() {
        // スレッド終了指令まで
        while(!toQuit){
            try{
                mServer = new ServerSocket(portNum);
                mServer.setSoTimeout(3000); // timeout 3sec
                mClient = mServer.accept();
                //Toast.makeText(this, "accept!", Toast.LENGTH_LONG).show();

                mClient.setSoTimeout(2000); // timeout 2sec
                if(toQuit) return;

                // Show Client Address
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        String clientIp = mClient.getInetAddress().getHostAddress();
                        textClientIp.setText(clientIp);
                    }
                });

                reader = new BufferedReader(new InputStreamReader(mClient.getInputStream()));
                writer = new BufferedWriter(new OutputStreamWriter(mClient.getOutputStream()));
                isOpen = true;

                //Toast.makeText(this, "hoge!", Toast.LENGTH_LONG).show();

                // クライアントが閉じられるまで
                while(!toQuit && !toUpdate){
                    String data;
                    try {
                        data = reader.readLine();
                        if(data == null){
                            break;
                        }
                        // 受信したデータの処理
                        executeRecvData(data);
                    }
                    catch( SocketTimeoutException ex ) {
                        // System.out.println( "-> 受信タイムアウトが発生しました " );
                        continue;
                    }
                }
            }
            catch (IOException e) {
                e.printStackTrace();
            }
            isOpen = false;
            try{
                if(mClient!=null) mClient.close();
                if(mServer!=null) mServer.close();
            }
            catch(IOException e) {
                e.printStackTrace();
            }

            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    textClientIp.setText("未接続");
                    String[] ip = getIPAddress();
                    textServerIp1.setText(ip[0]);
                    textServerIp2.setText(ip[1]);
                }
            });

            toUpdate = false;
        }
    }

    // 受信データの処理
    private void executeRecvData(String data)
    {
        // ネットワーク接続通知
        if(data.startsWith("open"))
        {
            if(mKonashiManager.isConnected()){
                if(isOpen){
                    try{
                        writer.write("onConnect ");
                        writer.write(mKonashiManager.getPeripheralName());
                        writer.newLine();
                        writer.flush();
                    }
                    catch(IOException ex){
                        ;
                    }
                }
            }
        }
        // UART送信
        else if(data.startsWith("uartWrite "))
        {
            if(mKonashiManager.isConnected()){
                byte [] bCommand=data.substring(10).getBytes();
                mKonashiManager.uartWrite(bCommand)
                        .fail(new FailCallback<BletiaException>() {
                            @Override
                            public void onFail(BletiaException result) {
                                //Toast.makeText(self, result.getMessage(), Toast.LENGTH_SHORT).show();
                            }
                        });
            }
        }
        // UARTボーレート設定
        else if(data.startsWith("uartBaudrate "))
        {
            if(mKonashiManager.isConnected()){
                try{
                    int val = Integer.parseInt(data.substring(13));

                    if(val == 9600){
                        mKonashiManager.uartBaudrate(Konashi.UART_RATE_9K6);
                    }
                    else if(val == 19200){
                        mKonashiManager.uartBaudrate(Konashi.UART_RATE_19K2);
                    }
                    else if(val == 38400){
                        mKonashiManager.uartBaudrate(Konashi.UART_RATE_38K4);
                    }
                }catch(NumberFormatException ex)
                {
                    ;
                }
            }
        }
    }

    // permission request

    private static final int REQ_CODE_ALLOW_BLUETOOTH = 100;

    @TargetApi(Build.VERSION_CODES.M)
    private void requestLocationPermission() {
        if (checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, REQ_CODE_ALLOW_BLUETOOTH);
        }
    }

    @TargetApi(Build.VERSION_CODES.M)
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == REQ_CODE_ALLOW_BLUETOOTH) {
            if (grantResults.length > 0 && grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                finish();
            }
        } else {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }
}


text:
<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="utf-8">

		<!-- Always force latest IE rendering engine (even in intranet) & Chrome Frame
		Remove this if you use the .htaccess -->
		<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">

		<title>index</title>
		<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
		<meta name="apple-mobile-web-app-capable" content="yes">
		<meta name="apple-touch-fullscreen" content="yes">
		<meta name="apple-mobile-web-app-status-bar-style" content="black">
		<!-- Replace favicon.ico & apple-touch-icon.png in the root of your domain and delete these references -->
		<link rel="shortcut icon" href="/favicon.ico">
		<link rel="apple-touch-icon" href="/apple-touch-icon.png">
		<script src="http://maps.google.com/maps/api/js?sensor=true&libraries=places"></script>
		<link href="/static/world/css/bootstrap.min.css" type="text/css" rel="stylesheet"/>
		<link href="/static/world/css/style.css" type="text/css" rel="stylesheet"/>
		<script src="/static/jquery/jquery-2.1.1.min.js"></script>
		<!-- <script src="/static/world/js/app.js"></script> -->
		<script src="/static/OpenLayers/OpenLayers.js"></script>
		<script src="/static/world/js/openlayers.js"></script>
	</head>

	<body onload="geom.init();">
		<div id="map" class="map">
		</div>
		<textarea id="id_geom" cols="150" rows="10"></textarea>
	</body>
</html>


text:
using System;
using Umbraco.Cms.Core.Models.PublishedContent;

namespace Umbraco.Extensions
{
    /// <summary>
    /// Provides strongly typed published content models services.
    /// </summary>
    public static class PublishedContentExtensionsForModels
    {
        /// <summary>
        /// Creates a strongly typed published content model for an internal published content.
        /// </summary>
        /// <param name="content">The internal published content.</param>
        /// <returns>The strongly typed published content model.</returns>
        public static IPublishedContent CreateModel(this IPublishedContent content, IPublishedModelFactory publishedModelFactory)
        {
            if (publishedModelFactory == null) throw new ArgumentNullException(nameof(publishedModelFactory));
            if (content == null)
                return null;

            // get model
            // if factory returns nothing, throw
            var model = publishedModelFactory.CreateModel(content);
            if (model == null)
                throw new InvalidOperationException("Factory returned null.");

            // if factory returns a different type, throw
            if (!(model is IPublishedContent publishedContent))
                throw new InvalidOperationException($"Factory returned model of type {model.GetType().FullName} which does not implement IPublishedContent.");

            return publishedContent;
        }
    }
}


text:
package com.twosigma.beaker.chart.xychart.plotitem;

import com.twosigma.beaker.chart.Color;
import java.util.ArrayList;
import java.util.List;

abstract public class XYGraphics {
  private List<Number> xs;
  private List<Number> ys;
  private boolean visible = true;
  private String displayName = "";
  private String yAxisName = null;

  public void setX(List<Number> xs) {
    this.xs = xs;
  }

  public List<Number> getX() {
    if (xs == null) {
      generateXs();
    }
    return this.xs;
  }

  public void setY(List<Number> ys) {
    this.ys = ys;
  }

  public List<Number> getY() {
    return this.ys;
  }

  public void setVisible(boolean visible) {
    this.visible = visible;
  }

  public Boolean getVisible() {
    return this.visible;
  }

  public void setDisplayName(String displayName) {
    this.displayName = displayName;
  }

  public String getDisplayName() {
    return this.displayName;
  }

  public void setYAxis(String yAxisName) {
    this.yAxisName = yAxisName;
  }

  public void setyAxis(String yAxisName) {
    this.yAxisName = yAxisName;
  }

  private void generateXs() {
    this.xs = new ArrayList<>(this.ys.size());
    for (int i = 0; i < ys.size(); ++i) {
      this.xs.add(i);
    }
  }

  abstract public void setColori(Color color);
  abstract public Color getColor();
}


text:
import uuid
from observable import Observable
from twisted.internet.protocol import Factory, Protocol

class EndpointFactory(Factory):
    def __init__(self, endpoint):
        self.endpoint = endpoint

class EndpointProtocol(Protocol):
    def connectionMade(self):
        self.factory.endpoint.transports.add(self.transport)
        self.factory.endpoint.trigger('connection', self.transport)

    def dataReceived(self, data):
        self.factory.endpoint.trigger('data', self.transport, data)

    def connectionLost(self, reason):
        value = None
        if reason and reason.value:
            value = reason.value

        self.factory.endpoint.transports.remove(self.transport)
        self.factory.endpoint.trigger('close', self.transport, value)

class Transports(dict):
    def __init__(self, *args, **kwargs):
        super(Transports, self).__init__(*args, **kwargs)

    def __call__(self, *args, **kwargs):
        return self.values()

    def add(self, transport):
        transport.id = str(uuid.uuid4())
        self[transport.id] = transport

    def remove(self, transport):
        if transport.id in self:
            del self[transport.id]

class Endpoint(Observable):
    def __init__(self, name):
        self.name = name
        self.transports = Transports()