text:
/*!
 * \file
 * \brief WGL Utilities.
 *//*--------------------------------------------------------------------*/

#include "tcuWGL.hpp"
#include "tcuWin32Window.hpp"
#include "deDynamicLibrary.hpp"
#include "deMemory.h"
#include "deStringUtil.hpp"
#include "tcuFormatUtil.hpp"
#include "gluRenderConfig.hpp"
#include "glwEnums.hpp"

#include <map>
#include <sstream>
#include <iterator>
#include <set>

#include <WinGDI.h>

// WGL_ARB_pixel_format
#define WGL_NUMBER_PIXEL_FORMATS_ARB				0x2000
#define WGL_DRAW_TO_WINDOW_ARB						0x2001
#define WGL_DRAW_TO_BITMAP_ARB						0x2002
#define WGL_ACCELERATION_ARB						0x2003
#define WGL_NEED_PALETTE_ARB						0x2004
#define WGL_NEED_SYSTEM_PALETTE_ARB					0x2005
#define WGL_SWAP_LAYER_BUFFERS_ARB					0x2006
#define WGL_SWAP_METHOD_ARB							0x2007
#define WGL_NUMBER_OVERLAYS_ARB						0x2008
#define WGL_NUMBER_UNDERLAYS_ARB					0x2009
#define WGL_TRANSPARENT_ARB							0x200A
#define WGL_TRANSPARENT_RED_VALUE_ARB				0x2037
#define WGL_TRANSPARENT_GREEN_VALUE_ARB				0x2038
#define WGL_TRANSPARENT_BLUE_VALUE_ARB				0x2039
#define WGL_TRANSPARENT_ALPHA_VALUE_ARB				0x203A
#define WGL_TRANSPARENT_INDEX_VALUE_ARB				0x203B
#define WGL_SHARE_DEPTH_ARB							0x200C
#define WGL_SHARE_STENCIL_ARB						0x200D
#define WGL_SHARE_ACCUM_ARB							0x200E
#define WGL_SUPPORT_GDI_ARB							0x200F
#define WGL_SUPPORT_OPENGL_ARB						0x2010
#define WGL_DOUBLE_BUFFER_ARB						0x2011
#define WGL_STEREO_ARB								0x2012
#define WGL_PIXEL_TYPE_ARB							0x2013
#define WGL_COLOR_BITS_ARB							0x2014
#define WGL_RED_BITS_ARB							0x2015
#define WGL_RED_SHIFT_ARB							0x2016
#define WGL_GREEN_BITS_ARB							0x2017
#define WGL_GREEN_SHIFT_ARB							0x2018
#define WGL_BLUE_BITS_ARB							0x2019
#define WGL_BLUE_SHIFT_ARB							0x201A
#define WGL_ALPHA_BITS_ARB							0x201B
#define WGL_ALPHA_SHIFT_ARB							0x201C
#define WGL_ACCUM_BITS_ARB							0x201D
#define WGL_ACCUM_RED_BITS_ARB						0x201E
#define WGL_ACCUM_GREEN_BITS_ARB					0x201F
#define WGL_ACCUM_BLUE_BITS_ARB						0x2020
#define WGL_ACCUM_ALPHA_BITS_ARB					0x2021
#define WGL_DEPTH_BITS_ARB							0x2022
#define WGL_STENCIL_BITS_ARB						0x2023
#define WGL_AUX_BUFFERS_ARB							0x2024

#define WGL_NO_ACCELERATION_ARB						0x2025
#define WGL_GENERIC_ACCELERATION_ARB				0x2026
#define WGL_FULL_ACCELERATION_ARB					0x2027

#define WGL_TYPE_RGBA_ARB							0x202B
#define WGL_TYPE_COLORINDEX_ARB						0x202C

// WGL_ARB_color_buffer_float
#define WGL_TYPE_RGBA_FLOAT_ARB						0x21A0

// WGL_EXT_pixel_type_packed_float
#define WGL_TYPE_RGBA_UNSIGNED_FLOAT_EXT			0x20A8

// WGL_ARB_multisample
#define WGL_SAMPLE_BUFFERS_ARB						0x2041
#define WGL_SAMPLES_ARB								0x2042

// WGL_ARB_create_context
#define WGL_CONTEXT_MAJOR_VERSION_ARB				0x2091
#define WGL_CONTEXT_MINOR_VERSION_ARB				0x2092
#define WGL_CONTEXT_LAYER_PLANE_ARB					0x2093
#define WGL_CONTEXT_FLAGS_ARB						0x2094
#define WGL_CONTEXT_PROFILE_MASK_ARB				0x9126
#define WGL_CONTEXT_DEBUG_BIT_ARB					0x0001
#define WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB		0x0002
#define WGL_CONTEXT_CORE_PROFILE_BIT_ARB			0x00000001
#define WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB	0x00000002
#define WGL_CONTEXT_ES_PROFILE_BIT_EXT				0x00000004

// WGL_ARB_create_context_robustness
#define WGL_CONTEXT_ROBUST_ACCESS_BIT_ARB			0x0004
#define WGL_CONTEXT_RESET_NOTIFICATION_STRATEGY_ARB	0x8256
#define WGL_NO_RESET_NOTIFICATION_ARB				0x8261
#define WGL_LOSE_CONTEXT_ON_RESET_ARB				0x8252

// WGL ARB_create_context_no_error
#define WGL_CONTEXT_OPENGL_NO_ERROR_ARB				0x31B3

DE_BEGIN_EXTERN_C

// WGL core
typedef HGLRC		(WINAPI* wglCreateContextFunc)				(HDC hdc);
typedef BOOL		(WINAPI* wglDeleteContextFunc)				(HGLRC hglrc);
typedef BOOL		(WINAPI* wglMakeCurrentFunc)				(HDC hdc, HGLRC hglrc);
typedef PROC		(WINAPI* wglGetProcAddressFunc)				(LPCSTR lpszProc);
typedef BOOL		(WINAPI* wglSwapLayerBuffersFunc)			(HDC dhc, UINT fuPlanes);

// WGL_ARB_pixel_format
typedef BOOL		(WINAPI* wglGetPixelFormatAttribivARBFunc)	(HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, int *piValues);
typedef BOOL		(WINAPI* wglGetPixelFormatAttribfvARBFunc)	(HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, FLOAT *pfValues);
typedef BOOL		(WINAPI* wglChoosePixelFormatARBFunc)		(HDC hdc, const int *piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats);

// WGL_ARB_create_context
typedef HGLRC		(WINAPI* wglCreateContextAttribsARBFunc)	(HDC hdc, HGLRC hshareContext, const int* attribList);
typedef const char*	(WINAPI* wglGetExtensionsStringARBFunc)		(HDC hdc);

DE_END_EXTERN_C

namespace tcu
{
namespace wgl
{

// Functions

struct Functions
{
	// Core
	wglCreateContextFunc				createContext;
	wglDeleteContextFunc				deleteContext;
	wglMakeCurrentFunc					makeCurrent;
	wglGetProcAddressFunc				getProcAddress;
	wglSwapLayerBuffersFunc				swapLayerBuffers;

	// WGL_ARB_pixel_format
	wglGetPixelFormatAttribivARBFunc	getPixelFormatAttribivARB;
	wglGetPixelFormatAttribfvARBFunc	getPixelFormatAttribfvARB;
	wglChoosePixelFormatARBFunc			choosePixelFormatARB;

	// WGL_ARB_create_context
	wglCreateContextAttribsARBFunc		createContextAttribsARB;
	wglGetExtensionsStringARBFunc		getExtensionsStringARB;

	Functions (void)
		: createContext				(DE_NULL)
		, deleteContext				(DE_NULL)
		, makeCurrent				(DE_NULL)
		, getProcAddress			(DE_NULL)
		, swapLayerBuffers			(DE_NULL)
		, getPixelFormatAttribivARB	(DE_NULL)
		, getPixelFormatAttribfvARB	(DE_NULL)
		, choosePixelFormatARB		(DE_NULL)
		, createContextAttribsARB	(DE_NULL)
		, getExtensionsStringARB	(DE_NULL)
	{
	}
};

// Library

class Library
{
public:
								Library			(HINSTANCE instance);
								~Library		(void);

	const Functions&			getFunctions	(void) const	{ return m_functions;	}
	const de::DynamicLibrary&	getGLLibrary	(void) const	{ return m_library;		}
	bool						isWglExtensionSupported (const char* extName) const;

private:
	de::DynamicLibrary			m_library;
	Functions					m_functions;
	std::set<std::string>		m_extensions;
};

Library::Library (HINSTANCE instance)
	: m_library("opengl32.dll")
{
	// Temporary 1x1 window for creating context
	win32::Window tmpWindow(instance, 1, 1);

	// Load WGL core.
	m_functions.createContext		= (wglCreateContextFunc)		m_library.getFunction("wglCreateContext");
	m_functions.deleteContext		= (wglDeleteContextFunc)		m_library.getFunction("wglDeleteContext");
	m_functions.getProcAddress		= (wglGetProcAddressFunc)		m_library.getFunction("wglGetProcAddress");
	m_functions.makeCurrent			= (wglMakeCurrentFunc)			m_library.getFunction("wglMakeCurrent");
	m_functions.swapLayerBuffers	= (wglSwapLayerBuffersFunc)		m_library.getFunction("wglSwapLayerBuffers");

	if (!m_functions.createContext		||
		!m_functions.deleteContext		||
		!m_functions.getProcAddress		||
		!m_functions.makeCurrent		||
		!m_functions.swapLayerBuffers)
		throw ResourceError("Failed to load core WGL functions");

	{
		PIXELFORMATDESCRIPTOR pixelFormatDesc;
		deMemset(&pixelFormatDesc, 0, sizeof(pixelFormatDesc));

		pixelFormatDesc.nSize			= sizeof(pixelFormatDesc);
		pixelFormatDesc.nVersion		= 1;
		pixelFormatDesc.dwFlags			= PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
		pixelFormatDesc.iPixelType		= PFD_TYPE_RGBA;
		pixelFormatDesc.iLayerType		= PFD_MAIN_PLANE;

		int pixelFormat = ChoosePixelFormat(tmpWindow.getDeviceContext(), &pixelFormatDesc);
		if (!SetPixelFormat(tmpWindow.getDeviceContext(), pixelFormat, &pixelFormatDesc))
			throw ResourceError("Failed to set pixel format for temporary context creation");
	}

	// Create temporary context for loading extension functions.
	HGLRC tmpCtx = m_functions.createContext(tmpWindow.getDeviceContext());
	if (!tmpCtx || !m_functions.makeCurrent(tmpWindow.getDeviceContext(), tmpCtx))
	{
		if (tmpCtx)
			m_functions.deleteContext(tmpCtx);
		throw ResourceError("Failed to create temporary WGL context");
	}

	// WGL_ARB_pixel_format
	m_functions.getPixelFormatAttribivARB	= (wglGetPixelFormatAttribivARBFunc)m_functions.getProcAddress("wglGetPixelFormatAttribivARB");
	m_functions.getPixelFormatAttribfvARB	= (wglGetPixelFormatAttribfvARBFunc)m_functions.getProcAddress("wglGetPixelFormatAttribfvARB");
	m_functions.choosePixelFormatARB		= (wglChoosePixelFormatARBFunc)m_functions.getProcAddress("wglChoosePixelFormatARB");

	// WGL_ARB_create_context
	m_functions.createContextAttribsARB		= (wglCreateContextAttribsARBFunc)m_functions.getProcAddress("wglCreateContextAttribsARB");
	m_functions.getExtensionsStringARB		= (wglGetExtensionsStringARBFunc)m_functions.getProcAddress("wglGetExtensionsStringARB");

	m_functions.makeCurrent(tmpWindow.getDeviceContext(), NULL);
	m_functions.deleteContext(tmpCtx);

	if (!m_functions.getPixelFormatAttribivARB	||
		!m_functions.getPixelFormatAttribfvARB	||
		!m_functions.choosePixelFormatARB		||
		!m_functions.createContextAttribsARB	||
		!m_functions.getExtensionsStringARB)
		throw ResourceError("Failed to load WGL extension functions");

	const char* extensions = m_functions.getExtensionsStringARB(tmpWindow.getDeviceContext());
	std::istringstream extStream(extensions);
	m_extensions = std::set<std::string>(std::istream_iterator<std::string>(extStream),
										 std::istream_iterator<std::string>());
}

Library::~Library (void)
{
}

bool Library::isWglExtensionSupported (const char* extName) const
{
	return m_extensions.find(extName) != m_extensions.end();
}

// Core

Core::Core (HINSTANCE instance)
	: m_library(new Library(instance))
{
}

Core::~Core (void)
{
	delete m_library;
}

std::vector<int> Core::getPixelFormats (HDC deviceCtx) const
{
	const Functions& wgl = m_library->getFunctions();

	int attribs[] = { WGL_NUMBER_PIXEL_FORMATS_ARB };
	int values[DE_LENGTH_OF_ARRAY(attribs)];

	if (!wgl.getPixelFormatAttribivARB(deviceCtx, 0, 0, DE_LENGTH_OF_ARRAY(attribs), &attribs[0], &values[0]))
		TCU_THROW(ResourceError, "Failed to query number of WGL pixel formats");

	std::vector<int> pixelFormats(values[0]);
	for (int i = 0; i < values[0]; i++)
		pixelFormats[i] = i+1;

	return pixelFormats;
}

static PixelFormatInfo::Acceleration translateAcceleration (int accel)
{
	switch (accel)
	{
		case WGL_NO_ACCELERATION_ARB:		return PixelFormatInfo::ACCELERATION_NONE;
		case WGL_GENERIC_ACCELERATION_ARB:	return PixelFormatInfo::ACCELERATION_GENERIC;
		case WGL_FULL_ACCELERATION_ARB:		return PixelFormatInfo::ACCELERATION_FULL;
		default:							return PixelFormatInfo::ACCELERATION_UNKNOWN;
	}
}

static PixelFormatInfo::PixelType translatePixelType (int type)
{
	switch (type)
	{
		case WGL_TYPE_RGBA_ARB:					return PixelFormatInfo::PIXELTYPE_RGBA;
		case WGL_TYPE_RGBA_FLOAT_ARB:			return PixelFormatInfo::PIXELTYPE_RGBA_FLOAT;
		case WGL_TYPE_RGBA_UNSIGNED_FLOAT_EXT:	return PixelFormatInfo::PIXELTYPE_RGBA_UNSIGNED_FLOAT;
		case WGL_TYPE_COLORINDEX_ARB:			return PixelFormatInfo::PIXELTYPE_COLOR_INDEX;
		default:								return PixelFormatInfo::PIXELTYPE_UNKNOWN;
	}
}

static void getPixelFormatAttribs (const Functions& wgl, HDC deviceCtx, int pixelFormat, int numAttribs, const int* attribs, std::map<int, int>* dst)
{
	std::vector<int>	values	(numAttribs);

	if (!wgl.getPixelFormatAttribivARB(deviceCtx, pixelFormat, 0, numAttribs, &attribs[0], &values[0]))
		TCU_THROW(ResourceError, "Pixel format query failed");

	for (int ndx = 0; ndx < numAttribs; ++ndx)
		(*dst)[attribs[ndx]] = values[ndx];
}

PixelFormatInfo Core::getPixelFormatInfo (HDC deviceCtx, int pixelFormat) const
{
	static const int	s_attribsToQuery[] =
	{
		WGL_DRAW_TO_WINDOW_ARB,
		WGL_DRAW_TO_BITMAP_ARB,
		WGL_ACCELERATION_ARB,
		WGL_NEED_PALETTE_ARB,
		WGL_NEED_SYSTEM_PALETTE_ARB,
		WGL_NUMBER_OVERLAYS_ARB,
		WGL_NUMBER_UNDERLAYS_ARB,
		WGL_SUPPORT_OPENGL_ARB,
		WGL_DOUBLE_BUFFER_ARB,
		WGL_STEREO_ARB,
		WGL_PIXEL_TYPE_ARB,
		WGL_RED_BITS_ARB,
		WGL_GREEN_BITS_ARB,
		WGL_BLUE_BITS_ARB,
		WGL_ALPHA_BITS_ARB,
		WGL_ACCUM_BITS_ARB,
		WGL_DEPTH_BITS_ARB,
		WGL_STENCIL_BITS_ARB,
		WGL_AUX_BUFFERS_ARB,
		WGL_SAMPLE_BUFFERS_ARB,
		WGL_SAMPLES_ARB,
	};
	const Functions&	wgl			= m_library->getFunctions();
	std::map<int, int>	values;

	getPixelFormatAttribs(wgl, deviceCtx, pixelFormat, DE_LENGTH_OF_ARRAY(s_attribsToQuery), &s_attribsToQuery[0], &values);

	// Translate values.
	PixelFormatInfo info;

	info.pixelFormat		= pixelFormat;
	info.surfaceTypes		|= (values[WGL_DRAW_TO_WINDOW_ARB] ? PixelFormatInfo::SURFACE_WINDOW : 0);
	info.surfaceTypes		|= (values[WGL_DRAW_TO_BITMAP_ARB] ? PixelFormatInfo::SURFACE_PIXMAP : 0);
	info.acceleration		= translateAcceleration(values[WGL_ACCELERATION_ARB]);
	info.needPalette		= values[WGL_NEED_PALETTE_ARB] != 0;
	info.needSystemPalette	= values[WGL_NEED_SYSTEM_PALETTE_ARB] != 0;
	info.numOverlays		= values[WGL_NUMBER_OVERLAYS_ARB] != 0;
	info.numUnderlays		= values[WGL_NUMBER_UNDERLAYS_ARB] != 0;
	info.supportOpenGL		= values[WGL_SUPPORT_OPENGL_ARB] != 0;
	info.doubleBuffer		= values[WGL_DOUBLE_BUFFER_ARB] != 0;
	info.stereo				= values[WGL_STEREO_ARB] != 0;
	info.pixelType			= translatePixelType(values[WGL_PIXEL_TYPE_ARB]);
	info.redBits			= values[WGL_RED_BITS_ARB];
	info.greenBits			= values[WGL_GREEN_BITS_ARB];
	info.blueBits			= values[WGL_BLUE_BITS_ARB];
	info.alphaBits			= values[WGL_ALPHA_BITS_ARB];
	info.accumBits			= values[WGL_ACCUM_BITS_ARB];
	info.depthBits			= values[WGL_DEPTH_BITS_ARB];
	info.stencilBits		= values[WGL_STENCIL_BITS_ARB];
	info.numAuxBuffers		= values[WGL_AUX_BUFFERS_ARB];
	info.sampleBuffers		= values[WGL_SAMPLE_BUFFERS_ARB];
	info.samples			= values[WGL_SAMPLES_ARB];

	return info;
}

// Context

Context::Context (const Core*						core,
				  HDC								deviceCtx,
				  const Context*					sharedContext,
				  glu::ContextType					ctxType,
				  int								pixelFormat,
				  glu::ResetNotificationStrategy	resetNotificationStrategy)
	: m_core		(core)
	, m_deviceCtx	(deviceCtx)
	, m_context		(0)
{
	const Functions&		wgl				= core->getLibrary()->getFunctions();
	std::vector<int>		attribList;

	// Context version and profile
	{
		int	profileBit	= 0;
		HGLRC sharedCtx	= DE_NULL;
		int minor		= ctxType.getMinorVersion();
		int major		= ctxType.getMajorVersion();

		switch (ctxType.getProfile())
		{
			case glu::PROFILE_CORE:
				profileBit = WGL_CONTEXT_CORE_PROFILE_BIT_ARB;
				if (major == 3 && minor < 3)
					minor = 3;
				break;

			case glu::PROFILE_ES:
				profileBit = WGL_CONTEXT_ES_PROFILE_BIT_EXT;
				break;

			case glu::PROFILE_COMPATIBILITY:
				profileBit = WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB;
				break;

			default:
				TCU_THROW(NotSupportedError, "Unsupported context type for WGL");
		}

		attribList.push_back(WGL_CONTEXT_MAJOR_VERSION_ARB);
		attribList.push_back(major);
		attribList.push_back(WGL_CONTEXT_MINOR_VERSION_ARB);
		attribList.push_back(minor);
		attribList.push_back(WGL_CONTEXT_PROFILE_MASK_ARB);
		attribList.push_back(profileBit);
	}

	// Context flags
	{
		int		flags	= 0;

		if ((ctxType.getFlags() & glu::CONTEXT_FORWARD_COMPATIBLE) != 0)
		{
			if (glu::isContextTypeES(ctxType))
				TCU_THROW(InternalError, "Only OpenGL core contexts can be forward-compatible");

			flags |= WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB;
		}

		if ((ctxType.getFlags() & glu::CONTEXT_DEBUG) != 0)
			flags |= WGL_CONTEXT_DEBUG_BIT_ARB;

		if ((ctxType.getFlags() & glu::CONTEXT_ROBUST) != 0)
			flags |= WGL_CONTEXT_ROBUST_ACCESS_BIT_ARB;

		if ((ctxType.getFlags() & glu::CONTEXT_NO_ERROR) != 0)
		{
			if (core->getLibrary()->isWglExtensionSupported("WGL_ARB_create_context_no_error"))
			{
				attribList.push_back(WGL_CONTEXT_OPENGL_NO_ERROR_ARB);
				attribList.push_back(1);
			}
			else
				TCU_THROW(NotSupportedError, "WGL_ARB_create_context_no_error is required for creating no-error contexts");
		}

		if (flags != 0)
		{
			attribList.push_back(WGL_CONTEXT_FLAGS_ARB);
			attribList.push_back(flags);
		}
	}

	if (resetNotificationStrategy != glu::RESET_NOTIFICATION_STRATEGY_NOT_SPECIFIED)
	{
		attribList.push_back(WGL_CONTEXT_RESET_NOTIFICATION_STRATEGY_ARB);

		if (resetNotificationStrategy == glu::RESET_NOTIFICATION_STRATEGY_NO_RESET_NOTIFICATION)
			attribList.push_back(WGL_NO_RESET_NOTIFICATION_ARB);
		else if (resetNotificationStrategy == glu::RESET_NOTIFICATION_STRATEGY_LOSE_CONTEXT_ON_RESET)
			attribList.push_back(WGL_LOSE_CONTEXT_ON_RESET_ARB);
		else
			TCU_THROW(InternalError, "Unknown reset notification strategy");
	}

	// Set pixel format
	{
		PIXELFORMATDESCRIPTOR pixelFormatDesc;
		deMemset(&pixelFormatDesc, 0, sizeof(pixelFormatDesc));

		if (!DescribePixelFormat(deviceCtx, pixelFormat, sizeof(pixelFormatDesc), &pixelFormatDesc))
			throw ResourceError("DescribePixelFormat() failed");

		if (!SetPixelFormat(deviceCtx, pixelFormat, &pixelFormatDesc))
			throw ResourceError("Failed to set pixel format");
	}

	HGLRC sharedCtx = DE_NULL;
	if (DE_NULL != sharedContext)
		sharedCtx = sharedContext->m_context;

	// Terminate attribList
	attribList.push_back(0);

	// Create context
	m_context = wgl.createContextAttribsARB(deviceCtx, sharedCtx, &attribList[0]);

	if (!m_context)
		TCU_THROW(ResourceError, "Failed to create WGL context");

	if (!wgl.makeCurrent(deviceCtx, m_context))
	{
		wgl.deleteContext(m_context);
		TCU_THROW(ResourceError, "wglMakeCurrent() failed");
	}
}

Context::~Context (void)
{
	const Functions& wgl = m_core->getLibrary()->getFunctions();

	wgl.makeCurrent(m_deviceCtx, NULL);
	wgl.deleteContext(m_context);
}

FunctionPtr Context::getGLFunction (const char* name) const
{
	FunctionPtr ptr = DE_NULL;

	// Try first with wglGeProcAddress()
	ptr = (FunctionPtr)m_core->getLibrary()->getFunctions().getProcAddress(name);

	// Fall-back to dynlib
	if (!ptr)
		ptr = (FunctionPtr)m_core->getLibrary()->getGLLibrary().getFunction(name);

	return ptr;
}

void Context::makeCurrent (void)
{
	const Functions& wgl = m_core->getLibrary()->getFunctions();
	if (!wgl.makeCurrent(m_deviceCtx, m_context))
		TCU_THROW(ResourceError, "wglMakeCurrent() failed");
}

void Context::swapBuffers (void) const
{
	const Functions& wgl = m_core->getLibrary()->getFunctions();
	if (!wgl.swapLayerBuffers(m_deviceCtx, WGL_SWAP_MAIN_PLANE))
		TCU_THROW(ResourceError, "wglSwapBuffers() failed");
}

bool isSupportedByTests (const PixelFormatInfo& info)
{
	if (!info.supportOpenGL)
		return false;

	if (info.acceleration != wgl::PixelFormatInfo::ACCELERATION_FULL)
		return false;

	if (info.pixelType != wgl::PixelFormatInfo::PIXELTYPE_RGBA)
		return false;

	if ((info.surfaceTypes & wgl::PixelFormatInfo::SURFACE_WINDOW) == 0)
		return false;

	if (info.needPalette || info.needSystemPalette)
		return false;

	if (info.numOverlays != 0 || info.numUnderlays != 0)
		return false;

	if (info.stereo)
		return false;

	return true;
}

int choosePixelFormat (const Core& wgl, HDC deviceCtx, const glu::RenderConfig& config)
{
	std::vector<int> pixelFormats = wgl.getPixelFormats(deviceCtx);

	for (std::vector<int>::const_iterator fmtIter = pixelFormats.begin(); fmtIter != pixelFormats.end(); ++fmtIter)
	{
		const PixelFormatInfo info = wgl.getPixelFormatInfo(deviceCtx, *fmtIter);

		// Skip formats that are fundamentally not compatible with current tests
		if (!isSupportedByTests(info))
			continue;

		if (config.redBits != glu::RenderConfig::DONT_CARE &&
			config.redBits != info.redBits)
			continue;

		if (config.greenBits != glu::RenderConfig::DONT_CARE &&
			config.greenBits != info.greenBits)
			continue;

		if (config.blueBits != glu::RenderConfig::DONT_CARE &&
			config.blueBits != info.blueBits)
			continue;

		if (config.alphaBits != glu::RenderConfig::DONT_CARE &&
			config.alphaBits != info.alphaBits)
			continue;

		if (config.depthBits != glu::RenderConfig::DONT_CARE &&
			config.depthBits != info.depthBits)
			continue;

		if (config.stencilBits != glu::RenderConfig::DONT_CARE &&
			config.stencilBits != info.stencilBits)
			continue;

		if (config.numSamples != glu::RenderConfig::DONT_CARE &&
			config.numSamples != info.samples)
			continue;

		// Passed all tests - select this.
		return info.pixelFormat;
	}

	return -1;
}

} // wgl
} // tcu


text:
import MemoryDriver from '../drivers/memory-driver';
import Store from '../index';

describe('store', () => {
  for (const Driver of [MemoryDriver]) {
    describe(Driver.name, () => {
      it('supports CRUD operations', async () => {
        const s = new Store(new Driver());
        expect(await s.hasItem('404')).toBe(false);
        expect(await s.getItem('404')).toBe(null);
        expect(await s.setItem('foo', 'bar')).toBe(undefined);
        expect(await s.getItem('foo')).toBe('bar');
        expect(await s.setItem('null', null)).toBe(undefined);
        expect(await s.getItem('null')).toBe(null);
        expect(
          await s.setItem('obj', {
            foo: 'bar',
          }),
        ).toBe(undefined);
        expect(await s.getItem('obj')).toEqual({
          foo: 'bar',
        });
        expect(await s.removeItem('foo')).toBe(undefined);
        expect(await s.hasItem('foo')).toBe(false);
        expect(await s.getItem('foo')).toBe(null);
      });

      it('clears all values', async () => {
        const s = new Store(new Driver());
        await s.setItem('a', 'aaa');
        await s.setItem('b', 'bbb');
        await s.clear();
        expect(await s.hasItem('a')).toBe(false);
        expect(await s.hasItem('b')).toBe(false);
      });

      it('stores buffers directly', async () => {
        const s = new Store(new Driver());
        await s.setItem('buff', Buffer.from('{"hi": "there"}', 'utf8'));
        await s.setItem('json', {
          hi: 'there',
        });
        expect(await s.getItem('buff')).toEqual({
          hi: 'there',
        });
        expect(await s.getItem('json')).toEqual({
          hi: 'there',
        });
        expect((await s._driver.getItem('buff')).toString('utf8')).toEqual('{"hi": "there"}');
        expect((await s._driver.getItem('json')).toString('utf8')).toEqual('{\n  "hi": "there"\n}');
      });
    });
  }

  it('supports hooks', async () => {
    const s = new Store(new MemoryDriver(), [
      {
        // Just some dumb hooks to test with
        read: (_ext, buff) => Buffer.from(buff.toString('utf8').replace('WORLD', 'World')),
        write: (_ext, buff) => Buffer.from(buff.toString('utf8').replace('World', 'WORLD')),
      },
    ]);
    await s.setItem('foo', {
      Hello: 'World!',
    });
    expect((await s._driver.getItem('foo')).toString('utf8')).toBe('{\n  "Hello": "WORLD!"\n}');
    expect(await s.getItem('foo')).toEqual({
      Hello: 'World!',
    });
  });
});

redpajama_set_name: RedPajamaGithub


text:
package clientmock

import (
	context "context"
	reflect "reflect"

	gomock "github.com/golang/mock/gomock"
	echo "github.com/uber/zanzibar/examples/example-gateway/build/gen-code/clients-idl/clients/echo"
	yarpc "go.uber.org/yarpc"
)

// MockClient is a mock of Client interface.
type MockClient struct {
	ctrl     *gomock.Controller
	recorder *MockClientMockRecorder
}

// MockClientMockRecorder is the mock recorder for MockClient.
type MockClientMockRecorder struct {
	mock *MockClient
}

// NewMockClient creates a new mock instance.
func NewMockClient(ctrl *gomock.Controller) *MockClient {
	mock := &MockClient{ctrl: ctrl}
	mock.recorder = &MockClientMockRecorder{mock}
	return mock
}

// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockClient) EXPECT() *MockClientMockRecorder {
	return m.recorder
}

// EchoEcho mocks base method.
func (m *MockClient) EchoEcho(arg0 context.Context, arg1 *echo.Request, arg2 ...yarpc.CallOption) (context.Context, *echo.Response, error) {
	m.ctrl.T.Helper()
	varargs := []interface{}{arg0, arg1}
	for _, a := range arg2 {
		varargs = append(varargs, a)
	}
	ret := m.ctrl.Call(m, "EchoEcho", varargs...)
	ret0, _ := ret[0].(context.Context)
	ret1, _ := ret[1].(*echo.Response)
	ret2, _ := ret[2].(error)
	return ret0, ret1, ret2
}

// EchoEcho indicates an expected call of EchoEcho.
func (mr *MockClientMockRecorder) EchoEcho(arg0, arg1 interface{}, arg2 ...interface{}) *gomock.Call {
	mr.mock.ctrl.T.Helper()
	varargs := append([]interface{}{arg0, arg1}, arg2...)
	return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "EchoEcho", reflect.TypeOf((*MockClient)(nil).EchoEcho), varargs...)
}


text:
namespace mongocxx {
MONGOCXX_INLINE_NAMESPACE_BEGIN

///
/// Class representing an exception received from a MongoDB server.  It includes the server-provided
/// error code, if one was available.
///
/// @see mongocxx::exception
///
class MONGOCXX_API operation_exception : public exception {
   public:
    using exception::exception;

    ///
    /// Constructs a new operation exception.
    ///
    /// @param ec
    ///   The error code associated with this exception.
    /// @param raw_server_error
    ///   The optional raw bson error document to be associated with this exception.
    /// @param what_arg
    ///   An optional message to be returned by `what`.
    ///
    operation_exception(std::error_code ec,
                        bsoncxx::document::value&& raw_server_error,
                        std::string what_arg = "");

    ///
    /// @{
    ///
    /// The optional raw bson error document from the server.
    ///
    /// @returns The raw server error, if it is available.
    ///
    const stdx::optional<bsoncxx::document::value>& raw_server_error() const;
    stdx::optional<bsoncxx::document::value>& raw_server_error();
    ///
    /// @}
    ///

    ///
    /// Checks for the specified label in a operation exception.
    ///
    /// @param label
    ///   A string of the label to search for
    ///
    /// @returns True if the label is found in the operation exception, and false otherwise.
    ///
    bool has_error_label(stdx::string_view label) const;

   private:
    stdx::optional<bsoncxx::document::value> _raw_server_error;
};

MONGOCXX_INLINE_NAMESPACE_END
}  // namespace mongocxx

#include <mongocxx/config/postlude.hpp>


text:
FROM python:3.6
RUN apt-get update -q -y && apt-get install build-essential -q -y
ADD . /code
WORKDIR code
RUN pip install -r requirements.txt
RUN pip install .


text:
package pl.touk.nussknacker.engine.util.service

import cats.data.NonEmptyList
import com.typesafe.scalalogging.LazyLogging
import pl.touk.nussknacker.engine.api.Service
import pl.touk.nussknacker.engine.api.runtimecontext.EngineRuntimeContext
import pl.touk.nussknacker.engine.util.SafeLazyValues
import pl.touk.nussknacker.engine.util.metrics.MetricIdentifier

import scala.concurrent.duration.{Duration, DurationInt}
import scala.concurrent.{ExecutionContext, Future}
import scala.util.{Failure, Success, Try}

trait TimeMeasuringService { self: Service =>

  protected var timeMeasurement: AsyncExecutionTimeMeasurement = _

  override def open(context: EngineRuntimeContext): Unit = {
    timeMeasurement = new AsyncExecutionTimeMeasurement(context, serviceName, tags)
  }

  def measuring[T](actionFun: => Future[T])(implicit ec: ExecutionContext) : Future[T] = timeMeasurement.measuring(actionFun)

  protected def tags: Map[String, String] = Map()

  protected def serviceName: String

}

class AsyncExecutionTimeMeasurement(context: EngineRuntimeContext,
                                    serviceName: String,
                                    tags: Map[String, String],
                                    instantTimerWindow: Duration = 20 seconds) extends LazyLogging {

  protected def metricName: NonEmptyList[String] = NonEmptyList.of("service")

  //TODO: add metrics eagerly during open, so that we don't need this map
  private val metrics = new SafeLazyValues[String, EspTimer]

  def measuring[T](actionFun: => Future[T])(implicit ec: ExecutionContext) : Future[T] = {
    measuring(tags)(actionFun)
  }

  def measuring[T](tags: Map[String, String])(actionFun: => Future[T])(implicit ec: ExecutionContext) : Future[T] = {
    val start = System.nanoTime()
    //we use transform instead of onComplete, so we don't e.g. measure wrong value when onComplete waits due to contention...)
    //(also tests are difficult to get right then)
    actionFun.transform { result =>
      detectMeterName(result).foreach { meterName =>
        getOrCreateTimer(tags, meterName).update(start)
      }
      result
    }
  }

  protected def detectMeterName(result: Try[Any]) : Option[String] = result match {
    case Success(_) => Some("OK")
    case Failure(_) => Some("FAIL")
  }

  private def getOrCreateTimer(tags: Map[String, String], meterType: String) : EspTimer = {
    metrics.getOrCreate(meterType, () => espTimer(tags + ("serviceName" -> serviceName), metricName :+ meterType))
  }

  def espTimer(tags: Map[String, String], name: NonEmptyList[String]): EspTimer = {
    //TODO: so far in ServiceQuery we don't do open(...) because there's no RuntimeContext
    //we should make it nicer than below, but it's still better than throwing NullPointerException
    if (context == null) {
      logger.info("open not called on TimeMeasuringService - is it ServiceQuery? Using dummy timer")
      EspTimer(() => (), _ => {})
    } else {
      context.metricsProvider.espTimer(MetricIdentifier(name, tags), instantTimerWindow.toSeconds)
    }
  }

}


text:
(function(){
    "use strict";

    //create a new angular app and declare it's dependency on a module
    var app = angular.module('app', ['advaricsModule']);

}());


text:
Drawille for Ruby
========
[![Gem Version](https://badge.fury.io/rb/drawille.svg)](http://badge.fury.io/rb/drawille)

Draw in your terminal with Unicode [Braille][] characters. Implementation based on [drawille][] by @asciimoo.

[Braille]: http://en.wikipedia.org/wiki/Braille
[Drawille]: https://github.com/asciimoo/drawille

## Installation

Add this line to your application's Gemfile:

    gem 'drawille'

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install drawille

## Usage

Drawille can be used like the Python implementation due to the similar API. Here is one of its examples:

```ruby
require 'drawille'

canvas = Drawille::Canvas.new

(0..1800).step(10).each do |x|
  canvas.set(x/10, 10 + Math.sin(x * Math::PI / 180) * 10)
end

puts canvas.frame
```

![Sinus](docs/images/sinus.gif)

But in the end you can use it in every possible situation where you have only two colors. This means it is perfect for some stencil graffitis.

```ruby
require 'drawille'
require 'chunky_png'

include ChunkyPNG

canvas = Drawille::Canvas.new

def draw canvas, img, xoffset=0
  (0..img.dimension.width-1).each do |x|
    (0..img.dimension.height-1).each do |y|
      r = Color.r(img[x,y])
      g = Color.g(img[x,y])
      b = Color.b(img[x,y])
      canvas.set(x+xoffset, y) if (r + b + g) > 100
    end
  end
end

draw canvas, Image.from_file('examples/stencil-1.png')
draw canvas, Image.from_file('examples/stencil-2.jpg'), 141

puts canvas.frame
```

![Stencil](docs/images/stencil.gif)

With a "flipbook" you can also create animations on your terminal.

![Conway](docs/images/conway.gif)

This implementation also includes a [Turtle graphics](http://en.wikipedia.org/wiki/Turtle_graphics) API for all your beloved fractals:

```ruby
require 'drawille'

canvas = Drawille::Canvas.new

frame = canvas.paint do
  move 300, 300
  down

  36.times do
    right 10
    36.times do
      right 10
      forward 8
    end
  end

end.frame

puts frame
```

![MN-gon](docs/images/mn-gon.gif)

### Turtle-API

```ruby
  canvas = Drawille::Canvas.new
  canvas.paint do
    # Move your brush with the following commands
  end
```

``forward 10`` or ``fw 10``

Moves your brush in the current direction (default is 0 which points to the right). Please note that your brush has to be set down to actually draw.

``back 10`` or ``bk 10``

Moves your brush in the opposite direction. Please note that your brush has to be set down to actually draw.

``right 90`` or ``rt 90``

Turn the direction of the brush by 90 degrees to the right.

``left 90`` or ``lt 90``

Turn the direction of the brush by 90 degrees to the left.

``up`` or ``pu``

Sets the brush up which means all following operations will have no effect on the canvas itself.

``down`` or ``pd``

Sets the drush down which means that moving the brush will draw a stroke.

``move 100, 100`` or ``mv 100, 100``

Moves the brush to the position ``x=100`` and ``y=100``.

``line from: [30, 20], to: [100, 100]``

A line between the two given points will be drawn. The movement to the starting point will be with an ``up`` brush, but the former state of the brush will be restored after this line.

### ``Drawille::Canvas`` API

``#set(x, y)`` / ``#[x, y] = true``

Sets the state of the given position to ``true``, i.e. the ``#frame`` method will render a point at ``[x,y]``.

``#unset(x, y)`` / ``#[x, y] = false``

Sets the state of the given position to ``false``, i.e. the ``#frame`` method will _not_ render a point at ``[x,y]``.

``#toggle(x, y)``

Toggles the state of the given position.

``#clear``

No point will be rendered by the ``#frame`` method.

``#frame``

Returns newline-delimited string of the given canvas state. Braille characters are used to represent points. Please note that a single character contains 2 x 4 pixels.

### Flip-book

```ruby
c = Drawille::Canvas.new
f = Drawille::FlipBook.new

c.paint do
  move 200, 100
  down

  36.times do
    right 10
    36.times do
      right 10
      forward 8
    end
    f.snapshot canvas
  end

end

f.play repeat: true, fps: 6
```

With the flip-book it is possible to create and play animations. Just draw on the canvas as usual and create a snapshot for every frame you want to be included in the animation.

``FlipBook#snapshot canvas``

Saves a snapshot of the current state of the canvas.

``FlipBook#snapshot#play``

Will render the animation on the terminal. The method also takes an option hash with the options ``:repeat`` ``:fps``.

As an alternative to snapshots it is possible to pass a block which will be called consecutively and should return a canvas which will be rendered as a frame in the animation or ``nil`` to stop the animation.

## License

MIT License

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


text: .hello{color: red;}


text:
/* SoundfileDeviceTest.h from libstand http://github.com/qtau-devgroup/libstand by Hal@shurabaP, BSD license */
#ifndef SOUNDFILEDEVICETEST_H
#define SOUNDFILEDEVICETEST_H

#include <QTest>
#include <QBuffer>
#include "util/SoundfileDevice.h"

#include "AutoTest.h"

namespace stand
{

class SoundfileDeviceTest : public QObject
{
    Q_OBJECT
private slots:
    void write_and_read_properly_in()
    {
        int format = SF_FORMAT_WAV | SF_FORMAT_PCM_16;

        QList<Signal> signalList;
        Signal signal(22050);
        for(int i = 0; i < signal.size(); i++)
        {
            signal[i] = (i % 256) / 512.0;
        }
        signalList.append(signal);
        signalList.append(signal);

        QSharedPointer<QBuffer> buffer = QSharedPointer<QBuffer>(new QBuffer());

        QCOMPARE(SoundfileDevice().write(signalList, format, buffer), true);

        auto actual = (SoundfileDevice().read(buffer));
        QCOMPARE(actual, signalList);
        for(int i = 0; i < actual.size(); i++)
        {
            QCOMPARE(actual[i].samplingFrequency(), signalList[i].samplingFrequency());
        }
    }
};

}

DECLARE_TEST(stand::SoundfileDeviceTest)

#endif // SOUNDFILEDEVICETEST_H


text:
package org.elasticsearch.test.rest.yaml.section;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.elasticsearch.common.collect.Tuple;
import org.elasticsearch.common.xcontent.XContentLocation;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.test.NotEqualMessageBuilder;

import java.io.IOException;
import java.util.regex.Pattern;

import static org.elasticsearch.test.hamcrest.RegexMatcher.matches;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.instanceOf;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;

/**
 * Represents a match assert section:
 *
 *   - match:   { get.fields._routing: "5" }
 *
 */
public class MatchAssertion extends Assertion {
    public static MatchAssertion parse(XContentParser parser) throws IOException {
        XContentLocation location = parser.getTokenLocation();
        Tuple<String,Object> stringObjectTuple = ParserUtils.parseTuple(parser);
        return new MatchAssertion(location, stringObjectTuple.v1(), stringObjectTuple.v2());
    }

    private static final Logger logger = LogManager.getLogger(MatchAssertion.class);

    public MatchAssertion(XContentLocation location, String field, Object expectedValue) {
        super(location, field, expectedValue);
    }

    @Override
    protected void doAssert(Object actualValue, Object expectedValue) {
        //if the value is wrapped into / it is a regexp (e.g. /s+d+/)
        if (expectedValue instanceof String) {
            String expValue = ((String) expectedValue).trim();
            if (expValue.length() > 2 && expValue.startsWith("/") && expValue.endsWith("/")) {
                assertThat("field [" + getField() + "] was expected to be of type String but is an instanceof [" +
                        safeClass(actualValue) + "]", actualValue, instanceOf(String.class));
                String stringValue = (String) actualValue;
                String regex = expValue.substring(1, expValue.length() - 1);
                logger.trace("assert that [{}] matches [{}]", stringValue, regex);
                assertThat("field [" + getField() + "] was expected to match the provided regex but didn't",
                        stringValue, matches(regex, Pattern.COMMENTS));
                return;
            }
        }

        logger.trace("assert that [{}] matches [{}] (field [{}])", actualValue, expectedValue, getField());
        if (expectedValue == null) {
            assertNull("field [" + getField() + "] should be null but was [" + actualValue + "]", actualValue);
            return;
        }
        assertNotNull("field [" + getField() + "] is null", actualValue);

        if (actualValue.getClass().equals(safeClass(expectedValue)) == false) {
            if (actualValue instanceof Number && expectedValue instanceof Number) {
                //Double 1.0 is equal to Integer 1
                assertThat("field [" + getField() + "] doesn't match the expected value",
                        ((Number) actualValue).doubleValue(), equalTo(((Number) expectedValue).doubleValue()));
                return;
            }
        }

        if (expectedValue.equals(actualValue) == false) {
            NotEqualMessageBuilder message = new NotEqualMessageBuilder();
            message.compare(getField(), actualValue, expectedValue);
            throw new AssertionError(getField() + " didn't match expected value:\n" + message);
        }
    }
}


text:
require "rails_helper"

module HotDrinks
  RSpec.describe MachinesController, type: :routing do
    describe "routing" do

      it "routes to #index" do
        expect(:get => "/machines").to route_to("machines#index")
      end

      it "routes to #new" do
        expect(:get => "/machines/new").to route_to("machines#new")
      end

      it "routes to #show" do
        expect(:get => "/machines/1").to route_to("machines#show", :id => "1")
      end

      it "routes to #edit" do
        expect(:get => "/machines/1/edit").to route_to("machines#edit", :id => "1")
      end

      it "routes to #create" do
        expect(:post => "/machines").to route_to("machines#create")
      end

      it "routes to #update via PUT" do
        expect(:put => "/machines/1").to route_to("machines#update", :id => "1")
      end

      it "routes to #update via PATCH" do
        expect(:patch => "/machines/1").to route_to("machines#update", :id => "1")
      end

      it "routes to #destroy" do
        expect(:delete => "/machines/1").to route_to("machines#destroy", :id => "1")
      end

    end
  end
end


text:
module.exports = function ({ $incremental, $lookup }) {
    return {
        object: function () {
            return function () {
                return function ($buffer, $start, $end) {
                    let object = {
                        nudge: 0,
                        value: 0,
                        sentry: 0
                    }

                    if ($end - $start < 4) {
                        return $incremental.object(object, 1)($buffer, $start, $end)
                    }

                    object.nudge = $buffer[$start++]

                    object.value =
                        ($buffer[$start++] & 0x7f) << 7 |
                        $buffer[$start++]

                    object.sentry = $buffer[$start++]

                    return { start: $start, object: object, parse: null }
                }
            } ()
        }
    }
}


text:
import sys
import lldb
from weakref import WeakValueDictionary

#	This is manual object management.
#	Only objects registered here can be transferred to remote process.
ID_TO_OBJ_MAP	=	WeakValueDictionary()

#	Protocol Summary
#	----------------
#	Processes line-by-line.
#	Single REQUEST must make a single RESPONSE.
#	REQUESTer must wait for a RESPONSE.

#	Object transmission
#	-------------------
#
#	There're two type of objects.
#
#	-	Values. Transmitted by copy. `VALUE:<type>:<expr>`
#	-	Objects. Transmitted by ref. `ID:<number>`

def readCall():

def	writeError(msg):
	print("RESPONSE:ERROR:" + msg)

def	writeOK(tobjexpr):
	print("RESPONSE:OK:" + tobjexpr)

def	decodeValue(x):

def	decodeObject(idnum):
	ID_TO_OBJ_MAP[idnum]

def	decodeTOBJ(x):

def	unregisterObjectForID(id):
	ID_TO_OBJ_MAP[id]	=	None

def	transForID(id):
	ID_TO_OBJ_MAP[id]

def	encodeObjectIntoTransmissionExpression(o):
	if o == None:
		return	"NoneType::"

	idnum	=	id(temp)
	if ID_TO_OBJ_MAP[idnum] == None:
		ID_TO_OBJ_MAP[id(o)]	=	o

	return	o.__class__.__name__ + ":" + idnum + ":" + o

def	decodeObjectFromTransmissionExpression(x):
	if x == "NoneType::":
		return	None

	ps			=	x.split(":",2)
	typename	=	ps[0]
	idnum		=	ps[1]
	expr		=	ps[2]

	return	ID_TO_OBJ_MAP[int(idnum)]

#	if idnum == "":
#		return	ID_TO_OBJ_MAP[int(idnum)]
#
#	else:
#		return	eval(ps[0])(ps[2])

def	callInstanceMethodFromSwift(self, methodName, argExpressionList):
	temp	=	getattr(self, methodName)(*args)
	idnum	=	id(temp)
	ID_TO_OBJ_MAP[id(temp)]	=	temp
	return	temp.__class__.__name__ + ":" + idnum  + ":" + temp

while True:
	exec(sys.stdin.readline())
	sys.stdout.flush()


text:
@extends('site.layouts.default')

{{-- Web site Title --}}
@section('title')
{{{ String::title($post->title) }}} ::
@parent
@stop

{{-- Update the Meta Title --}}
@section('meta_title')
@parent

@stop

{{-- Update the Meta Description --}}
@section('meta_description')
@parent

@stop

{{-- Update the Meta Keywords --}}
@section('meta_keywords')
@parent

@stop

{{-- Content --}}
@section('content')

{{ $post->title }}

{{ $post->content() }}

	Posted {{{ $post->date() }}}

{{{ $comments->count() }}} Comments

@if ($comments->count())
@foreach ($comments as $comment)

				{{{ $comment->author->username }}}
				•
				{{{ $comment->date() }}}

				{{{ $comment->content() }}}

@endforeach
@else

@endif

@if ( ! Auth::check())
You need to be logged in to add comments.

Click here to login into your account.
@elseif ( ! $canComment )
You don't have the correct permissions to add comments.
@else

Add a Comment

<form method="post" action="{{{ URL::to($post->slug) }}}">
	<input type="hidden" name="_token" value="{{{ Session::getToken() }}}" />

	<textarea class="input-block-level" rows="4" name="comment" id="comment">{{{ Request::old('comment') }}}</textarea>

			<input type="submit" class="btn" id="submit" value="Submit" />

</form>
@endif
@stop


text:
package com.guestful.json.groovy;

import groovy.json.JsonLexer;
import groovy.json.JsonToken;
import groovy.json.internal.Chr;
import org.codehaus.groovy.runtime.DefaultGroovyMethods;

import javax.json.JsonException;
import javax.json.JsonValue;
import java.io.StringReader;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @author Mathieu Carbou (mathieu.carbou@gmail.com)
 */
public class JsonWriter {

    private static final char[] EMPTY_MAP_CHARS = {'{', '}'};
    private static final char[] EMPTY_LIST_CHARS = {'[', ']'};
    private static final char[] EMPTY_STRING_CHARS = Chr.array('"', '"');

    private final CharBuf buffer = CharBuf.create(255);

    private final SerializerRepository serializerRepository;
    private final boolean ignoreMapNullValues;

    public JsonWriter(SerializerRepository serializerRepository, boolean ignoreMapNullValues) {
        this.serializerRepository = serializerRepository;
        this.ignoreMapNullValues = ignoreMapNullValues;
    }

    public JsonWriter writeEscapedString(char[] chars) {
        if (chars.length > 0) {
            buffer.addJsonEscapedString(chars);
        } else {
            buffer.addChars(EMPTY_STRING_CHARS);
        }
        return this;
    }

    public JsonWriter writeEscapedString(CharSequence s) {
        if (s.length() > 0) {
            buffer.addJsonEscapedString(s.toString());
        } else {
            buffer.addChars(EMPTY_STRING_CHARS);
        }
        return this;
    }

    public JsonWriter writeRaw(String s) {
        buffer.add(s);
        return this;
    }

    public JsonWriter writeString(CharSequence s) {
        if (s.length() > 0) {
            buffer.addQuoted(s.toString());
        } else {
            buffer.addChars(EMPTY_STRING_CHARS);
        }
        return this;
    }

    public JsonWriter writeBoolean(Boolean o) {
        buffer.addBoolean(o);
        return this;
    }

    public JsonWriter writeDouble(Double key) {
        buffer.addDouble(key);
        return this;
    }

    public JsonWriter writeFloat(Float key) {
        buffer.addFloat(key);
        return this;
    }

    public JsonWriter writeInt(Integer key) {
        buffer.addInt(key);
        return this;
    }

    public JsonWriter writeShort(Short key) {
        buffer.addShort(key);
        return this;
    }

    public JsonWriter writeByte(Byte key) {
        buffer.addByte(key);
        return this;
    }

    public JsonWriter writeLong(Long key) {
        buffer.addLong(key);
        return this;
    }

    public JsonWriter writeBigInteger(BigInteger key) {
        buffer.addBigInteger(key);
        return this;
    }

    public JsonWriter writeBigDecimal(BigDecimal key) {
        buffer.addBigDecimal(key);
        return this;
    }

    public JsonWriter writeNull() {
        buffer.addNull();
        return this;
    }

    public JsonWriter writeJsonValue(JsonValue o) {
        buffer.add(o.toString());
        return this;
    }

    public JsonWriter writeIterator(Iterator<?> o) {
        if (o.hasNext()) {
            buffer.addChar('[');
            Object it = o.next();
            writeObject(it);
            while (o.hasNext()) {
                it = o.next();
                buffer.addChar(',');
                writeObject(it);
            }
            buffer.addChar(']');
        } else {
            buffer.addChars(EMPTY_LIST_CHARS);
        }
        return this;
    }

    public JsonWriter writeArray(Object array) {
        Class<?> arrayClass = array.getClass();
        if (!arrayClass.isArray()) {
            throw new JsonException("not an array: " + arrayClass);
        }
        buffer.addChar('[');
        if (Object[].class.isAssignableFrom(arrayClass)) {
            Object[] objArray = (Object[]) array;
            if (objArray.length > 0) {
                writeObject(objArray[0]);
                for (int i = 1; i < objArray.length; i++) {
                    buffer.addChar(',');
                    writeObject(objArray[i]);
                }
            }
        } else if (int[].class.isAssignableFrom(arrayClass)) {
            int[] intArray = (int[]) array;
            if (intArray.length > 0) {
                buffer.addInt(intArray[0]);
                for (int i = 1; i < intArray.length; i++) {
                    buffer.addChar(',').addInt(intArray[i]);
                }
            }
        } else if (long[].class.isAssignableFrom(arrayClass)) {
            long[] longArray = (long[]) array;
            if (longArray.length > 0) {
                buffer.addLong(longArray[0]);
                for (int i = 1; i < longArray.length; i++) {
                    buffer.addChar(',').addLong(longArray[i]);
                }
            }
        } else if (boolean[].class.isAssignableFrom(arrayClass)) {
            boolean[] booleanArray = (boolean[]) array;
            if (booleanArray.length > 0) {
                buffer.addBoolean(booleanArray[0]);
                for (int i = 1; i < booleanArray.length; i++) {
                    buffer.addChar(',').addBoolean(booleanArray[i]);
                }
            }
        } else if (char[].class.isAssignableFrom(arrayClass)) {
            char[] charArray = (char[]) array;
            if (charArray.length > 0) {
                buffer.addJsonEscapedString(Chr.array(charArray[0]));
                for (int i = 1; i < charArray.length; i++) {
                    buffer.addChar(',').addJsonEscapedString(Chr.array(charArray[i]));
                }
            }
        } else if (double[].class.isAssignableFrom(arrayClass)) {
            double[] doubleArray = (double[]) array;
            if (doubleArray.length > 0) {
                buffer.addDouble(doubleArray[0]);
                for (int i = 1; i < doubleArray.length; i++) {
                    buffer.addChar(',').addDouble(doubleArray[i]);
                }
            }
        } else if (float[].class.isAssignableFrom(arrayClass)) {
            float[] floatArray = (float[]) array;
            if (floatArray.length > 0) {
                buffer.addFloat(floatArray[0]);
                for (int i = 1; i < floatArray.length; i++) {
                    buffer.addChar(',').addFloat(floatArray[i]);
                }
            }
        } else if (byte[].class.isAssignableFrom(arrayClass)) {
            byte[] byteArray = (byte[]) array;
            if (byteArray.length > 0) {
                buffer.addByte(byteArray[0]);
                for (int i = 1; i < byteArray.length; i++) {
                    buffer.addChar(',').addByte(byteArray[i]);
                }
            }
        } else if (short[].class.isAssignableFrom(arrayClass)) {
            short[] shortArray = (short[]) array;
            if (shortArray.length > 0) {
                buffer.addShort(shortArray[0]);
                for (int i = 1; i < shortArray.length; i++) {
                    buffer.addChar(',').addShort(shortArray[i]);
                }
            }
        } else {
            throw new JsonException("Cannot serialize array: " + Arrays.deepToString((Object[]) array));
        }
        buffer.addChar(']');
        return this;
    }

    public JsonWriter writeMap(Map<?, ?> o) {
        if (!o.isEmpty()) {
            buffer.addChar('{');
            boolean firstItem = true;
            for (Map.Entry<?, ?> entry : o.entrySet()) {
                if (ignoreMapNullValues && entry.getValue() == null) {
                    continue;
                }
                if (entry.getKey() == null) {
                    throw new IllegalArgumentException("Maps with null keys can\'t be converted to JSON");
                }
                if (!firstItem) {
                    buffer.addChar(',');
                } else {
                    firstItem = false;
                }
                buffer.addJsonFieldName(entry.getKey().toString());
                writeObject(entry.getValue());
            }
            buffer.addChar('}');
        } else {
            buffer.addChars(EMPTY_MAP_CHARS);
        }
        return this;
    }

    @Override
    public String toString() {
        return toString(false);
    }

    public String toString(boolean pretty) {
        return pretty ? prettyPrint(buffer.toString()) : buffer.toString();
    }

    public JsonWriter writeObject(Object object) {
        if (object == null) {
            buffer.addNull();
        } else {
            Class<?> objectClass = object.getClass();
            JsonTypeSerializer<Object> serializer = serializerRepository.findSerializer(objectClass);
            if (serializer != null) {
                serializer.write(object, this);
            } else if (objectClass.isArray()) {
                writeArray(object);
            } else {
                Map<?, ?> properties = DefaultGroovyMethods.getProperties(object);
                properties.remove("class");
                properties.remove("declaringClass");
                properties.remove("metaClass");
                writeMap(properties);
            }
        }
        return this;
    }

    @SuppressWarnings("ConstantConditions")
    private static String prettyPrint(String jsonPayload) {
        int indentSize = 0;
        // Just a guess that the pretty view will take a 20 percent more than original.
        final groovy.json.internal.CharBuf output = groovy.json.internal.CharBuf.create((int) (jsonPayload.length() * 0.2));

        JsonLexer lexer = new JsonLexer(new StringReader(jsonPayload));
        // Will store already created indents.
        Map<Integer, char[]> indentCache = new HashMap<>();
        while (lexer.hasNext()) {
            JsonToken token = lexer.next();
            switch (token.getType()) {
                case OPEN_CURLY:
                    indentSize += 4;
                    output.addChars(Chr.array('{', '\n')).addChars(getIndent(indentSize, indentCache));

                    break;
                case CLOSE_CURLY:
                    indentSize -= 4;
                    output.addChar('\n');
                    if (indentSize > 0) {
                        output.addChars(getIndent(indentSize, indentCache));
                    }
                    output.addChar('}');

                    break;
                case OPEN_BRACKET:
                    indentSize += 4;
                    output.addChars(Chr.array('[', '\n')).addChars(getIndent(indentSize, indentCache));

                    break;
                case CLOSE_BRACKET:
                    indentSize -= 4;
                    output.addChar('\n');
                    if (indentSize > 0) {
                        output.addChars(getIndent(indentSize, indentCache));
                    }
                    output.addChar(']');

                    break;
                case COMMA:
                    output.addChars(Chr.array(',', '\n')).addChars(getIndent(indentSize, indentCache));

                    break;
                case COLON:
                    output.addChars(Chr.array(':', ' '));

                    break;
                case STRING:
                    String textStr = token.getText();
                    String textWithoutQuotes = textStr.substring(1, textStr.length() - 1);
                    if (textWithoutQuotes.length() > 0) {
                        output.addJsonEscapedString(textWithoutQuotes);
                    } else {
                        output.addQuoted(Chr.array());
                    }

                    break;
                default:
                    output.addString(token.getText());
            }
        }

        return output.toString();
    }

    private static char[] getIndent(int indentSize, Map<Integer, char[]> indentCache) {
        char[] indent = indentCache.get(indentSize);
        if (indent == null) {
            indent = new char[indentSize];
            Arrays.fill(indent, ' ');
            indentCache.put(indentSize, indent);
        }

        return indent;
    }

}


text:
example
=======

example base on beego


text:
@interface RecruitThings : SPSprite

+(RecruitThings*) getInstance;
-(void)initWithObjectsToRecruit: (NSArray*)objectsToRecruit;
-(void) setPossibleTradeRecruits: (NSArray*) arr;

@end


text:
#include "hal.h"
#include "ch_test.h"
#include "test_root.h"

/**
 * @file    test_sequence_005.c
 * @brief   Test Sequence 005 code.
 *
 * @page test_sequence_005 [5] Counter and Binary Semaphores
 *
 * File: @ref test_sequence_005.c
 *
 *
Description

 * This sequence tests the ChibiOS/RT functionalities related to
 * counter semaphores.
 *
 *
Conditions

 * This sequence is only executed if the following preprocessor condition
 * evaluates to true:
 * - CH_CFG_USE_SEMAPHORES
 * .
 *
 *
Test Cases

 * - @subpage test_005_001
 * - @subpage test_005_002
 * - @subpage test_005_003
 * - @subpage test_005_004
 * - @subpage test_005_005
 * - @subpage test_005_006
 * .
 */

#if (CH_CFG_USE_SEMAPHORES) || defined(__DOXYGEN__)

/****************************************************************************
 * Shared code.
 ****************************************************************************/

#include "ch.h"

static semaphore_t sem1;

static THD_FUNCTION(thread1, p) {

  chSemWait(&sem1);
  test_emit_token(*(char *)p);
}

static THD_FUNCTION(thread2, p) {

  (void)p;
  chThdSleepMilliseconds(50);
  chSysLock();
  chSemSignalI(&sem1); /* For coverage reasons */
  chSchRescheduleS();
  chSysUnlock();
}

static THD_FUNCTION(thread3, p) {

  (void)p;
  chSemWait(&sem1);
  chSemSignal(&sem1);
}

static THD_FUNCTION(thread4, p) {

  chBSemSignal((binary_semaphore_t *)p);
}

/****************************************************************************
 * Test cases.
 ****************************************************************************/

/**
 * @page test_005_001 [5.1] Semaphore primitives, no state change
 *
 *
Description

 * Wait, Signal and Reset primitives are tested. The testing thread
 * does not trigger a state change.
 *
 *
Test Steps

 * - [5.1.1] The function chSemWait() is invoked, after return the
 *   counter and the returned message are tested.
 * - [5.1.2] The function chSemSignal() is invoked, after return the
 *   counter is tested.
 * - [5.1.3] The function chSemReset() is invoked, after return the
 *   counter is tested.
 * .
 */

static void test_005_001_setup(void) {
  chSemObjectInit(&sem1, 1);
}

static void test_005_001_teardown(void) {
  chSemReset(&sem1, 0);
}

static void test_005_001_execute(void) {

  /* [5.1.1] The function chSemWait() is invoked, after return the
     counter and the returned message are tested.*/
  test_set_step(1);
  {
    msg_t msg;

    msg = chSemWait(&sem1);
    test_assert_lock(chSemGetCounterI(&sem1) == 0, "wrong counter value");
    test_assert(MSG_OK == msg, "wrong returned message");
  }

  /* [5.1.2] The function chSemSignal() is invoked, after return the
     counter is tested.*/
  test_set_step(2);
  {
    chSemSignal(&sem1);
    test_assert_lock(chSemGetCounterI(&sem1) == 1, "wrong counter value");
  }

  /* [5.1.3] The function chSemReset() is invoked, after return the
     counter is tested.*/
  test_set_step(3);
  {
    chSemReset(&sem1, 2);
    test_assert_lock(chSemGetCounterI(&sem1) == 2, "wrong counter value");
  }
}

static const testcase_t test_005_001 = {
  "Semaphore primitives, no state change",
  test_005_001_setup,
  test_005_001_teardown,
  test_005_001_execute
};

/**
 * @page test_005_002 [5.2] Semaphore enqueuing test
 *
 *
Description

 * Five threads with randomized priorities are enqueued to a semaphore
 * then awakened one at time. The test expects that the threads reach
 * their goal in FIFO order or priority order depending on the @p
 * CH_CFG_USE_SEMAPHORES_PRIORITY configuration setting.
 *
 *
Test Steps

 * - [5.2.1] Five threads are created with mixed priority levels (not
 *   increasing nor decreasing). Threads enqueue on a semaphore
 *   initialized to zero.
 * - [5.2.2] The semaphore is signaled 5 times. The thread activation
 *   sequence is tested.
 * .
 */

static void test_005_002_setup(void) {
  chSemObjectInit(&sem1, 0);
}

static void test_005_002_execute(void) {

  /* [5.2.1] Five threads are created with mixed priority levels (not
     increasing nor decreasing). Threads enqueue on a semaphore
     initialized to zero.*/
  test_set_step(1);
  {
    threads[0] = chThdCreateStatic(wa[0], WA_SIZE, chThdGetPriorityX()+5, thread1, "A");
    threads[1] = chThdCreateStatic(wa[1], WA_SIZE, chThdGetPriorityX()+1, thread1, "B");
    threads[2] = chThdCreateStatic(wa[2], WA_SIZE, chThdGetPriorityX()+3, thread1, "C");
    threads[3] = chThdCreateStatic(wa[3], WA_SIZE, chThdGetPriorityX()+4, thread1, "D");
    threads[4] = chThdCreateStatic(wa[4], WA_SIZE, chThdGetPriorityX()+2, thread1, "E");
  }

  /* [5.2.2] The semaphore is signaled 5 times. The thread activation
     sequence is tested.*/
  test_set_step(2);
  {
    chSemSignal(&sem1);
    chSemSignal(&sem1);
    chSemSignal(&sem1);
    chSemSignal(&sem1);
    chSemSignal(&sem1);
    test_wait_threads();
#if CH_CFG_USE_SEMAPHORES_PRIORITY
    test_assert_sequence("ADCEB", "invalid sequence");
#else
    test_assert_sequence("ABCDE", "invalid sequence");
#endif
  }
}

static const testcase_t test_005_002 = {
  "Semaphore enqueuing test",
  test_005_002_setup,
  NULL,
  test_005_002_execute
};

/**
 * @page test_005_003 [5.3] Semaphore timeout test
 *
 *
Description

 * The three possible semaphore waiting modes (do not wait, wait with
 * timeout, wait without timeout) are explored. The test expects that
 * the semaphore wait function returns the correct value in each of the
 * above scenario and that the semaphore structure status is correct
 * after each operation.
 *
 *
Test Steps

 * - [5.3.1] Testing special case TIME_IMMEDIATE.
 * - [5.3.2] Testing non-timeout condition.
 * - [5.3.3] Testing timeout condition.
 * .
 */

static void test_005_003_setup(void) {
  chSemObjectInit(&sem1, 0);
}

static void test_005_003_execute(void) {
  unsigned i;
  systime_t target_time;
  msg_t msg;

  /* [5.3.1] Testing special case TIME_IMMEDIATE.*/
  test_set_step(1);
  {
    msg = chSemWaitTimeout(&sem1, TIME_IMMEDIATE);
    test_assert(msg == MSG_TIMEOUT, "wrong wake-up message");
    test_assert(queue_isempty(&sem1.queue), "queue not empty");
    test_assert(sem1.cnt == 0, "counter not zero");
  }

  /* [5.3.2] Testing non-timeout condition.*/
  test_set_step(2);
  {
    threads[0] = chThdCreateStatic(wa[0], WA_SIZE, chThdGetPriorityX() - 1,
                                   thread2, 0);
    msg = chSemWaitTimeout(&sem1, MS2ST(500));
    test_wait_threads();
    test_assert(msg == MSG_OK, "wrong wake-up message");
    test_assert(queue_isempty(&sem1.queue), "queue not empty");
    test_assert(sem1.cnt == 0, "counter not zero");
  }

  /* [5.3.3] Testing timeout condition.*/
  test_set_step(3);
  {
    target_time = test_wait_tick() + MS2ST(5 * 50);
    for (i = 0; i < 5; i++) {
      test_emit_token('A' + i);
      msg = chSemWaitTimeout(&sem1, MS2ST(50));
      test_assert(msg == MSG_TIMEOUT, "wrong wake-up message");
      test_assert(queue_isempty(&sem1.queue), "queue not empty");
      test_assert(sem1.cnt == 0, "counter not zero");
    }
    test_assert_sequence("ABCDE", "invalid sequence");
    test_assert_time_window(target_time, target_time + ALLOWED_DELAY,
                            "out of time window");
  }
}

static const testcase_t test_005_003 = {
  "Semaphore timeout test",
  test_005_003_setup,
  NULL,
  test_005_003_execute
};

/**
 * @page test_005_004 [5.4] Testing chSemAddCounterI() functionality
 *
 *
Description

 * The functon is tested by waking up a thread then the semaphore
 * counter value is tested.
 *
 *
Test Steps

 * - [5.4.1] A thread is created, it goes to wait on the semaphore.
 * - [5.4.2] The semaphore counter is increased by two, it is then
 *   tested to be one, the thread must have completed.
 * .
 */

static void test_005_004_setup(void) {
  chSemObjectInit(&sem1, 0);
}

static void test_005_004_execute(void) {

  /* [5.4.1] A thread is created, it goes to wait on the semaphore.*/
  test_set_step(1);
  {
    threads[0] = chThdCreateStatic(wa[0], WA_SIZE, chThdGetPriorityX()+1, thread1, "A");
  }

  /* [5.4.2] The semaphore counter is increased by two, it is then
     tested to be one, the thread must have completed.*/
  test_set_step(2);
  {
    chSysLock();
    chSemAddCounterI(&sem1, 2);
    chSchRescheduleS();
    chSysUnlock();
    test_wait_threads();
    test_assert_lock(chSemGetCounterI(&sem1) == 1, "invalid counter");
    test_assert_sequence("A", "invalid sequence");
  }
}

static const testcase_t test_005_004 = {
  "Testing chSemAddCounterI() functionality",
  test_005_004_setup,
  NULL,
  test_005_004_execute
};

/**
 * @page test_005_005 [5.5] Testing chSemWaitSignal() functionality
 *
 *
Description

 * This test case explicitly addresses the @p chSemWaitSignal()
 * function. A thread is created that performs a wait and a signal
 * operations. The tester thread is awakened from an atomic wait/signal
 * operation. The test expects that the semaphore wait function returns
 * the correct value in each of the above scenario and that the
 * semaphore structure status is correct after each operation.
 *
 *
Test Steps

 * - [5.5.1] An higher priority thread is created that performs
 *   non-atomical wait and signal operations on a semaphore.
 * - [5.5.2] The function chSemSignalWait() is invoked by specifying
 *   the same semaphore for the wait and signal phases. The counter
 *   value must be one on exit.
 * - [5.5.3] The function chSemSignalWait() is invoked again by
 *   specifying the same semaphore for the wait and signal phases. The
 *   counter value must be one on exit.
 * .
 */

static void test_005_005_setup(void) {
  chSemObjectInit(&sem1, 0);
}

static void test_005_005_teardown(void) {
  test_wait_threads();
}

static void test_005_005_execute(void) {

  /* [5.5.1] An higher priority thread is created that performs
     non-atomical wait and signal operations on a semaphore.*/
  test_set_step(1);
  {
    threads[0] = chThdCreateStatic(wa[0], WA_SIZE, chThdGetPriorityX()+1, thread3, 0);
  }

  /* [5.5.2] The function chSemSignalWait() is invoked by specifying
     the same semaphore for the wait and signal phases. The counter
     value must be one on exit.*/
  test_set_step(2);
  {
    chSemSignalWait(&sem1, &sem1);
    test_assert(queue_isempty(&sem1.queue), "queue not empty");
    test_assert(sem1.cnt == 0, "counter not zero");
  }

  /* [5.5.3] The function chSemSignalWait() is invoked again by
     specifying the same semaphore for the wait and signal phases. The
     counter value must be one on exit.*/
  test_set_step(3);
  {
    chSemSignalWait(&sem1, &sem1);
    test_assert(queue_isempty(&sem1.queue), "queue not empty");
    test_assert(sem1.cnt == 0, "counter not zero");
  }
}

static const testcase_t test_005_005 = {
  "Testing chSemWaitSignal() functionality",
  test_005_005_setup,
  test_005_005_teardown,
  test_005_005_execute
};

/**
 * @page test_005_006 [5.6] Testing Binary Semaphores special case
 *
 *
Description

 * This test case tests the binary semaphores functionality. The test
 * both checks the binary semaphore status and the expected status of
 * the underlying counting semaphore.
 *
 *
Test Steps

 * - [5.6.1] Creating a binary semaphore in "taken" state, the state is
 *   checked.
 * - [5.6.2] Resetting the binary semaphore in "taken" state, the state
 *   must not change.
 * - [5.6.3] Starting a signaler thread at a lower priority.
 * - [5.6.4] Waiting for the binary semaphore to be signaled, the
 *   semaphore is expected to be taken.
 * - [5.6.5] Signaling the binary semaphore, checking the binary
 *   semaphore state to be "not taken" and the underlying counter
 *   semaphore counter to be one.
 * - [5.6.6] Signaling the binary semaphore again, the internal state
 *   must not change from "not taken".
 * .
 */

static void test_005_006_teardown(void) {
  test_wait_threads();
}

static void test_005_006_execute(void) {
  binary_semaphore_t bsem;
  msg_t msg;

  /* [5.6.1] Creating a binary semaphore in "taken" state, the state is
     checked.*/
  test_set_step(1);
  {
    chBSemObjectInit(&bsem, true);
    test_assert_lock(chBSemGetStateI(&bsem) == true, "not taken");
  }

  /* [5.6.2] Resetting the binary semaphore in "taken" state, the state
     must not change.*/
  test_set_step(2);
  {
    chBSemReset(&bsem, true);
    test_assert_lock(chBSemGetStateI(&bsem) == true, "not taken");
  }

  /* [5.6.3] Starting a signaler thread at a lower priority.*/
  test_set_step(3);
  {
    threads[0] = chThdCreateStatic(wa[0], WA_SIZE,
                                   chThdGetPriorityX()-1, thread4, &bsem);
  }

  /* [5.6.4] Waiting for the binary semaphore to be signaled, the
     semaphore is expected to be taken.*/
  test_set_step(4);
  {
    msg = chBSemWait(&bsem);
    test_assert_lock(chBSemGetStateI(&bsem) == true, "not taken");
    test_assert(msg == MSG_OK, "unexpected message");
  }

  /* [5.6.5] Signaling the binary semaphore, checking the binary
     semaphore state to be "not taken" and the underlying counter
     semaphore counter to be one.*/
  test_set_step(5);
  {
    chBSemSignal(&bsem);
    test_assert_lock(chBSemGetStateI(&bsem) ==false, "still taken");
    test_assert_lock(chSemGetCounterI(&bsem.sem) == 1, "unexpected counter");
  }

  /* [5.6.6] Signaling the binary semaphore again, the internal state
     must not change from "not taken".*/
  test_set_step(6);
  {
    chBSemSignal(&bsem);
    test_assert_lock(chBSemGetStateI(&bsem) == false, "taken");
    test_assert_lock(chSemGetCounterI(&bsem.sem) == 1, "unexpected counter");
  }
}

static const testcase_t test_005_006 = {
  "Testing Binary Semaphores special case",
  NULL,
  test_005_006_teardown,
  test_005_006_execute
};

/****************************************************************************
 * Exported data.
 ****************************************************************************/

/**
 * @brief   Counter and Binary Semaphores.
 */
const testcase_t * const test_sequence_005[] = {
  &test_005_001,
  &test_005_002,
  &test_005_003,
  &test_005_004,
  &test_005_005,
  &test_005_006,
  NULL
};

#endif /* CH_CFG_USE_SEMAPHORES */


text:
package com.mysql.binlog.event;

/**
 * @author Stanley Shyiko
 */
public class QueryEventData implements EventData {

    private long threadId;
    private long executionTime;
    private int errorCode;
    private String database;
    private String sql;

    public long getThreadId() {
        return threadId;
    }

    public void setThreadId(long threadId) {
        this.threadId = threadId;
    }

    public long getExecutionTime() {
        return executionTime;
    }

    public void setExecutionTime(long executionTime) {
        this.executionTime = executionTime;
    }

    public int getErrorCode() {
        return errorCode;
    }

    public void setErrorCode(int errorCode) {
        this.errorCode = errorCode;
    }

    public String getDatabase() {
        return database;
    }

    public void setDatabase(String database) {
        this.database = database;
    }

    public String getSql() {
        return sql;
    }

    public void setSql(String sql) {
        this.sql = sql;
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder();
        sb.append("QueryEventData");
        sb.append("{threadId=").append(threadId);
        sb.append(", executionTime=").append(executionTime);
        sb.append(", errorCode=").append(errorCode);
        sb.append(", database='").append(database).append('\'');
        sb.append(", sql='").append(sql).append('\'');
        sb.append('}');
        return sb.toString();
    }
}


text:
"""Test for the tit for tat strategies."""

import axelrod
from .test_player import TestPlayer

C, D = axelrod.Actions.C, axelrod.Actions.D

class TestTitForTat(TestPlayer):

    name = "Tit For Tat"
    player = axelrod.TitForTat
    expected_classifier = {
        'memory_depth': 1,
        'stochastic': False,
        'inspects_source': False,
        'manipulates_source': False,
        'manipulates_state': False
    }

    def test_strategy(self):
        """Starts by cooperating."""
        self.first_play_test(C)

    def test_effect_of_strategy(self):
        """Repeats last action of opponent history."""
        self.markov_test([C, D, C, D])
        self.responses_test([C] * 4, [C, C, C, C], [C])
        self.responses_test([C] * 5, [C, C, C, C, D], [D])

class TestTitFor2Tats(TestPlayer):

    name = 'Tit For 2 Tats'
    player = axelrod.TitFor2Tats
    expected_classifier = {
        'memory_depth': 2,
        'stochastic': False,
        'inspects_source': False,
        'manipulates_source': False,
        'manipulates_state': False
    }

    def test_strategy(self):
        """Starts by cooperating."""
        self.first_play_test(C)

    def test_effect_of_strategy(self):
        """Will defect only when last two turns of opponent were defections."""
        self.responses_test([C, C, C], [D, D, D], [D])
        self.responses_test([C, C, D, D], [D, D, D, C], [C])

class TestTwoTitsForTat(TestPlayer):

    name = 'Two Tits For Tat'
    player = axelrod.TwoTitsForTat
    expected_classifier = {
        'memory_depth': 2,
        'stochastic': False,
        'inspects_source': False,
        'manipulates_source': False,
        'manipulates_state': False
    }

    def test_strategy(self):
        """Starts by cooperating."""
        self.first_play_test(C)

    def test_effect_of_strategy(self):
        """Will defect twice when last turn of opponent was defection."""
        self.responses_test([C], [D], [D])
        self.responses_test([C, C], [D, D], [D])
        self.responses_test([C, C, C], [D, D, C], [D])
        self.responses_test([C, C, D, D], [D, D, C, C], [C])

class TestBully(TestPlayer):

    name = "Bully"
    player = axelrod.Bully
    expected_classifier = {
        'memory_depth': 1,
        'stochastic': False,
        'inspects_source': False,
        'manipulates_source': False,
        'manipulates_state': False
    }

    def test_strategy(self):
        """Starts by defecting"""
        self.first_play_test(D)

    def test_affect_of_strategy(self):
        """Will do opposite of what opponent does."""
        self.markov_test([D, C, D, C])

class TestSneakyTitForTat(TestPlayer):

    name = "Sneaky Tit For Tat"
    player = axelrod.SneakyTitForTat
    expected_classifier = {
        'memory_depth': float('inf'),  # Long memory
        'stochastic': False,
        'inspects_source': False,
        'manipulates_source': False,
        'manipulates_state': False
    }

    def test_strategy(self):
        """Starts by cooperating."""
        self.first_play_test(C)

    def test_effect_of_strategy(self):
        """Will try defecting after two turns of cooperation, but will stop if punished."""
        self.responses_test([C, C], [C, C], [D])
        self.responses_test([C, C, D, D], [C, C, C, D], [C])

class TestSuspiciousTitForTat(TestPlayer):

    name = 'Suspicious Tit For Tat'
    player = axelrod.SuspiciousTitForTat
    expected_classifier = {
        'memory_depth': 1, # Four-Vector = (1.,0.,1.,0.)
        'stochastic': False,
        'inspects_source': False,
        'manipulates_source': False,
        'manipulates_state': False
    }

    def test_strategy(self):
        """Starts by Defecting"""
        self.first_play_test(D)

    def test_affect_of_strategy(self):
        """Plays like TFT after the first move, repeating the opponents last move."""
        self.markov_test([C, D, C, D])

class TestAntiTitForTat(TestPlayer):

    name = 'Anti Tit For Tat'
    player = axelrod.AntiTitForTat
    expected_classifier = {
        'memory_depth': 1, # Four-Vector = (1.,0.,1.,0.)
        'stochastic': False,
        'inspects_source': False,
        'manipulates_source': False,
        'manipulates_state': False
    }

    def test_strategy(self):
        """Starts by Cooperating"""
        self.first_play_test(C)

    def test_affect_of_strategy(self):
        """Will do opposite of what opponent does."""
        self.markov_test([D, C, D, C])

class TestHardTitForTat(TestPlayer):

    name = "Hard Tit For Tat"
    player = axelrod.HardTitForTat
    expected_classifier = {
        'memory_depth': 3, # Four-Vector = (1.,0.,1.,0.)
        'stochastic': False,
        'inspects_source': False,
        'manipulates_source': False,
        'manipulates_state': False
    }

    def test_strategy(self):
        """Starts by cooperating."""
        self.first_play_test(C)

    def test_effect_of_strategy(self):
        """Repeats last action of opponent history."""
        self.responses_test([C, C, C], [C, C, C], [C])
        self.responses_test([C, C, C], [D, C, C], [D])
        self.responses_test([C, C, C], [C, D, C], [D])
        self.responses_test([C, C, C], [C, C, D], [D])
        self.responses_test([C, C, C, C], [D, C, C, C], [C])

class TestHardTitFor2Tats(TestPlayer):

    name = "Hard Tit For 2 Tats"
    player = axelrod.HardTitFor2Tats
    expected_classifier = {
        'memory_depth': 3, # Four-Vector = (1.,0.,1.,0.)
        'stochastic': False,
        'inspects_source': False,
        'manipulates_source': False,
        'manipulates_state': False
    }

    def test_strategy(self):
        """Starts by cooperating."""
        self.first_play_test(C)

    def test_effect_of_strategy(self):
        """Repeats last action of opponent history."""
        self.responses_test([C, C, C], [C, C, C], [C])
        self.responses_test([C, C, C], [D, C, C], [C])
        self.responses_test([C, C, C], [C, D, C], [C])
        self.responses_test([C, C, C], [C, C, D], [C])

        self.responses_test([C, C, C], [D, C, D], [C])
        self.responses_test([C, C, C], [D, D, C], [D])
        self.responses_test([C, C, C], [C, D, D], [D])

        self.responses_test([C, C, C, C], [D, C, C, C], [C])
        self.responses_test([C, C, C, C], [D, D, C, C], [C])
        self.responses_test([C, C, C, C], [C, D, D, C], [D])


text:
from hypothesis import given
from hypothesis.strategies import binary

from mitmproxy import options
from mitmproxy.connection import Client
from mitmproxy.proxy.context import Context
from mitmproxy.proxy.events import DataReceived
from mitmproxy.proxy.layers.modes import Socks5Proxy

opts = options.Options()
tctx = Context(Client(("client", 1234), ("127.0.0.1", 8080), 1605699329), opts)

@given(binary())
def test_socks5_fuzz(data):
    layer = Socks5Proxy(tctx)
    list(layer.handle_event(DataReceived(tctx.client, data)))