text:
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include "fdsapi.h"

#include <winpr/crt.h>
#include <winpr/wnd.h>
#include <winpr/wlog.h>
#include <winpr/pipe.h>
#include <winpr/file.h>
#include <winpr/print.h>
#include <winpr/sysinfo.h>
#include <winpr/wtsapi.h>
#include <winpr/winsock.h>

#include <freerds/rpc.h>

#include "FDSApiMessages.h"

static DWORD g_currentSessionId = 0xFFFFFFFF;

static rdsRpcClient* g_RpcClient = NULL;

static wLog* g_logger = NULL;

struct _FDSAPI_CHANNEL
{
	char* guid;
	UINT32 port;
	SOCKET socket;
	HANDLE event;
};
typedef struct _FDSAPI_CHANNEL FDSAPI_CHANNEL;

static FDSAPI_CHANNEL* FDSAPI_Channel_New()
{
	FDSAPI_CHANNEL* pChannel;

	pChannel = (FDSAPI_CHANNEL*) calloc(1, sizeof(FDSAPI_CHANNEL));

	if (pChannel)
	{

	}

	return pChannel;
}

static int FDSAPI_Channel_Connect(FDSAPI_CHANNEL* pChannel, const char* guid, UINT32 port)
{
	int status;
	int optlen = 0;
	UINT32 optval = 0;
	unsigned long addr;
	struct sockaddr_in sockAddr;

	if (strlen(guid) != 36)
		return -1001;

	pChannel->port = port;

	pChannel->guid = _strdup(guid);

	if (!pChannel->guid)
		return -1002;

	pChannel->socket = _socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

	if (pChannel->socket == INVALID_SOCKET)
		return -1003;

	addr = _inet_addr("127.0.0.1");

	sockAddr.sin_family = AF_INET;
	sockAddr.sin_addr.s_addr = addr;
	sockAddr.sin_port = htons(port);

	status = _connect(pChannel->socket, (struct sockaddr*) &sockAddr, sizeof(sockAddr));

	if (status != 0)
	{
		closesocket(pChannel->socket);
		pChannel->socket = 0;
		return -1004;
	}

	status = _send(pChannel->socket, guid, 36, 0);

	if (status != 36)
	{
		closesocket(pChannel->socket);
		pChannel->socket = 0;
		return -1005;
	}

	optval = TRUE;
	optlen = sizeof(optval);

	_setsockopt(pChannel->socket, IPPROTO_TCP, TCP_NODELAY, (char*) &optval, optlen);

	pChannel->event = CreateFileDescriptorEvent(NULL, FALSE, FALSE, (int) pChannel->socket);

	return 1;
}

static void FDSAPI_Channel_Free(FDSAPI_CHANNEL* pChannel)
{
	if (!pChannel)
		return;

	if (pChannel->socket)
	{
		closesocket(pChannel->socket);
		pChannel->socket = 0;
	}

	if (pChannel->event)
	{
		CloseHandle(pChannel->event);
		pChannel->event = NULL;
	}

	free(pChannel->guid);

	free(pChannel);
}

/*
 * Most calls result in a request/response message being sent and
 * received from the FreeRDS server.  The following code handles
 * the blocking nature of these calls in a thread-safe manner.
 * Each request is tagged with a unique request id and a response
 * is paired with the request.
 */

typedef struct
{
	HANDLE hWaitEvent;
	FDSAPI_MESSAGE* requestMsg;
	FDSAPI_MESSAGE* responseMsg;
}
FDSAPI_REQUEST_ITEM;

static UINT16 g_nextRequestId;
static wArrayList* g_activeRequestList;

static BOOL FDSAPI_SendRequest(FDSAPI_MESSAGE* requestMsg, FDSAPI_MESSAGE* responseMsg)
{
	FDSAPI_REQUEST_ITEM requestItem;
	BOOL success = FALSE;
	wStream* s = NULL;
	int status;

	ZeroMemory(&requestItem, sizeof(requestItem));

	/* Enter critical section. */
	ArrayList_Lock(g_activeRequestList);

	/* Set the request id. */
	requestMsg->requestId = g_nextRequestId++;

	/* Leave critical section. */
	ArrayList_Unlock(g_activeRequestList);

	WLog_Print(g_logger, WLOG_DEBUG, "sending request %d", requestMsg->requestId);

	/* Encode the request. */
	s = FDSAPI_EncodeMessage(requestMsg);

	if (!s)
	{
		WLog_Print(g_logger, WLOG_ERROR, "failed to encode request");
		return FALSE;
	}

	/* Add the request to the list. */
	requestItem.hWaitEvent = CreateEvent(NULL, TRUE, FALSE, NULL);

	if (!requestItem.hWaitEvent)
	{
		WLog_Print(g_logger, WLOG_ERROR, "failed to create event");
		goto EXCEPTION;
	}

	requestItem.requestMsg = requestMsg;
	requestItem.responseMsg = responseMsg;

	ArrayList_Add(g_activeRequestList, &requestItem);

	/* Send the request to the FreeRDS server. */
	status = freerds_rpc_client_send_message(g_RpcClient, Stream_Buffer(s), Stream_Length(s));

	if (status == Stream_Length(s))
	{
		WLog_Print(g_logger, WLOG_DEBUG, "waiting for response");

		/* Wait for the response. */
		WaitForSingleObject(requestItem.hWaitEvent, INFINITE);

		WLog_Print(g_logger, WLOG_DEBUG, "received response %d", responseMsg->requestId);

		/* Check for the expected response. */
		if (requestMsg->requestId == responseMsg->requestId)
		{
			success = TRUE;
		}
	}
	else
	{
		WLog_Print(g_logger, WLOG_ERROR, "failed to send request");
	}

	/* Remove the request from the list. */
	ArrayList_Remove(g_activeRequestList, &requestItem);

	CloseHandle(requestItem.hWaitEvent);

EXCEPTION:
	if (s)
	{
		Stream_Free(s, TRUE);
	}

	return success;
}

static int FDSAPI_HandleResponse(rdsRpcClient* rpcClient, FDSAPI_MESSAGE* msg)
{
	int index;
	FDSAPI_REQUEST_ITEM* requestItem;

	/* Find the matching request. */
	ArrayList_Lock(g_activeRequestList);

	for (index = 0; index < ArrayList_Count(g_activeRequestList); index++)
	{
		requestItem = (FDSAPI_REQUEST_ITEM*) ArrayList_GetItem(g_activeRequestList, index);

		if (msg->requestId == requestItem->requestMsg->requestId)
		{
			/* Wake up the requesting thread. */
			CopyMemory(requestItem->responseMsg, msg, sizeof(FDSAPI_MESSAGE));
			SetEvent(requestItem->hWaitEvent);
			break;
		}
	}

	ArrayList_Unlock(g_activeRequestList);

	return 0;
}

/**
 * As calls to WTSWaitSystemEvent and WTSRegisterSessionNotification
 * are made from various threads in the process, a list is maintained
 * of FDSAPI_SESSION_EVENT_OBSERVER structures.  Each time a session
 * event message (FDSAPI_SESSION_EVENT) is received from the FreeRDS
 * server, we need to walk through this list and deliver the session
 * event in the desired manner (either by completing the wait being
 * done in WTSWaitSystemEvent or sending a message to the HWND that
 * was registered via WTSRegisterSessionNotification).
 */

#define FDSAPI_WAIT_SYSTEM_EVENT_TYPE		1
#define FDSAPI_SESSION_NOTIFICATION_TYPE	2

typedef struct
{
	HANDLE hWaitEvent;
	DWORD dwEventMask;
	DWORD dwEventFlags;
}
FDSAPI_WAIT_SYSTEM_EVENT;

typedef struct
{
	HWND hWnd;
	DWORD dwFlags;
}
FDSAPI_SESSION_NOTIFICATION;

typedef struct
{
	int type;
	union
	{
		FDSAPI_WAIT_SYSTEM_EVENT waitSystemEvent;
		FDSAPI_SESSION_NOTIFICATION sessionNotification;
	} u;
}
FDSAPI_SESSION_EVENT_OBSERVER;

static wArrayList* g_sessionEventObserverList;
static DWORD g_sessionEventTimeDelay = 1000;
static DWORD g_sessionEventTimeStamp;

static int FDSAPI_HandleSessionEvent(rdsRpcClient* rpcClient, FDSAPI_SESSION_EVENT* sessionEvent)
{
	int index;
	DWORD sleepTime;
	FDSAPI_SESSION_EVENT_OBSERVER* observer;

	/* Enter critical section. */
	ArrayList_Lock(g_sessionEventObserverList);

	/*
	 * Wait a short period of time to allow session event observers to
	 * register.  This can happen if a WTSWaitSystemEvent gets satisfied
	 * and another session event comes in immediately.  In this case, the
	 * possibility exists that a session event could get missed.
	 */
	sleepTime = g_sessionEventTimeDelay - (GetTickCount() - g_sessionEventTimeStamp);

	if (sleepTime < g_sessionEventTimeDelay)
	{
		ArrayList_Unlock(g_sessionEventObserverList);
		Sleep(sleepTime);
		ArrayList_Lock(g_sessionEventObserverList);
	}

	/* Loop through all items in the list... */
	for (index = 0; index < ArrayList_Count(g_sessionEventObserverList); index++)
	{
		observer = (FDSAPI_SESSION_EVENT_OBSERVER*) ArrayList_GetItem(g_sessionEventObserverList, index);

		switch (observer->type)
		{
			case FDSAPI_WAIT_SYSTEM_EVENT_TYPE:
			{
				DWORD dwEventFlags = 0;

				/* Map the state change to event flags. */
				switch (sessionEvent->stateChange)
				{
					case WTS_SESSION_CREATE:
						dwEventFlags = WTS_EVENT_CREATE;
						break;

					case WTS_SESSION_TERMINATE:
						dwEventFlags = WTS_EVENT_DELETE;
						break;

					case WTS_CONSOLE_CONNECT:
					case WTS_REMOTE_CONNECT:
						dwEventFlags = WTS_EVENT_STATECHANGE | WTS_EVENT_CONNECT;
						break;

					case WTS_CONSOLE_DISCONNECT:
					case WTS_REMOTE_DISCONNECT:
						dwEventFlags = WTS_EVENT_STATECHANGE | WTS_EVENT_DISCONNECT;
						break;

					case WTS_SESSION_LOGON:
						dwEventFlags = WTS_EVENT_STATECHANGE | WTS_EVENT_LOGON;
						break;

					case WTS_SESSION_LOGOFF:
						dwEventFlags = WTS_EVENT_STATECHANGE | WTS_EVENT_LOGOFF;
						break;

					default:
						break;
				}

				/* If the event flags match the event mask... */
				if ((dwEventFlags & observer->u.waitSystemEvent.dwEventMask) != 0)
				{
					/* Save the event flags. */
					observer->u.waitSystemEvent.dwEventFlags |= dwEventFlags;

					/* Wake up the thread calling WTSWaitSystemEvent. */
					SetEvent(observer->u.waitSystemEvent.hWaitEvent);
				}

				break;
			}

			case FDSAPI_SESSION_NOTIFICATION_TYPE:
			{
				/* If the session matches a session being monitored... */
				if ((observer->u.sessionNotification.dwFlags == NOTIFY_FOR_ALL_SESSIONS) ||
				    ((observer->u.sessionNotification.dwFlags == NOTIFY_FOR_THIS_SESSION)
				        && (sessionEvent->sessionId == g_currentSessionId)))
				{
					/* Send a WM_WTSSESSION_CHANGE message to the window. */
					SendMessage(observer->u.sessionNotification.hWnd,
						WM_WTSSESSION_CHANGE,
						(WPARAM) sessionEvent->stateChange,
						(LPARAM) sessionEvent->sessionId);
				}

				break;
			}
		}
	}

	/* Update the timestamp. */
	g_sessionEventTimeStamp = GetTickCount();

	/* Leave critical section. */
	ArrayList_Unlock(g_sessionEventObserverList);

	return 0;
}

int FDSAPI_RpcConnectionClosed(rdsRpcClient* rpcClient)
{
	WLog_Print(g_logger, WLOG_DEBUG, "connection closed");

	return 0;
}

int FDSAPI_RpcMessageReceived(rdsRpcClient* rpcClient, BYTE* buffer, UINT32 length)
{
	int status;
	wStream *s;
	FDSAPI_MESSAGE msg;

	status = -1;

	WLog_Print(g_logger, WLOG_DEBUG, "message received");

	/* Allocate a stream. */
	s = Stream_New(buffer, length);

	if (!s)
	{
		WLog_Print(g_logger, WLOG_ERROR, "failed to allocate stream");
		return -1;
	}

	/* Decode the message. */
	if (FDSAPI_DecodeMessage(s, &msg))
	{
		switch (msg.messageId)
		{
			case FDSAPI_SESSION_EVENT_ID:
				status = FDSAPI_HandleSessionEvent(rpcClient, &msg.u.sessionEvent);
				break;

			default:
				status = FDSAPI_HandleResponse(rpcClient, &msg);
				break;
		}
	}
	else
	{
		WLog_Print(g_logger, WLOG_ERROR, "failed to decode message");
	}

	/* Free the stream. */
	Stream_Free(s, FALSE);

	return status;
}

static BOOL ConnectClient()
{
	if (!g_logger)
	{
		g_logger = WLog_Get("freerds.fdsapi");
	}

	if (!g_RpcClient)
	{
		WLog_Print(g_logger, WLOG_DEBUG, "connecting to FDSAPI server");

		g_activeRequestList = ArrayList_New(TRUE);
		g_sessionEventObserverList = ArrayList_New(TRUE);

		g_RpcClient = freerds_rpc_client_new("FDSAPI");
		g_RpcClient->ConnectionClosed = FDSAPI_RpcConnectionClosed;
		g_RpcClient->MessageReceived = FDSAPI_RpcMessageReceived;

		freerds_rpc_client_start(g_RpcClient);
	}

	return TRUE;
}

/**
 * Local Utility Functions
 */

static BOOL GetCurrentSessionId(LPDWORD pSessionId)
{
	char* env;

	/* If the session has been previously obtained... */
	if (g_currentSessionId != 0xFFFFFFFF)
	{
		/* Simply return it to the caller. */
		*pSessionId = g_currentSessionId;
		return TRUE;
	}

	/* The FREERDS_SID environment variable has the session id. */
	env = getenv("FREERDS_SID");

	if (env)
	{
		g_currentSessionId = atoi(env);
		*pSessionId = g_currentSessionId;
		return TRUE;
	}

	return FALSE;
}

static BOOL CheckSessionId(LPDWORD pSessionId)
{
	if (*pSessionId == WTS_CURRENT_SESSION)
	{
		return GetCurrentSessionId(pSessionId);
	}

	/**
	 * TODO: Need to do some additional checks to prevent
	 * normal users from being able to interact with other
	 * sessions.
	 */
	return TRUE;
}

/**
 * WTSAPI Public Interface
 */

BOOL WINAPI
FreeRDS_WTSStartRemoteControlSessionW(
	LPWSTR pTargetServerName,
	ULONG TargetLogonId,
	BYTE HotkeyVk,
	USHORT HotkeyModifiers
)
{
	return FALSE;
}

BOOL WINAPI
FreeRDS_WTSStartRemoteControlSessionA(
	LPSTR pTargetServerName,
	ULONG TargetLogonId,
	BYTE HotkeyVk,
	USHORT HotkeyModifiers
)
{
	return FALSE;
}

BOOL WINAPI
FreeRDS_WTSStopRemoteControlSession(
	ULONG LogonId
)
{
	return FALSE;
}

BOOL WINAPI
FreeRDS_WTSConnectSessionW(
	ULONG LogonId,
	ULONG TargetLogonId,
	PWSTR pPassword,
	BOOL bWait
)
{
	return FALSE;
}

BOOL WINAPI
FreeRDS_WTSConnectSessionA(
	ULONG LogonId,
	ULONG TargetLogonId,
	PSTR pPassword,
	BOOL bWait
)
{
	return FALSE;
}

BOOL WINAPI
FreeRDS_WTSEnumerateServersW(
	LPWSTR pDomainName,
	DWORD Reserved,
	DWORD Version,
	PWTS_SERVER_INFOW* ppServerInfo,
	DWORD* pCount
)
{
	return FALSE;
}

BOOL WINAPI
FreeRDS_WTSEnumerateServersA(
	LPSTR pDomainName,
	DWORD Reserved,
	DWORD Version,
	PWTS_SERVER_INFOA* ppServerInfo,
	DWORD* pCount
)
{
	return FALSE;
}

HANDLE WINAPI
FreeRDS_WTSOpenServerW(LPWSTR pServerName)
{
	return NULL;
}

HANDLE WINAPI
FreeRDS_WTSOpenServerA(LPSTR pServerName)
{
	return NULL;
}

HANDLE WINAPI FreeRDS_WTSOpenServerExW(LPWSTR pServerName)
{
	return FreeRDS_WTSOpenServerW(pServerName);
}

HANDLE WINAPI
FreeRDS_WTSOpenServerExA(LPSTR pServerName)
{
	return FreeRDS_WTSOpenServerA(pServerName);
}

VOID WINAPI
FreeRDS_WTSCloseServer(HANDLE hServer)
{
}

BOOL WINAPI
FreeRDS_WTSEnumerateSessionsA(
	HANDLE hServer,
	DWORD Reserved,
	DWORD Version,
	PWTS_SESSION_INFOA* ppSessionInfo,
	DWORD* pCount)
{
	FDSAPI_MESSAGE requestMsg;
	FDSAPI_MESSAGE responseMsg;

	PWTS_SESSION_INFOA pSessionInfoA;
	BOOL bSuccess;
	LPBYTE pExtra;
	DWORD cbExtra;
	DWORD index;
	DWORD count;
	DWORD size;

	*ppSessionInfo = NULL;
	*pCount = 0;

	if (!ConnectClient())
		return FALSE;

	/* Check parameters. */
	if (hServer != WTS_CURRENT_SERVER_HANDLE)
		return FALSE;

	if (Version != 1)
		return FALSE;

	if (!ppSessionInfo)
		return FALSE;

	if (!pCount)
		return FALSE;

	*ppSessionInfo = NULL;
	*pCount = 0;

	/* Execute session manager RPC. */
	ZeroMemory(&requestMsg, sizeof(FDSAPI_MESSAGE));
	ZeroMemory(&responseMsg, sizeof(FDSAPI_MESSAGE));

	requestMsg.messageId = FDSAPI_ENUMERATE_SESSIONS_REQUEST_ID;
	requestMsg.u.enumerateSessionsRequest.version = Version;

	bSuccess = FDSAPI_SendRequest(&requestMsg, &responseMsg);

	if (bSuccess)
	{
		WLog_Print(g_logger, WLOG_DEBUG,
			"WTSEnumerateSessionsA: result=%u, count=%u",
			responseMsg.u.enumerateSessionsResponse.result,
			responseMsg.u.enumerateSessionsResponse.cSessions);

		bSuccess = responseMsg.u.enumerateSessionsResponse.result;
	}

	if (!bSuccess)
		return FALSE;

	count = responseMsg.u.enumerateSessionsResponse.cSessions;

	if (count == 0)
		return TRUE;

	/* Allocate memory (including space for strings). */
	cbExtra = 0;
	for (index = 0; index < count; index++)
	{
		FDSAPI_SESSION_INFO* pSessionInfo = &responseMsg.u.enumerateSessionsResponse.pSessionInfo[index];
		cbExtra += pSessionInfo->winStationName ? strlen(pSessionInfo->winStationName) + 1 : 0;
	}

	size = (count * sizeof(WTS_SESSION_INFOA)) + cbExtra;
	pSessionInfoA = (PWTS_SESSION_INFOA) calloc(1, size);

	if (!pSessionInfoA)
		return FALSE;

	pExtra = (LPBYTE) pSessionInfoA + (count * sizeof(WTS_SESSION_INFOA));

	/* Fill memory with session information. */
	for (index = 0; index < count; index++)
	{
		FDSAPI_SESSION_INFO* pSessionInfo = &responseMsg.u.enumerateSessionsResponse.pSessionInfo[index];

		pSessionInfoA[index].SessionId = (DWORD) pSessionInfo->sessionId;
		pSessionInfoA[index].pWinStationName = (LPSTR) pExtra;
		pSessionInfoA[index].State = (WTS_CONNECTSTATE_CLASS) pSessionInfo->connectState;

		size = pSessionInfo->winStationName ? strlen(pSessionInfo->winStationName) : 0;
		if (size > 0)
		{
			strcpy((LPSTR) pExtra, pSessionInfo->winStationName);
		}
		pExtra += size + 1;
	}

	*ppSessionInfo = pSessionInfoA;
	*pCount = count;

	return TRUE;
}

BOOL WINAPI
FreeRDS_WTSEnumerateSessionsW(
	HANDLE hServer,
	DWORD Reserved,
	DWORD Version,
	PWTS_SESSION_INFOW* ppSessionInfo,
	DWORD* pCount
)
{
	PWTS_SESSION_INFOA pSessionInfoA;
	PWTS_SESSION_INFOW pSessionInfoW;
	BOOL bSuccess;
	LPBYTE pExtra;
	DWORD cbExtra;
	DWORD count;
	DWORD index;
	DWORD size;

	*ppSessionInfo = NULL;
	*pCount = 0;

	if (!ConnectClient())
		return FALSE;

	bSuccess = FreeRDS_WTSEnumerateSessionsA(
		hServer,
		Reserved,
		Version,
		&pSessionInfoA,
		&count);

	if (bSuccess)
	{
		if (count == 0) return TRUE;

		/* Allocate memory (including space for strings). */
		cbExtra = 0;
		for (index = 0; index < count; index++)
		{
			cbExtra += MultiByteToWideChar(CP_ACP, 0, pSessionInfoA[index].pWinStationName, -1, NULL, 0);
		}

		size = (count * sizeof(WTS_SESSION_INFOW)) + cbExtra;
		pSessionInfoW = (PWTS_SESSION_INFOW)malloc(size);
		if (pSessionInfoW == NULL)
		{
			WTSFreeMemory(pSessionInfoA);
			return FALSE;
		}
		ZeroMemory(pSessionInfoW, size);

		pExtra = (LPBYTE)pSessionInfoW + (count * sizeof(WTS_SESSION_INFOW));

		/* Fill memory with session information. */
		for (index = 0; index < count; index++)
		{
			DWORD cbWinStationName;

			pSessionInfoW[index].SessionId = pSessionInfoA[index].SessionId;
			pSessionInfoW[index].State = pSessionInfoA[index].State;

			if (pSessionInfoA[index].pWinStationName)
			{
				pSessionInfoW[index].pWinStationName = (LPWSTR)pExtra;

				size = MultiByteToWideChar(CP_ACP, 0,
					pSessionInfoA[index].pWinStationName, -1,
					pSessionInfoW[index].pWinStationName, cbExtra);

				pExtra += size;
				cbExtra -= size;
			}
		}
	}

	*ppSessionInfo = pSessionInfoW;
	*pCount = count;

	return bSuccess;
}

BOOL WINAPI
FreeRDS_WTSEnumerateSessionsExW(
	HANDLE hServer,
	DWORD* pLevel,
	DWORD Filter,
	PWTS_SESSION_INFO_1W* ppSessionInfo,
	DWORD* pCount
)
{
	return FALSE;
}

BOOL WINAPI
FreeRDS_WTSEnumerateSessionsExA(
	HANDLE hServer,
	DWORD* pLevel,
	DWORD Filter,
	PWTS_SESSION_INFO_1A* ppSessionInfo,
	DWORD* pCount
)
{
	return FALSE;
}

BOOL WINAPI
FreeRDS_WTSEnumerateProcessesW(
	HANDLE hServer,
	DWORD Reserved,
	DWORD Version,
	PWTS_PROCESS_INFOW* ppProcessInfo,
	DWORD* pCount
)
{
	return FALSE;
}

BOOL WINAPI
FreeRDS_WTSEnumerateProcessesA(
	HANDLE hServer,
	DWORD Reserved,
	DWORD Version,
	PWTS_PROCESS_INFOA* ppProcessInfo,
	DWORD* pCount
)
{
	return FALSE;
}

BOOL WINAPI
FreeRDS_WTSTerminateProcess(
	HANDLE hServer,
	DWORD ProcessId,
	DWORD ExitCode
)
{
	return FALSE;
}

BOOL WINAPI
FreeRDS_WTSQuerySessionInformationA(
	HANDLE hServer,
	DWORD SessionId,
	WTS_INFO_CLASS WTSInfoClass,
	LPSTR* ppBuffer,
	DWORD* pBytesReturned
)
{
	BOOL bSuccess;
	FDSAPI_MESSAGE requestMsg;
	FDSAPI_MESSAGE responseMsg;
	FDSAPI_SESSION_INFO_VALUE* infoValue;

	/* Check parameters. */
	if (hServer != WTS_CURRENT_SERVER_HANDLE)
	{
		SetLastError(ERROR_INVALID_PARAMETER);
		return FALSE;
	}

	if (!CheckSessionId(&SessionId))
		return FALSE;

	if (!ppBuffer)
	{
		SetLastError(ERROR_INVALID_PARAMETER);
		return FALSE;
	}

	if (!pBytesReturned)
	{
		SetLastError(ERROR_INVALID_PARAMETER);
		return FALSE;
	}

	/* Connect to the session manager. */
	if (!ConnectClient())
	{
		SetLastError(ERROR_INTERNAL_ERROR);
		return FALSE;
	}

	*ppBuffer = NULL;
	*pBytesReturned = 0;

	ZeroMemory(&requestMsg, sizeof(FDSAPI_MESSAGE));
	ZeroMemory(&responseMsg, sizeof(FDSAPI_MESSAGE));

	requestMsg.messageId = FDSAPI_QUERY_SESSION_INFORMATION_REQUEST_ID;
	requestMsg.u.querySessionInformationRequest.sessionId = SessionId;
	requestMsg.u.querySessionInformationRequest.infoClass = WTSInfoClass;

	infoValue = &responseMsg.u.querySessionInformationResponse.infoValue;

	bSuccess = FDSAPI_SendRequest(&requestMsg, &responseMsg);

	if (!bSuccess)
	{
		SetLastError(ERROR_INTERNAL_ERROR);
		return FALSE;
	}

	if (!responseMsg.u.querySessionInformationResponse.result)
	{
		FDSAPI_FreeMessage(&responseMsg);
		SetLastError(ERROR_INTERNAL_ERROR);
		return FALSE;
	}

	/* Return the result. */
	switch (WTSInfoClass)
	{
		case WTSSessionId:
		case WTSConnectState:
		case WTSClientBuildNumber:
		case WTSClientHardwareId:
		{
			ULONG* pulValue = (ULONG*) malloc(sizeof(ULONG));

			if (!pulValue)
			{
				WLog_Print(g_logger, WLOG_ERROR, "memory allocation error");
				FDSAPI_FreeMessage(&responseMsg);
				SetLastError(ERROR_NOT_ENOUGH_MEMORY);
				return FALSE;
			}

			*pulValue = (ULONG) infoValue->u.uint32Value;

			*ppBuffer = (LPSTR) pulValue;
			*pBytesReturned = sizeof(ULONG);

			break;
		}

		case WTSClientProductId:
		case WTSClientProtocolType:
		{
			USHORT* pusValue = (USHORT*) malloc(sizeof(USHORT));

			if (!pusValue)
			{
				WLog_Print(g_logger, WLOG_ERROR, "memory allocation error");
				FDSAPI_FreeMessage(&responseMsg);
				SetLastError(ERROR_NOT_ENOUGH_MEMORY);
				return FALSE;
			}

			*pusValue = (USHORT) infoValue->u.uint16Value;

			*ppBuffer = (LPSTR) pusValue;
			*pBytesReturned = sizeof(USHORT);

			break;
		}

		case WTSUserName:
		case WTSWinStationName:
		case WTSDomainName:
		case WTSClientName:
		{
			const char* stringValue = infoValue->u.stringValue ? infoValue->u.stringValue : "";
			int size = strlen(stringValue) + 1;

			LPSTR pszValue = (LPSTR) malloc(size);

			if (!pszValue)
			{
				WLog_Print(g_logger, WLOG_ERROR, "memory allocation error");
				FDSAPI_FreeMessage(&responseMsg);
				SetLastError(ERROR_NOT_ENOUGH_MEMORY);
				return FALSE;
			}

			strncpy(pszValue, stringValue, size);

			*ppBuffer = pszValue;
			*pBytesReturned = size;

			break;
		}

		case WTSClientAddress:
		{
			int ipAddr[4];
			const char* stringValue = infoValue->u.stringValue ? infoValue->u.stringValue : "";

			int size = sizeof(WTS_CLIENT_ADDRESS);
			WTS_CLIENT_ADDRESS* pClientAddress = (WTS_CLIENT_ADDRESS*) calloc(1, size);

			if (!pClientAddress)
			{
				WLog_Print(g_logger, WLOG_ERROR, "memory allocation error");
				FDSAPI_FreeMessage(&responseMsg);
				SetLastError(ERROR_NOT_ENOUGH_MEMORY);
				return FALSE;
			}

			/* TODO: Need to convert IPV4 or IPV6 address from string to binary. */

			pClientAddress->AddressFamily = AF_INET;

			if (sscanf(stringValue, "%d.%d.%d.%d", &ipAddr[0], &ipAddr[1], &ipAddr[2], &ipAddr[3]) == 4)
			{
				pClientAddress->Address[2] = (BYTE)ipAddr[0];
				pClientAddress->Address[3] = (BYTE)ipAddr[1];
				pClientAddress->Address[4] = (BYTE)ipAddr[2];
				pClientAddress->Address[5] = (BYTE)ipAddr[3];
			}

			*ppBuffer = (LPSTR) pClientAddress;
			*pBytesReturned = size;

			break;
		}

		case WTSClientDisplay:
		{
			int size = sizeof(WTS_CLIENT_DISPLAY);
			WTS_CLIENT_DISPLAY* pClientDisplay = (WTS_CLIENT_DISPLAY*) malloc(size);

			if (!pClientDisplay)
			{
				WLog_Print(g_logger, WLOG_ERROR, "memory allocation error");
				FDSAPI_FreeMessage(&responseMsg);
				SetLastError(ERROR_NOT_ENOUGH_MEMORY);
				return FALSE;
			}

			pClientDisplay->HorizontalResolution = infoValue->u.displayValue.displayWidth;
			pClientDisplay->VerticalResolution = infoValue->u.displayValue.displayHeight;
			pClientDisplay->ColorDepth = infoValue->u.displayValue.colorDepth;

			*ppBuffer = (LPSTR) pClientDisplay;
			*pBytesReturned = size;

			break;
		}

		default:
			bSuccess = FALSE;
			break;
	}

	FDSAPI_FreeMessage(&responseMsg);

	return bSuccess;
}

BOOL WINAPI
FreeRDS_WTSQuerySessionInformationW(
	HANDLE hServer,
	DWORD SessionId,
	WTS_INFO_CLASS WTSInfoClass,
	LPWSTR* ppBuffer,
	DWORD* pBytesReturned
)
{
	LPSTR pBuffer;
	DWORD cbBuffer;
	BOOL bSuccess;

	*ppBuffer = NULL;
	*pBytesReturned = 0;

	bSuccess = FreeRDS_WTSQuerySessionInformationA(
		hServer,
		SessionId,
		WTSInfoClass,
		&pBuffer,
		&cbBuffer);

	if (bSuccess)
	{
		switch (WTSInfoClass)
		{
			case WTSUserName:
			case WTSWinStationName:
			case WTSDomainName:
			case WTSClientName:
			{
				int status = ConvertToUnicode(CP_ACP, 0, pBuffer, -1, ppBuffer, 0);
				if (status > 0)
				{
					*pBytesReturned = status;
				}
				else
				{
					bSuccess = FALSE;
				}
				WTSFreeMemory(pBuffer);
				break;
			}

			default:
				*ppBuffer = (LPWSTR)pBuffer;
				*pBytesReturned = cbBuffer;
				break;
		}
	}

	return bSuccess;
}

BOOL WINAPI
FreeRDS_WTSQueryUserConfigW(
	LPWSTR pServerName,
	LPWSTR pUserName,
	WTS_CONFIG_CLASS WTSConfigClass,
	LPWSTR* ppBuffer,
	DWORD* pBytesReturned
)
{
	return FALSE;
}

BOOL WINAPI
FreeRDS_WTSQueryUserConfigA(
	LPSTR pServerName,
	LPSTR pUserName,
	WTS_CONFIG_CLASS WTSConfigClass,
	LPSTR* ppBuffer,
	DWORD* pBytesReturned
)
{
	return FALSE;
}

BOOL WINAPI
FreeRDS_WTSSetUserConfigW(
	LPWSTR pServerName,
	LPWSTR pUserName,
	WTS_CONFIG_CLASS WTSConfigClass,
	LPWSTR pBuffer,
	DWORD DataLength
)
{
	return FALSE;
}

BOOL WINAPI
FreeRDS_WTSSetUserConfigA(
	LPSTR pServerName,
	LPSTR pUserName,
	WTS_CONFIG_CLASS WTSConfigClass,
	LPSTR pBuffer,
	DWORD DataLength
)
{
	return FALSE;
}

BOOL WINAPI
FreeRDS_WTSSendMessageW(
	HANDLE hServer,
	DWORD SessionId,
	LPWSTR pTitle,
	DWORD TitleLength,
	LPWSTR pMessage,
	DWORD MessageLength,
	DWORD Style,
	DWORD Timeout,
	DWORD* pResponse,
	BOOL bWait
)
{
	return FALSE;
}

BOOL WINAPI
FreeRDS_WTSSendMessageA(
	HANDLE hServer,
	DWORD SessionId,
	LPSTR pTitle,
	DWORD TitleLength,
	LPSTR pMessage,
	DWORD MessageLength,
	DWORD Style,
	DWORD Timeout,
	DWORD* pResponse,
	BOOL bWait
)
{
	return FALSE;
}

BOOL WINAPI
FreeRDS_WTSDisconnectSession(
	HANDLE hServer,
	DWORD SessionId,
	BOOL bWait
)
{
	BOOL bSuccess;
	FDSAPI_MESSAGE requestMsg;
	FDSAPI_MESSAGE responseMsg;

	/* Check parameters. */
	if (hServer != WTS_CURRENT_SERVER_HANDLE)
	{
		SetLastError(ERROR_INVALID_PARAMETER);
		return FALSE;
	}

	if (!CheckSessionId(&SessionId))
	{
		SetLastError(ERROR_INVALID_PARAMETER);
		return FALSE;
	}

	/* Connect to the session manager. */
	if (!ConnectClient())
	{
		SetLastError(ERROR_INTERNAL_ERROR);
		return FALSE;
	}

	/* Execute session manager RPC. */
	ZeroMemory(&requestMsg, sizeof(FDSAPI_MESSAGE));
	ZeroMemory(&responseMsg, sizeof(FDSAPI_MESSAGE));

	requestMsg.messageId = FDSAPI_DISCONNECT_SESSION_REQUEST_ID;
	requestMsg.u.disconnectSessionRequest.sessionId = SessionId;
	requestMsg.u.disconnectSessionRequest.wait = bWait;

	bSuccess = FDSAPI_SendRequest(&requestMsg, &responseMsg);

	if (bSuccess)
	{
		bSuccess = responseMsg.u.disconnectSessionResponse.result;

		FDSAPI_FreeMessage(&responseMsg);
	}

	/* Return the result. */
	return bSuccess;
}

BOOL WINAPI
FreeRDS_WTSLogoffSession(
	HANDLE hServer,
	DWORD SessionId,
	BOOL bWait
)
{
	BOOL bSuccess;
	FDSAPI_MESSAGE requestMsg;
	FDSAPI_MESSAGE responseMsg;

	/* Check parameters. */
	if (hServer != WTS_CURRENT_SERVER_HANDLE)
	{
		SetLastError(ERROR_INVALID_PARAMETER);
		return FALSE;
	}

	if (!CheckSessionId(&SessionId))
	{
		SetLastError(ERROR_INVALID_PARAMETER);
		return FALSE;
	}

	/* Connect to the session manager. */
	if (!ConnectClient())
	{
		SetLastError(ERROR_INTERNAL_ERROR);
		return FALSE;
	}

	/* Execute session manager RPC. */
	ZeroMemory(&requestMsg, sizeof(FDSAPI_MESSAGE));
	ZeroMemory(&responseMsg, sizeof(FDSAPI_MESSAGE));

	requestMsg.messageId = FDSAPI_LOGOFF_SESSION_REQUEST_ID;
	requestMsg.u.logoffSessionRequest.sessionId = SessionId;
	requestMsg.u.logoffSessionRequest.wait = bWait;

	bSuccess = FDSAPI_SendRequest(&requestMsg, &responseMsg);

	if (bSuccess)
	{
		bSuccess = responseMsg.u.logoffSessionResponse.result;

		FDSAPI_FreeMessage(&responseMsg);
	}

	/* Return the result. */
	return bSuccess;
}

BOOL WINAPI
FreeRDS_WTSShutdownSystem(
	HANDLE hServer,
	DWORD ShutdownFlag
)
{
	FDSAPI_MESSAGE requestMsg;
	FDSAPI_MESSAGE responseMsg;
	BOOL bSuccess;

	/* Check parameters. */
	if (hServer != WTS_CURRENT_SERVER_HANDLE)
	{
		SetLastError(ERROR_INVALID_PARAMETER);
		return FALSE;
	}

	/* Connect to the session manager. */
	if (!ConnectClient())
	{
		SetLastError(ERROR_INTERNAL_ERROR);
		return FALSE;
	}

	/* Execute session manager RPC. */
	ZeroMemory(&requestMsg, sizeof(FDSAPI_MESSAGE));
	ZeroMemory(&responseMsg, sizeof(FDSAPI_MESSAGE));

	requestMsg.messageId = FDSAPI_SHUTDOWN_SYSTEM_REQUEST_ID;
	requestMsg.u.shutdownSystemRequest.shutdownFlag = ShutdownFlag;

	bSuccess = FDSAPI_SendRequest(&requestMsg, &responseMsg);

	if (bSuccess)
	{
		bSuccess = responseMsg.u.shutdownSystemResponse.result;

		FDSAPI_FreeMessage(&responseMsg);
	}

	/* Return the result. */
	return bSuccess;
}

BOOL WINAPI
FreeRDS_WTSWaitSystemEvent(
	HANDLE hServer,
	DWORD EventMask,
	DWORD* pEventFlags
)
{
	DWORD dwErrorCode;
	BOOL bSuccess = FALSE;
	HANDLE hEvent = NULL;
	FDSAPI_SESSION_EVENT_OBSERVER* pSessionEventObserver = NULL;

	/* Check parameters. */
	if (hServer != WTS_CURRENT_SERVER_HANDLE)
	{
		SetLastError(ERROR_INVALID_PARAMETER);
		return FALSE;
	}

	/* Connect to the FDSAPI server. */
	if (!ConnectClient())
	{
		SetLastError(ERROR_INTERNAL_ERROR);
		return FALSE;
	}

	/* Create an event. */
	hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);

	if (!hEvent)
	{
		dwErrorCode = GetLastError();
		WLog_Print(g_logger, WLOG_ERROR, "error creating event");
		goto CLEANUP;
	}

	/* Create a session event observer. */
	pSessionEventObserver = (FDSAPI_SESSION_EVENT_OBSERVER*) calloc(1, sizeof(FDSAPI_SESSION_EVENT_OBSERVER));

	if (!pSessionEventObserver)
	{
		dwErrorCode = ERROR_NOT_ENOUGH_MEMORY;
		WLog_Print(g_logger, WLOG_ERROR, "memory allocation error");
		goto CLEANUP;
	}

	pSessionEventObserver->type = FDSAPI_WAIT_SYSTEM_EVENT_TYPE;
	pSessionEventObserver->u.waitSystemEvent.hWaitEvent = hEvent;
	pSessionEventObserver->u.waitSystemEvent.dwEventMask = EventMask;

	/* Add the session event observer to a list. */
	ArrayList_Lock(g_sessionEventObserverList);
	ArrayList_Add(g_sessionEventObserverList, pSessionEventObserver);
	ArrayList_Unlock(g_sessionEventObserverList);

	/* Wait for the event. */
	if (WaitForSingleObject(hEvent, INFINITE) == WAIT_OBJECT_0)
	{
		bSuccess = TRUE;
		dwErrorCode = ERROR_SUCCESS;
	}
	else
	{
		dwErrorCode = GetLastError();
		WLog_Print(g_logger, WLOG_ERROR, "event wait failed");
	}

	/* Remove the session event observer from a list. */
	ArrayList_Lock(g_sessionEventObserverList);
	ArrayList_Remove(g_sessionEventObserverList, pSessionEventObserver);
	ArrayList_Unlock(g_sessionEventObserverList);

	if (bSuccess)
	{
		/* Return the event flags to the caller. */
		*pEventFlags = pSessionEventObserver->u.waitSystemEvent.dwEventFlags;
	}

CLEANUP:
	if (hEvent)
	{
		CloseHandle(hEvent);
	}

	if (pSessionEventObserver)
	{
		free(pSessionEventObserver);
	}

	SetLastError(dwErrorCode);

	return bSuccess;
}

HANDLE WINAPI
FreeRDS_WTSVirtualChannelOpen(
	HANDLE hServer,
	DWORD SessionId,
	LPSTR pVirtualName
)
{
	int status;
	BOOL bSuccess;
	DWORD dwErrorCode;
	UINT32 channelPort;
	const char* channelGuid;
	FDSAPI_MESSAGE requestMsg;
	FDSAPI_MESSAGE responseMsg;
	FDSAPI_CHANNEL* pChannel = NULL;

	if (!pVirtualName)
	{
		SetLastError(ERROR_INVALID_PARAMETER);
		return FALSE;
	}

	if (!ConnectClient())
	{
		SetLastError(ERROR_INTERNAL_ERROR);
		return NULL;
	}

	if (hServer != WTS_CURRENT_SERVER_HANDLE)
	{
		SetLastError(ERROR_NOT_SUPPORTED);
		return FALSE;
	}

	if (!CheckSessionId(&SessionId))
	{
		SetLastError(ERROR_INVALID_PARAMETER);
		return FALSE;
	}

	WLog_Print(g_logger, WLOG_DEBUG, "WTSVirtualChannelOpen: %s", pVirtualName);

	/* Execute session manager RPC. */
	ZeroMemory(&requestMsg, sizeof(FDSAPI_MESSAGE));
	ZeroMemory(&responseMsg, sizeof(FDSAPI_MESSAGE));

	requestMsg.messageId = FDSAPI_VIRTUAL_CHANNEL_OPEN_REQUEST_ID;
	requestMsg.u.virtualChannelOpenRequest.sessionId = SessionId;
	requestMsg.u.virtualChannelOpenRequest.virtualName = pVirtualName;

	bSuccess = FDSAPI_SendRequest(&requestMsg, &responseMsg);

	if (!bSuccess)
	{
		SetLastError(ERROR_INTERNAL_ERROR);
		return NULL;
	}

	channelPort = responseMsg.u.virtualChannelOpenResponse.channelPort;
	channelGuid = responseMsg.u.virtualChannelOpenResponse.channelGuid;

	WLog_Print(g_logger, WLOG_DEBUG, "WTSVirtualChannelOpen: %s:%d", channelGuid, channelPort);

	if (!channelGuid || !channelPort)
	{
		dwErrorCode = ERROR_INTERNAL_ERROR;
		goto CLEANUP;
	}

	pChannel = FDSAPI_Channel_New();

	if (!pChannel)
	{
		dwErrorCode = ERROR_NOT_ENOUGH_MEMORY;
		goto CLEANUP;
	}

	status = FDSAPI_Channel_Connect(pChannel, channelGuid, channelPort);

	if (status < 0)
	{
		dwErrorCode = ERROR_OPEN_FAILED;
		WLog_Print(g_logger, WLOG_ERROR, "FDSAPI_Channel_Connect failure: %d", status);
		goto CLEANUP;
	}

	FDSAPI_FreeMessage(&responseMsg);

	SetLastError(ERROR_SUCCESS);

	return (HANDLE) pChannel;

CLEANUP:
	if (pChannel)
	{
		FDSAPI_Channel_Free(pChannel);
	}

	FDSAPI_FreeMessage(&responseMsg);

	SetLastError(dwErrorCode);

	return NULL;
}

HANDLE WINAPI
FreeRDS_WTSVirtualChannelOpenEx(
	DWORD SessionId,
	LPSTR pVirtualName,
	DWORD flags
)
{
	int status;
	BOOL bSuccess;
	DWORD dwErrorCode;
	UINT32 channelPort;
	const char* channelGuid;
	FDSAPI_MESSAGE requestMsg;
	FDSAPI_MESSAGE responseMsg;
	FDSAPI_CHANNEL* pChannel = NULL;

	if (!pVirtualName)
	{
		SetLastError(ERROR_INVALID_PARAMETER);
		return FALSE;
	}

	if (!ConnectClient())
	{
		SetLastError(ERROR_INTERNAL_ERROR);
		return NULL;
	}

	if (!CheckSessionId(&SessionId))
	{
		SetLastError(ERROR_INVALID_PARAMETER);
		return FALSE;
	}

	WLog_Print(g_logger, WLOG_DEBUG, "WTSVirtualChannelOpenEx: %s, 0x%x", pVirtualName, flags);

	/* Execute session manager RPC. */
	ZeroMemory(&requestMsg, sizeof(FDSAPI_MESSAGE));
	ZeroMemory(&responseMsg, sizeof(FDSAPI_MESSAGE));

	requestMsg.messageId = FDSAPI_VIRTUAL_CHANNEL_OPEN_EX_REQUEST_ID;
	requestMsg.u.virtualChannelOpenExRequest.sessionId = SessionId;
	requestMsg.u.virtualChannelOpenExRequest.virtualName = pVirtualName;

	bSuccess = FDSAPI_SendRequest(&requestMsg, &responseMsg);

	if (!bSuccess)
	{
		SetLastError(ERROR_INTERNAL_ERROR);
		return NULL;
	}

	channelPort = responseMsg.u.virtualChannelOpenExResponse.channelPort;
	channelGuid = responseMsg.u.virtualChannelOpenExResponse.channelGuid;

	WLog_Print(g_logger, WLOG_DEBUG, "WTSVirtualChannelOpenEx: %s:%d", channelGuid, channelPort);

	if (!channelGuid || !channelPort)
	{
		dwErrorCode = ERROR_INTERNAL_ERROR;
		goto CLEANUP;
	}

	pChannel = FDSAPI_Channel_New();

	if (!pChannel)
	{
		dwErrorCode = ERROR_NOT_ENOUGH_MEMORY;
		goto CLEANUP;
	}

	status = FDSAPI_Channel_Connect(pChannel, channelGuid, channelPort);

	if (status < 0)
	{
		dwErrorCode = ERROR_OPEN_FAILED;
		WLog_Print(g_logger, WLOG_ERROR, "FDSAPI_Channel_Connect failure: %d", status);
		goto CLEANUP;
	}

	FDSAPI_FreeMessage(&responseMsg);

	SetLastError(ERROR_SUCCESS);

	return (HANDLE) pChannel;

CLEANUP:
	if (pChannel)
	{
		FDSAPI_Channel_Free(pChannel);
	}

	FDSAPI_FreeMessage(&responseMsg);

	SetLastError(dwErrorCode);

	return NULL;
}

BOOL WINAPI
FreeRDS_WTSVirtualChannelClose(
	HANDLE hChannelHandle
)
{
	FDSAPI_CHANNEL* pChannel;

	WLog_Print(g_logger, WLOG_DEBUG, "WTSVirtualChannelClose: %p", hChannelHandle);

	if (!hChannelHandle)
	{
		SetLastError(ERROR_INVALID_HANDLE);
		return FALSE;
	}

	pChannel = (FDSAPI_CHANNEL*) hChannelHandle;

	FDSAPI_Channel_Free(pChannel);

	return TRUE;
}

BOOL WINAPI
FreeRDS_WTSVirtualChannelRead(
	HANDLE hChannelHandle,
	ULONG TimeOut,
	PCHAR Buffer,
	ULONG BufferSize,
	PULONG pBytesRead
)
{
	int status;
	DWORD waitStatus;
	FDSAPI_CHANNEL* pChannel;

	WLog_Print(g_logger, WLOG_DEBUG, "WTSVirtualChannelRead: %p %lu %p %lu %p", hChannelHandle, TimeOut, Buffer, BufferSize, pBytesRead);

	if (!hChannelHandle)
	{
		SetLastError(ERROR_INVALID_HANDLE);
		return FALSE;
	}

	if (!Buffer && BufferSize)
	{
		SetLastError(ERROR_INVALID_PARAMETER);
		return FALSE;
	}

	if (!pBytesRead)
	{
		SetLastError(ERROR_INVALID_PARAMETER);
		return FALSE;
	}

	pChannel = (FDSAPI_CHANNEL*) hChannelHandle;

	*pBytesRead = 0;

	if (TimeOut)
	{
		waitStatus = WaitForSingleObject(pChannel->event, TimeOut);

		if (waitStatus == WAIT_TIMEOUT)
		{
			SetLastError(ERROR_IO_INCOMPLETE);
			return FALSE;
		}
		else if (waitStatus != WAIT_OBJECT_0)
		{
			SetLastError(ERROR_INTERNAL_ERROR);
			return FALSE;
		}
	}

	status = _recv(pChannel->socket, Buffer, BufferSize, 0);

	if (status <= 0)
	{
		SetLastError(ERROR_BROKEN_PIPE);
		return FALSE;
	}

	*pBytesRead = (ULONG) status;

	return TRUE;
}

BOOL WINAPI
FreeRDS_WTSVirtualChannelWrite(
	HANDLE hChannelHandle,
	PCHAR Buffer,
	ULONG Length,
	PULONG pBytesWritten
)
{
	int status;
	FDSAPI_CHANNEL* pChannel;

	WLog_Print(g_logger, WLOG_DEBUG, "WTSVirtualChannelWrite: %p %p %lu %p", hChannelHandle, Buffer, Length, pBytesWritten);

	if (!hChannelHandle)
	{
		SetLastError(ERROR_INVALID_HANDLE);
		return FALSE;
	}

	if (!Buffer && Length)
	{
		SetLastError(ERROR_INVALID_PARAMETER);
		return FALSE;
	}

	if (!pBytesWritten)
	{
		SetLastError(ERROR_INVALID_PARAMETER);
		return FALSE;
	}

	pChannel = (FDSAPI_CHANNEL*) hChannelHandle;

	*pBytesWritten = 0;

	status = _send(pChannel->socket, (const char *) &Length, sizeof(Length), 0);

	if (status < 0)
	{
		SetLastError(ERROR_BROKEN_PIPE);
		return FALSE;
	}

	status = _send(pChannel->socket, Buffer, Length, 0);

	if (status < 0)
	{
		SetLastError(ERROR_BROKEN_PIPE);
		return FALSE;
	}

	*pBytesWritten = (ULONG) status;

	return TRUE;
}

BOOL WINAPI
FreeRDS_WTSVirtualChannelPurgeInput(
	HANDLE hChannelHandle
)
{
	if (!hChannelHandle)
	{
		SetLastError(ERROR_INVALID_HANDLE);
		return FALSE;
	}

	return TRUE;
}

BOOL WINAPI
FreeRDS_WTSVirtualChannelPurgeOutput(
	HANDLE hChannelHandle
)
{
	if (!hChannelHandle)
	{
		SetLastError(ERROR_INVALID_HANDLE);
		return FALSE;
	}

	return TRUE;
}

BOOL WINAPI
FreeRDS_WTSVirtualChannelQuery(
	HANDLE hChannelHandle,
	WTS_VIRTUAL_CLASS WtsVirtualClass,
	PVOID* ppBuffer,
	DWORD* pBytesReturned
)
{
	FDSAPI_CHANNEL* pChannel;

	if (!hChannelHandle)
	{
		SetLastError(ERROR_INVALID_HANDLE);
		return FALSE;
	}

	if (!ppBuffer || !pBytesReturned)
	{
		SetLastError(ERROR_INVALID_PARAMETER);
		return FALSE;
	}

	pChannel = (FDSAPI_CHANNEL*) hChannelHandle;

	if (WtsVirtualClass == WTSVirtualFileHandle)
	{
		/* overlapped i/o is not supported */
		SetLastError(ERROR_INVALID_PARAMETER);
		return FALSE;
	}
	else if (WtsVirtualClass == WTSVirtualEventHandle)
	{
		*pBytesReturned = sizeof(HANDLE);
		*ppBuffer = malloc(*pBytesReturned);

		if (*ppBuffer == NULL)
		{
			SetLastError(ERROR_NOT_ENOUGH_MEMORY);
			return FALSE;
		}

		CopyMemory(*ppBuffer, &(pChannel->event), *pBytesReturned);
	}
	else
	{
		SetLastError(ERROR_INVALID_PARAMETER);
		return FALSE;
	}

	return TRUE;
}

VOID WINAPI
FreeRDS_WTSFreeMemory(
	PVOID pMemory
)
{
	if (pMemory)
	{
		free(pMemory);
	}
}

BOOL WINAPI
FreeRDS_WTSFreeMemoryExW(
	WTS_TYPE_CLASS WTSTypeClass,
	PVOID pMemory,
	ULONG NumberOfEntries
)
{
	return FALSE;
}

BOOL WINAPI
FreeRDS_WTSFreeMemoryExA(
	WTS_TYPE_CLASS WTSTypeClass,
	PVOID pMemory,
	ULONG NumberOfEntries
)
{
	return FALSE;
}

BOOL WINAPI
FreeRDS_WTSRegisterSessionNotification(
	HWND hWnd,
	DWORD dwFlags
)
{
	FDSAPI_SESSION_EVENT_OBSERVER* pSessionEventObserver = NULL;

	if (!ConnectClient())
		return FALSE;

	/* Create a session event observer. */
	pSessionEventObserver = (FDSAPI_SESSION_EVENT_OBSERVER*) calloc(1, sizeof(FDSAPI_SESSION_EVENT_OBSERVER));

	if (!pSessionEventObserver)
		return FALSE;

	pSessionEventObserver->type = FDSAPI_SESSION_NOTIFICATION_TYPE;
	pSessionEventObserver->u.sessionNotification.hWnd = hWnd;
	pSessionEventObserver->u.sessionNotification.dwFlags = dwFlags;

	/* Add the session event observer to a list. */
	ArrayList_Lock(g_sessionEventObserverList);
	ArrayList_Add(g_sessionEventObserverList, pSessionEventObserver);
	ArrayList_Unlock(g_sessionEventObserverList);

	return TRUE;
}

BOOL WINAPI
FreeRDS_WTSUnRegisterSessionNotification(
	HWND hWnd
)
{
	int index;
	BOOL bSuccess = FALSE;
	FDSAPI_SESSION_EVENT_OBSERVER* pSessionEventObserver;

	if (!ConnectClient())
		return FALSE;

	/* Loop through the session event observer list... */
	ArrayList_Lock(g_sessionEventObserverList);

	for (index = 0; !bSuccess && (index < ArrayList_Count(g_sessionEventObserverList)); index++)
	{
		/* Get the next item in the list. */
		pSessionEventObserver = (FDSAPI_SESSION_EVENT_OBSERVER*) ArrayList_GetItem(g_sessionEventObserverList, index);

		if (pSessionEventObserver->type == FDSAPI_SESSION_NOTIFICATION_TYPE)
		{
			/* If the item matches the specified HWND... */
			if (pSessionEventObserver->u.sessionNotification.hWnd == hWnd)
			{
				/* Remove the item from the list. */
				ArrayList_RemoveAt(g_sessionEventObserverList, index);

				/* Free the session event observer. */
				free(pSessionEventObserver);

				bSuccess = TRUE;
			}
		}
	}

	ArrayList_Unlock(g_sessionEventObserverList);

	return bSuccess;
}

BOOL WINAPI
FreeRDS_WTSRegisterSessionNotificationEx(
	HANDLE hServer,
	HWND hWnd,
	DWORD dwFlags
)
{
	/* Check parameters. */
	if (hServer != WTS_CURRENT_SERVER_HANDLE)
		return FALSE;

	return FreeRDS_WTSRegisterSessionNotification(hWnd, dwFlags);
}

BOOL WINAPI
FreeRDS_WTSUnRegisterSessionNotificationEx(
	HANDLE hServer,
	HWND hWnd
)
{
	/* Check parameters. */
	if (hServer != WTS_CURRENT_SERVER_HANDLE)
		return FALSE;

	return FreeRDS_WTSUnRegisterSessionNotification(hWnd);
}

BOOL WINAPI
FreeRDS_WTSQueryUserToken(
	ULONG SessionId,
	PHANDLE phToken
)
{
	return FALSE;
}

BOOL WINAPI
FreeRDS_WTSEnumerateProcessesExW(
	HANDLE hServer,
	DWORD* pLevel,
	DWORD SessionId,
	LPWSTR* ppProcessInfo,
	DWORD* pCount
)
{
	return FALSE;
}

BOOL WINAPI
FreeRDS_WTSEnumerateProcessesExA(
	HANDLE hServer,
	DWORD* pLevel,
	DWORD SessionId,
	LPSTR* ppProcessInfo,
	DWORD* pCount
)
{
	return FALSE;
}

BOOL WINAPI
FreeRDS_WTSEnumerateListenersW(
	HANDLE hServer,
	PVOID pReserved,
	DWORD Reserved,
	PWTSLISTENERNAMEW pListeners,
	DWORD* pCount
)
{
	return FALSE;
}

BOOL WINAPI
FreeRDS_WTSEnumerateListenersA(
	HANDLE hServer,
	PVOID pReserved,
	DWORD Reserved,
	PWTSLISTENERNAMEA pListeners,
	DWORD* pCount
)
{
	return FALSE;
}

BOOL WINAPI
FreeRDS_WTSQueryListenerConfigW(
	HANDLE hServer,
	PVOID pReserved,
	DWORD Reserved,
	LPWSTR pListenerName,
	PWTSLISTENERCONFIGW pBuffer
)
{
	return FALSE;
}

BOOL WINAPI
FreeRDS_WTSQueryListenerConfigA(
	HANDLE hServer,
	PVOID pReserved,
	DWORD Reserved,
	LPSTR pListenerName,
	PWTSLISTENERCONFIGA pBuffer
)
{
	return FALSE;
}

BOOL WINAPI
FreeRDS_WTSCreateListenerW(
	HANDLE hServer,
	PVOID pReserved,
	DWORD Reserved,
	LPWSTR pListenerName,
	PWTSLISTENERCONFIGW pBuffer,
	DWORD flag
)
{
	return FALSE;
}

BOOL WINAPI
FreeRDS_WTSCreateListenerA(
	HANDLE hServer,
	PVOID pReserved,
	DWORD Reserved,
	LPSTR pListenerName,
	PWTSLISTENERCONFIGA pBuffer,
	DWORD flag
)
{
	return FALSE;
}

BOOL WINAPI
FreeRDS_WTSSetListenerSecurityW(
	HANDLE hServer,
	PVOID pReserved,
	DWORD Reserved,
	LPWSTR pListenerName,
	SECURITY_INFORMATION SecurityInformation,
	PSECURITY_DESCRIPTOR pSecurityDescriptor
)
{
	return FALSE;
}

BOOL WINAPI
FreeRDS_WTSSetListenerSecurityA(
	HANDLE hServer,
	PVOID pReserved,
	DWORD Reserved,
	LPSTR pListenerName,
	SECURITY_INFORMATION SecurityInformation,
	PSECURITY_DESCRIPTOR pSecurityDescriptor
)
{
	return FALSE;
}

BOOL WINAPI
FreeRDS_WTSGetListenerSecurityW(
	HANDLE hServer,
	PVOID pReserved,
	DWORD Reserved,
	LPWSTR pListenerName,
	SECURITY_INFORMATION SecurityInformation,
	PSECURITY_DESCRIPTOR pSecurityDescriptor,
	DWORD nLength,
	LPDWORD lpnLengthNeeded
)
{
	return FALSE;
}

BOOL WINAPI
FreeRDS_WTSGetListenerSecurityA(
	HANDLE hServer,
	PVOID pReserved,
	DWORD Reserved,
	LPSTR pListenerName,
	SECURITY_INFORMATION SecurityInformation,
	PSECURITY_DESCRIPTOR pSecurityDescriptor,
	DWORD nLength,
	LPDWORD lpnLengthNeeded
)
{
	return FALSE;
}

BOOL CDECL
FreeRDS_WTSEnableChildSessions(
	BOOL bEnable
)
{
	return FALSE;
}

BOOL CDECL
FreeRDS_WTSIsChildSessionsEnabled(
	PBOOL pbEnabled
)
{
	return FALSE;
}

BOOL CDECL
FreeRDS_WTSGetChildSessionId(
	PULONG pSessionId
)
{
	return FALSE;
}

DWORD WINAPI
FreeRDS_WTSGetActiveConsoleSessionId(void)
{
	return 0xFFFFFFFF;
}

static WtsApiFunctionTable FreeRDS_WtsApiFunctionTable =
{
	0, /* dwVersion */
	0, /* dwFlags */

	FreeRDS_WTSStopRemoteControlSession, /* StopRemoteControlSession */
	FreeRDS_WTSStartRemoteControlSessionW, /* StartRemoteControlSessionW */
	FreeRDS_WTSStartRemoteControlSessionA, /* StartRemoteControlSessionA */
	FreeRDS_WTSConnectSessionW, /* ConnectSessionW */
	FreeRDS_WTSConnectSessionA, /* ConnectSessionA */
	FreeRDS_WTSEnumerateServersW, /* EnumerateServersW */
	FreeRDS_WTSEnumerateServersA, /* EnumerateServersA */
	FreeRDS_WTSOpenServerW, /* OpenServerW */
	FreeRDS_WTSOpenServerA, /* OpenServerA */
	FreeRDS_WTSOpenServerExW, /* OpenServerExW */
	FreeRDS_WTSOpenServerExA, /* OpenServerExA */
	FreeRDS_WTSCloseServer, /* CloseServer */
	FreeRDS_WTSEnumerateSessionsW, /* EnumerateSessionsW */
	FreeRDS_WTSEnumerateSessionsA, /* EnumerateSessionsA */
	FreeRDS_WTSEnumerateSessionsExW, /* EnumerateSessionsExW */
	FreeRDS_WTSEnumerateSessionsExA, /* EnumerateSessionsExA */
	FreeRDS_WTSEnumerateProcessesW, /* EnumerateProcessesW */
	FreeRDS_WTSEnumerateProcessesA, /* EnumerateProcessesA */
	FreeRDS_WTSTerminateProcess, /* TerminateProcess */
	FreeRDS_WTSQuerySessionInformationW, /* QuerySessionInformationW */
	FreeRDS_WTSQuerySessionInformationA, /* QuerySessionInformationA */
	FreeRDS_WTSQueryUserConfigW, /* QueryUserConfigW */
	FreeRDS_WTSQueryUserConfigA, /* QueryUserConfigA */
	FreeRDS_WTSSetUserConfigW, /* SetUserConfigW */
	FreeRDS_WTSSetUserConfigA, /* SetUserConfigA */
	FreeRDS_WTSSendMessageW, /* SendMessageW */
	FreeRDS_WTSSendMessageA, /* SendMessageA */
	FreeRDS_WTSDisconnectSession, /* DisconnectSession */
	FreeRDS_WTSLogoffSession, /* LogoffSession */
	FreeRDS_WTSShutdownSystem, /* ShutdownSystem */
	FreeRDS_WTSWaitSystemEvent, /* WaitSystemEvent */
	FreeRDS_WTSVirtualChannelOpen, /* VirtualChannelOpen */
	FreeRDS_WTSVirtualChannelOpenEx, /* VirtualChannelOpenEx */
	FreeRDS_WTSVirtualChannelClose, /* VirtualChannelClose */
	FreeRDS_WTSVirtualChannelRead, /* VirtualChannelRead */
	FreeRDS_WTSVirtualChannelWrite, /* VirtualChannelWrite */
	FreeRDS_WTSVirtualChannelPurgeInput, /* VirtualChannelPurgeInput */
	FreeRDS_WTSVirtualChannelPurgeOutput, /* VirtualChannelPurgeOutput */
	FreeRDS_WTSVirtualChannelQuery, /* VirtualChannelQuery */
	FreeRDS_WTSFreeMemory, /* FreeMemory */
	FreeRDS_WTSRegisterSessionNotification, /* RegisterSessionNotification */
	FreeRDS_WTSUnRegisterSessionNotification, /* UnRegisterSessionNotification */
	FreeRDS_WTSRegisterSessionNotificationEx, /* RegisterSessionNotificationEx */
	FreeRDS_WTSUnRegisterSessionNotificationEx, /* UnRegisterSessionNotificationEx */
	FreeRDS_WTSQueryUserToken, /* QueryUserToken */
	FreeRDS_WTSFreeMemoryExW, /* FreeMemoryExW */
	FreeRDS_WTSFreeMemoryExA, /* FreeMemoryExA */
	FreeRDS_WTSEnumerateProcessesExW, /* EnumerateProcessesExW */
	FreeRDS_WTSEnumerateProcessesExA, /* EnumerateProcessesExA */
	FreeRDS_WTSEnumerateListenersW, /* EnumerateListenersW */
	FreeRDS_WTSEnumerateListenersA, /* EnumerateListenersA */
	FreeRDS_WTSQueryListenerConfigW, /* QueryListenerConfigW */
	FreeRDS_WTSQueryListenerConfigA, /* QueryListenerConfigA */
	FreeRDS_WTSCreateListenerW, /* CreateListenerW */
	FreeRDS_WTSCreateListenerA, /* CreateListenerA */
	FreeRDS_WTSSetListenerSecurityW, /* SetListenerSecurityW */
	FreeRDS_WTSSetListenerSecurityA, /* SetListenerSecurityA */
	FreeRDS_WTSGetListenerSecurityW, /* GetListenerSecurityW */
	FreeRDS_WTSGetListenerSecurityA, /* GetListenerSecurityA */
	FreeRDS_WTSEnableChildSessions, /* EnableChildSessions */
	FreeRDS_WTSIsChildSessionsEnabled, /* IsChildSessionsEnabled */
	FreeRDS_WTSGetChildSessionId, /* GetChildSessionId */
	FreeRDS_WTSGetActiveConsoleSessionId /* GetActiveConsoleSessionId */
};

#ifdef __cplusplus
extern "C" {
#endif

/**
 * Export InitWtsApi() but do not expose it with a header file due to possible conflicts
 */

WINPR_API PWtsApiFunctionTable CDECL InitWtsApi(void)
{
	return &FreeRDS_WtsApiFunctionTable;
}

/**
 * Export explicit FreeRDS_InitWtsApi() which we can safely expose with a header
 */

WINPR_API PWtsApiFunctionTable CDECL FreeRDS_InitWtsApi(void)
{
	return &FreeRDS_WtsApiFunctionTable;
}

#ifdef __cplusplus
}
#endif

/**
 * WTSAPI Private Interface
 */

int WINAPI
FreeRDS_AuthenticateUser(
	UINT32 SessionId,
	LPCSTR Username,
	LPCSTR Password,
	LPCSTR Domain
)
{
	FDSAPI_MESSAGE requestMsg;
	FDSAPI_MESSAGE responseMsg;
	BOOL bSuccess;
	int authStatus;

	if (!ConnectClient())
		return FALSE;

	/* Check parameters. */
	if (!CheckSessionId((LPDWORD) &SessionId))
		return -1;

	/* Execute session manager RPC. */
	ZeroMemory(&requestMsg, sizeof(FDSAPI_MESSAGE));
	ZeroMemory(&responseMsg, sizeof(FDSAPI_MESSAGE));

	requestMsg.messageId = FDSAPI_AUTHENTICATE_USER_REQUEST_ID;
	requestMsg.u.authenticateUserRequest.sessionId = SessionId;
	requestMsg.u.authenticateUserRequest.username = Username ? _strdup(Username) : NULL;
	requestMsg.u.authenticateUserRequest.password = Password ? _strdup(Password) : NULL;
	requestMsg.u.authenticateUserRequest.domain = Domain ? _strdup(Domain) : NULL;

	bSuccess = FDSAPI_SendRequest(&requestMsg, &responseMsg);

	if (bSuccess)
	{
		authStatus = responseMsg.u.authenticateUserResponse.result;
	}
	else
	{
		authStatus = -1;
	}

	return authStatus;
}


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

using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace AeccApp.Core.Views.Templates
{
	[XamlCompilation(XamlCompilationOptions.Compile)]
	public partial class HospitalRequestsEmptyTemplate : ContentView
	{
		public HospitalRequestsEmptyTemplate ()
		{
			InitializeComponent ();
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
package zhongqiu.common.base;

//网络编程 socket,tcp/ip,url
//http://www.runoob.com/java/java-networking.html
//http://www.runoob.com/java/java-url-processing.html
public class NetDemo {
	public static void main(String[] args) {

	}
}


text:
/**
 * @module SermonsModule
 * @preferred
 */ /** */
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

import { SermonsComponent } from './sermons.component';
import { SermonsRoutingModule } from './sermons-routing.module';
import { FilterModule } from '../packages/filter/filter.module';
import { SharedModule } from '../shared/shared.module';
/**
 * @whatItDoes Lazy loaded feature module for the sermons page.
 * @consumers {@link AppRoutingModule} (on demand)
 */
@NgModule({
  imports: [
    CommonModule,
    FilterModule,
    SermonsRoutingModule,
    SharedModule
  ],
  declarations: [SermonsComponent]
})
export class SermonsModule { }


text:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;

namespace ConsoleApplication
{
    public class Startup
    {
        public void Configure(IApplicationBuilder app) {

            app.UseRuntimeInfoPage();

            app.Use((context, next) => {
                return context.Response.WriteAsync("Hello world!\n");
            });
        }
    }
}


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Article Page</title>

    <link href="bower_components/bootstrap/dist/css/bootstrap.css" rel="stylesheet" />


text:
angular
    .module('dart.controllers.entity_modal', [])
    .controller('EntityModalController', ['$scope', '$mdDialog', 'entity', 'getSchema', 'saveEntity',
        function($scope, $mdDialog, entity, getSchema, saveEntity) {
            $scope.form = ["*"];
            $scope.entity = entity;
            $scope.showSave = saveEntity;
            getSchema().then(function (response) {
                    $scope.schema = response.results;
                });
            $scope.onCancel = function() { $mdDialog.hide(); };
            $scope.onSubmit = function(entity, form) {
                $scope.working = true;
                $scope.$broadcast('schemaFormValidate');
                if (!form.$valid) {
                    $scope.working = false;
                    return
                }
                saveEntity(entity)
                    .then(function(response) {
                        $scope.working = false;
                        entity = response.results;
                        $mdDialog.hide();
                    });
            }
        }
    ])
;


text:
package com.twitter.graphjet.algorithms.counting.moment;

import java.util.Map;

import com.twitter.graphjet.algorithms.RecommendationType;
import com.twitter.graphjet.algorithms.filters.ResultFilterChain;
import com.twitter.graphjet.algorithms.counting.TopSecondDegreeByCountRequest;

import it.unimi.dsi.fastutil.longs.Long2DoubleMap;
import it.unimi.dsi.fastutil.longs.LongSet;

/**
 * Request data structure for calculating moment recommendations.
 */
public class TopSecondDegreeByCountRequestForMoment extends TopSecondDegreeByCountRequest {
  private final Map<Byte, Integer> minUserPerSocialProof;
  private final int maxNumResults;
  private final int maxNumSocialProofs;
  private final RecommendationType recommendationType = RecommendationType.MOMENT;

  /**
   * @param queryNode                 is the query node for running TopSecondDegreeByCountRequestForMoment
   * @param leftSeedNodesWithWeight   is the set of seed nodes and their weights to use for calculation
   * @param toBeFiltered              is the set of RHS nodes to be filtered from the output
   * @param maxNumResults             is the maximum number of recommendations returned in the response
   * @param maxNumSocialProofs        is the maximum number of social proofs per recommendation
   * @param maxSocialProofTypeSize    is the number of social proof types in the graph
   * @param minUserPerSocialProof     for each social proof, require a minimum number of users to be valid
   * @param socialProofTypes          is the list of valid social proofs, (i.e. Create, Like etc)
   * @param maxRightNodeAgeInMillis   Max right node age in millisecond, such as moment age
   * @param maxEdgeAgeInMillis        Max edge age in millisecond such as like edge age
   * @param resultFilterChain         is the chain of filters to be applied
   */
  public TopSecondDegreeByCountRequestForMoment(
    long queryNode,
    Long2DoubleMap leftSeedNodesWithWeight,
    LongSet toBeFiltered,
    int maxNumResults,
    int maxNumSocialProofs,
    int maxSocialProofTypeSize,
    Map<Byte, Integer> minUserPerSocialProof,
    byte[] socialProofTypes,
    long maxRightNodeAgeInMillis,
    long maxEdgeAgeInMillis,
    ResultFilterChain resultFilterChain) {
    super(queryNode, leftSeedNodesWithWeight, toBeFiltered, maxSocialProofTypeSize,
        socialProofTypes, maxRightNodeAgeInMillis, maxEdgeAgeInMillis, resultFilterChain);
    this.maxNumResults = maxNumResults;
    this.maxNumSocialProofs = maxNumSocialProofs;
    this.minUserPerSocialProof = minUserPerSocialProof;
  }

  public Map<Byte, Integer> getMinUserPerSocialProof() { return minUserPerSocialProof; }

  public int getMaxNumResults() { return maxNumResults; }

  public int getMaxNumSocialProofs() { return maxNumSocialProofs; }

  public RecommendationType getRecommendationType() { return recommendationType; }

}


text:
package org.arcticsoft.bluebearlive.core.handler.abstracts;

import com.mrheadshot62.api.Packet;
import com.mrheadshot62.api.types.ImagePacket;

/**
 * Created by novak on 05.01.2017.
 */
public abstract class AImageHandler{

    public void handlePacket(Packet p) {
        try{
            ImagePacket imagePacket = (ImagePacket)p.getData();
            handleImagePacket(imagePacket);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    protected abstract void handleImagePacket(ImagePacket imagePacket);
}


text:
"use strict";

var fs = require('fs');

var databaseP = require('./databaseClientP');

var dropTableScript = fs.readFileSync( require.resolve('./dropAllTables.sql') ).toString();

module.exports = function(){
    if(process.env.NODE_ENV !== 'test')
        console.warn('\n\t=====\n\nWARNING! Dropping all tables!\n\n\t=====\n');

    return new Promise(function(resolve, reject){
        databaseP.then(function(db){
            db.query(dropTableScript, function(err, result) {
                if(err) reject(err); else resolve(result);
            });
        }).catch(resolve);
    });
};


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

@Component({
    selector: 'app-directive',
    templateUrl: './directive.component.html',
    styleUrls: ['./directive.component.scss']
})
export class DirectiveComponent implements OnInit {

    @Input() today: number;
    @Input() timeAgo: string;
    @Input() value: number;

    ngOnInit() {
    }

}


text: This repository contains code for projects made related to WebDev.


text:
class CXFA_AdjustData final : public CXFA_Node {
 public:
  CXFA_AdjustData(CXFA_Document* doc, XFA_PacketType packet);
  ~CXFA_AdjustData() override;
};

#endif  // XFA_FXFA_PARSER_CXFA_ADJUSTDATA_H_


text:
package de.nedelosk.modularmachines.api.modules;

import de.nedelosk.modularmachines.api.modules.state.IModuleState;
import de.nedelosk.modularmachines.api.recipes.IRecipe;
import de.nedelosk.modularmachines.api.recipes.RecipeItem;

public interface IModuleRecipe extends IModule {

	/**
	 * @return The current recipe of the module state.
	 */
	IRecipe getCurrentRecipe(IModuleState state);

	/**
	 * Set the current recipe of the module state.
	 */
	void setCurrentRecipe(IModuleState state, IRecipe recipe);

	/**
	 * @return True if the stack is a input, of a recipe, at the matching position.
	 */
	boolean isRecipeInput(IModuleState state, RecipeItem item);

}


text:
//* Bobo Browse Engine - High performance faceted/parametric search implementation
//* that handles various types of semi-structured data.  Originally written in Java.
//*
//* Ported and adapted for C# by Shad Storhaug.
//*
//* Copyright (C) 2005-2015  John Wang
//*
//* Licensed under the Apache License, Version 2.0 (the "License");
//* you may not use this file except in compliance with the License.
//* You may obtain a copy of the License at
//*
//*   http://www.apache.org/licenses/LICENSE-2.0
//*
//* Unless required by applicable law or agreed to in writing, software
//* distributed under the License is distributed on an "AS IS" BASIS,
//* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//* See the License for the specific language governing permissions and
//* limitations under the License.

// Version compatibility level: 4.2.0
namespace BoboBrowse.Net.Sort
{
    using Lucene.Net.Index;

    public class MultiDocIdComparerSource : DocComparerSource
    {
        private readonly DocComparerSource[] m_compSources;

        public MultiDocIdComparerSource(DocComparerSource[] compSources)
        {
            m_compSources = compSources;
        }

        public override DocComparer GetComparer(AtomicReader reader, int docbase)
        {
            DocComparer[] comparers = new DocComparer[m_compSources.Length];
            for (int i = 0; i < m_compSources.Length; ++i)
            {
                comparers[i] = m_compSources[i].GetComparer(reader, docbase);
            }
            return new MultiDocIdComparer(comparers);
        }
    }
}


text:
void simon(int);	//define a function

int main()
{
	using namespace std;
	simon(3);
	return 0;

}

void simon(int n)
{
	using namespace std;

	cout << "number by simon is : " << n << endl;

}


text:
<?php
namespace Concrete\Core\Attribute;

use HtmlObject\Element;

/**
 * Formerly the only way to specify an icon – lets attributes provide one as icon.png
 * in their folder.
 *
 * \@package Concrete\Core\Attribute
 */
class FileIconFormatter implements IconFormatterInterface
{
    protected $controller;

    public function __construct(Controller $controller)
    {
        $this->controller = $controller;
    }

    public function getListIconElement()
    {
        $env = \Environment::get();
        $type = $this->controller->getAttributeType();
        $url = $env->getURL(
            implode('/', array(DIRNAME_ATTRIBUTES . '/' . $type->getAttributeTypeHandle() . '/' . FILENAME_BLOCK_ICON)),
            $type->getPackageHandle()
        );

        $img = new Element('img');
        $img->addClass('ccm-attribute-icon')
            ->src($url)
            ->width(16)
            ->height(16);

        return $img;
    }
}


text:
package com.newproject.jordi.hackupc17.Entities;

/**
 * Created by jordi on 4/3/17.
 */

public class UserRanking {
    String name;
    String score;
    String position;
    int face;

    public UserRanking(String name, String score, String position, int face) {
        this.name = name;
        this.score = score;
        this.position = position;
        this.face = face;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getScore() {
        return score;
    }

    public void setScore(String score) {
        this.score = score;
    }

    public String getPosition() {
        return position;
    }

    public void setPosition(String position) {
        this.position = position;
    }

    public int getFace() {
        return face;
    }

    public void setFace(int face) {
        this.face = face;
    }
}


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Primula dubernardiana Forrest

### Remarks
null


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Text;
using System.Threading.Tasks;

namespace MQTTLib.Protocol {
    public class EncodedDataField : IByteEncodable {

        public UInt16 Length
        {
            get { return (UInt16)Data.Count(); }
        }

        public IEnumerable<byte> Data { get; }

        public EncodedDataField(IEnumerable<byte> data) {
            Data = data;
        }

        public EncodedDataField(Stream byteStream)
        {
            byte[] lengthBytes = new byte[2];
            byteStream.Read(lengthBytes, 0, 2);

            UInt16 length = (UInt16)lengthBytes[0];
            length <<= 8;
            length |= lengthBytes[1];

            byte[] dataBuffer = new byte[length];
            byteStream.Read(dataBuffer, 0, length);
            Data = dataBuffer;
        }

        public IEnumerable<byte> Encode() {

            UInt16 length = (UInt16)Data.Count();
            return new byte[] { length.MostSignificantByte(), length.LeastSignificantByte() }.Concat(Data);
        }

        public static implicit operator byte[](EncodedDataField edf) {
            return edf.Data.ToArray();
        }
    }
}


text:
const Stage = () => {
  const render = (stage) => {
    const stageProps = {
      class: `stage stage-${stage.status.toLowerCase()}`,
    };
    return ['div', stageProps, stage.name];
  };

  return {
    render,
  };
};

module.exports = Stage;


text:
<?xml version="1.0"?>
<manuscript>
  <url/>
  <title>Book of Hours, Use of Paris</title>
  <shelfmark>Lewis E 96</shelfmark>
  <quire n="1">
    <leaf n="1" mode="original" single="false" folio_number="1" conjoin="6" position="1" opposite="6"/>
    <leaf n="2" mode="original" single="false" folio_number="2" conjoin="5" position="2" opposite="5"/>
    <leaf n="3" mode="original" single="false" folio_number="3" conjoin="4" position="3" opposite="4"/>
    <leaf n="4" mode="original" single="false" folio_number="4" conjoin="3" position="4" opposite="3"/>
    <leaf n="5" mode="original" single="false" folio_number="5" conjoin="2" position="5" opposite="2"/>
    <leaf n="6" mode="original" single="false" folio_number="6" conjoin="1" position="6" opposite="1"/>
  </quire>
  <quire n="2">
    <leaf n="1" mode="original" single="false" folio_number="7" conjoin="6" position="1" opposite="6"/>
    <leaf n="2" mode="original" single="false" folio_number="8" conjoin="5" position="2" opposite="5"/>
    <leaf n="3" mode="original" single="false" folio_number="9" conjoin="4" position="3" opposite="4"/>
    <leaf n="4" mode="original" single="false" folio_number="10" conjoin="3" position="4" opposite="3"/>
    <leaf n="5" mode="original" single="false" folio_number="11" conjoin="2" position="5" opposite="2"/>
    <leaf n="6" mode="original" single="false" folio_number="12" conjoin="1" position="6" opposite="1"/>
  </quire>
  <quire n="3">
    <leaf n="1" mode="original" single="false" folio_number="13" conjoin="6" position="1" opposite="6"/>
    <leaf n="2" mode="original" single="false" folio_number="14" conjoin="5" position="2" opposite="5"/>
    <leaf n="3" mode="original" single="false" folio_number="15" conjoin="4" position="3" opposite="4"/>
    <leaf n="4" mode="original" single="false" folio_number="16" conjoin="3" position="4" opposite="3"/>
    <leaf n="5" mode="original" single="false" folio_number="17" conjoin="2" position="5" opposite="2"/>
    <leaf n="6" mode="original" single="false" folio_number="18" conjoin="1" position="6" opposite="1"/>
  </quire>
  <quire n="4">
    <leaf n="1" mode="original" single="false" folio_number="19" conjoin="6" position="1" opposite="6"/>
    <leaf n="2" mode="original" single="false" folio_number="20" conjoin="5" position="2" opposite="5"/>
    <leaf n="3" mode="original" single="false" folio_number="21" conjoin="4" position="3" opposite="4"/>
    <leaf n="4" mode="original" single="false" folio_number="22" conjoin="3" position="4" opposite="3"/>
    <leaf n="5" mode="original" single="false" folio_number="23" conjoin="2" position="5" opposite="2"/>
    <leaf n="6" mode="original" single="false" folio_number="24" conjoin="1" position="6" opposite="1"/>
  </quire>
  <quire n="5">
    <leaf n="1" mode="original" single="false" folio_number="25" conjoin="6" position="1" opposite="6"/>
    <leaf n="2" mode="original" single="false" folio_number="26" conjoin="5" position="2" opposite="5"/>
    <leaf n="3" mode="original" single="false" folio_number="27" conjoin="4" position="3" opposite="4"/>
    <leaf n="4" mode="original" single="false" folio_number="28" conjoin="3" position="4" opposite="3"/>
    <leaf n="5" mode="original" single="false" folio_number="29" conjoin="2" position="5" opposite="2"/>
    <leaf n="6" mode="original" single="false" folio_number="30" conjoin="1" position="6" opposite="1"/>
  </quire>
  <quire n="6">
    <leaf n="1" mode="original" single="false" folio_number="31" conjoin="8" position="1" opposite="8"/>
    <leaf n="2" mode="original" single="false" folio_number="32" conjoin="7" position="2" opposite="7"/>
    <leaf n="3" mode="original" single="false" folio_number="33" conjoin="6" position="3" opposite="6"/>
    <leaf n="4" mode="original" single="false" folio_number="34" conjoin="5" position="4" opposite="5"/>
    <leaf n="5" mode="original" single="false" folio_number="35" conjoin="4" position="5" opposite="4"/>
    <leaf n="6" mode="original" single="false" folio_number="36" conjoin="3" position="6" opposite="3"/>
    <leaf n="7" mode="original" single="false" folio_number="37" conjoin="2" position="7" opposite="2"/>
    <leaf n="8" mode="original" single="false" folio_number="38" conjoin="1" position="8" opposite="1"/>
  </quire>
  <quire n="7">
    <leaf n="1" mode="original" single="false" folio_number="39" conjoin="8" position="1" opposite="8"/>
    <leaf n="2" mode="original" single="false" folio_number="40" conjoin="7" position="2" opposite="7"/>
    <leaf n="3" mode="original" single="false" folio_number="41" conjoin="6" position="3" opposite="6"/>
    <leaf n="4" mode="original" single="false" folio_number="42" conjoin="5" position="4" opposite="5"/>
    <leaf n="5" mode="original" single="false" folio_number="43" conjoin="4" position="5" opposite="4"/>
    <leaf n="6" mode="original" single="false" folio_number="44" conjoin="3" position="6" opposite="3"/>
    <leaf n="7" mode="original" single="false" folio_number="45" conjoin="2" position="7" opposite="2"/>
    <leaf n="8" mode="original" single="false" folio_number="46" conjoin="1" position="8" opposite="1"/>
  </quire>
  <quire n="8">
    <leaf n="1" mode="original" single="false" folio_number="47" conjoin="11" position="1" opposite="12"/>
    <leaf n="2" mode="original" single="false" folio_number="48" conjoin="10" position="2" opposite="11"/>
    <leaf n="3" mode="original" single="false" folio_number="49" conjoin="9" position="3" opposite="10"/>
    <leaf n="" conjoin="8" position="4" opposite="9"/>
    <leaf n="4" mode="original" single="false" folio_number="50" conjoin="7" position="5" opposite="8"/>
    <leaf n="5" mode="original" single="false" folio_number="51" conjoin="6" position="6" opposite="7"/>
    <leaf n="6" mode="original" single="false" folio_number="52" conjoin="5" position="7" opposite="6"/>
    <leaf n="7" mode="original" single="false" folio_number="53" conjoin="4" position="8" opposite="5"/>
    <leaf n="8" mode="original" single="true" folio_number="54" conjoin="" position="9" opposite="4"/>
    <leaf n="9" mode="original" single="false" folio_number="55" conjoin="3" position="10" opposite="3"/>
    <leaf n="10" mode="original" single="false" folio_number="56" conjoin="2" position="11" opposite="2"/>
    <leaf n="11" mode="original" single="false" folio_number="57" conjoin="1" position="12" opposite="1"/>
  </quire>
  <quire n="9">
    <leaf n="1" mode="original" single="false" folio_number="58" conjoin="6" position="1" opposite="6"/>
    <leaf n="2" mode="original" single="false" folio_number="59" conjoin="5" position="2" opposite="5"/>
    <leaf n="3" mode="original" single="false" folio_number="60" conjoin="4" position="3" opposite="4"/>
    <leaf n="4" mode="original" single="false" folio_number="61" conjoin="3" position="4" opposite="3"/>
    <leaf n="5" mode="original" single="false" folio_number="62" conjoin="2" position="5" opposite="2"/>
    <leaf n="6" mode="original" single="false" folio_number="63" conjoin="1" position="6" opposite="1"/>
  </quire>
  <quire n="10">
    <leaf n="1" mode="original" single="false" folio_number="64" conjoin="12" position="1" opposite="14"/>
    <leaf n="2" mode="original" single="false" folio_number="65" conjoin="11" position="2" opposite="13"/>
    <leaf n="3" mode="original" single="false" folio_number="66" conjoin="10" position="3" opposite="12"/>
    <leaf n="" conjoin="9" position="4" opposite="11"/>
    <leaf n="4" mode="original" single="false" folio_number="67" conjoin="8" position="5" opposite="10"/>
    <leaf n="5" mode="original" single="true" folio_number="68" conjoin="" position="6" opposite="9"/>
    <leaf n="6" mode="original" single="false" folio_number="69" conjoin="7" position="7" opposite="8"/>
    <leaf n="7" mode="original" single="false" folio_number="70" conjoin="6" position="8" opposite="7"/>
    <leaf n="" conjoin="5" position="9" opposite="6"/>
    <leaf n="8" mode="original" single="false" folio_number="71" conjoin="4" position="10" opposite="5"/>
    <leaf n="9" mode="original" single="true" folio_number="72" conjoin="" position="11" opposite="4"/>
    <leaf n="10" mode="original" single="false" folio_number="73" conjoin="3" position="12" opposite="3"/>
    <leaf n="11" mode="original" single="false" folio_number="74" conjoin="2" position="13" opposite="2"/>
    <leaf n="12" mode="original" single="false" folio_number="75" conjoin="1" position="14" opposite="1"/>
  </quire>
  <quire n="11">
    <leaf n="1" mode="original" single="false" folio_number="76" conjoin="10" position="1" opposite="10"/>
    <leaf n="2" mode="original" single="false" folio_number="77" conjoin="9" position="2" opposite="9"/>
    <leaf n="3" mode="original" single="false" folio_number="78" conjoin="8" position="3" opposite="8"/>
    <leaf n="4" mode="original" single="false" folio_number="79" conjoin="7" position="4" opposite="7"/>
    <leaf n="5" mode="original" single="false" folio_number="80" conjoin="6" position="5" opposite="6"/>
    <leaf n="6" mode="original" single="false" folio_number="81" conjoin="5" position="6" opposite="5"/>
    <leaf n="7" mode="original" single="false" folio_number="82" conjoin="4" position="7" opposite="4"/>
    <leaf n="8" mode="original" single="false" folio_number="83" conjoin="3" position="8" opposite="3"/>
    <leaf n="9" mode="original" single="false" folio_number="84" conjoin="2" position="9" opposite="2"/>
    <leaf n="10" mode="original" single="false" folio_number="85" conjoin="1" position="10" opposite="1"/>
  </quire>
  <quire n="12">
    <leaf n="1" mode="original" single="false" folio_number="86" conjoin="8" position="1" opposite="8"/>
    <leaf n="2" mode="original" single="false" folio_number="87" conjoin="7" position="2" opposite="7"/>
    <leaf n="3" mode="original" single="false" folio_number="88" conjoin="6" position="3" opposite="6"/>
    <leaf n="4" mode="original" single="false" folio_number="89" conjoin="5" position="4" opposite="5"/>
    <leaf n="5" mode="original" single="false" folio_number="90" conjoin="4" position="5" opposite="4"/>
    <leaf n="6" mode="original" single="false" folio_number="91" conjoin="3" position="6" opposite="3"/>
    <leaf n="7" mode="original" single="false" folio_number="92" conjoin="2" position="7" opposite="2"/>
    <leaf n="8" mode="original" single="false" folio_number="93" conjoin="1" position="8" opposite="1"/>
  </quire>
  <quire n="13">
    <leaf n="1" mode="original" single="false" folio_number="94" conjoin="4" position="1" opposite="4"/>
    <leaf n="2" mode="original" single="false" folio_number="95" conjoin="3" position="2" opposite="3"/>
    <leaf n="3" mode="original" single="false" folio_number="96" conjoin="2" position="3" opposite="2"/>
    <leaf n="4" mode="original" single="false" folio_number="97" conjoin="1" position="4" opposite="1"/>
  </quire>
  <quire n="14">
    <leaf n="1" mode="original" single="false" folio_number="98" conjoin="7" position="1" opposite="8"/>
    <leaf n="" conjoin="6" position="2" opposite="7"/>
    <leaf n="2" mode="original" single="false" folio_number="99" conjoin="5" position="3" opposite="6"/>
    <leaf n="3" mode="original" single="false" folio_number="100" conjoin="4" position="4" opposite="5"/>
    <leaf n="4" mode="original" single="false" folio_number="101" conjoin="3" position="5" opposite="4"/>
    <leaf n="5" mode="original" single="false" folio_number="102" conjoin="2" position="6" opposite="3"/>
    <leaf n="6" mode="original" single="true" folio_number="103" conjoin="" position="7" opposite="2"/>
    <leaf n="7" mode="original" single="false" folio_number="104" conjoin="1" position="8" opposite="1"/>
  </quire>
  <quire n="15">
    <leaf n="1" mode="original" single="false" folio_number="105" conjoin="8" position="1" opposite="8"/>
    <leaf n="2" mode="original" single="false" folio_number="106" conjoin="7" position="2" opposite="7"/>
    <leaf n="3" mode="original" single="false" folio_number="107" conjoin="6" position="3" opposite="6"/>
    <leaf n="4" mode="original" single="false" folio_number="108" conjoin="5" position="4" opposite="5"/>
    <leaf n="5" mode="original" single="false" folio_number="109" conjoin="4" position="5" opposite="4"/>
    <leaf n="6" mode="original" single="false" folio_number="110" conjoin="3" position="6" opposite="3"/>
    <leaf n="7" mode="original" single="false" folio_number="111" conjoin="2" position="7" opposite="2"/>
    <leaf n="8" mode="original" single="false" folio_number="112" conjoin="1" position="8" opposite="1"/>
  </quire>
  <quire n="16">
    <leaf n="1" mode="original" single="false" folio_number="113" conjoin="8" position="1" opposite="8"/>
    <leaf n="2" mode="original" single="false" folio_number="114" conjoin="7" position="2" opposite="7"/>
    <leaf n="3" mode="original" single="false" folio_number="115" conjoin="6" position="3" opposite="6"/>
    <leaf n="4" mode="original" single="false" folio_number="116" conjoin="5" position="4" opposite="5"/>
    <leaf n="5" mode="original" single="false" folio_number="117" conjoin="4" position="5" opposite="4"/>
    <leaf n="6" mode="original" single="false" folio_number="118" conjoin="3" position="6" opposite="3"/>
    <leaf n="7" mode="original" single="false" folio_number="119" conjoin="2" position="7" opposite="2"/>
    <leaf n="8" mode="original" single="false" folio_number="120" conjoin="1" position="8" opposite="1"/>
  </quire>
  <quire n="17">
    <leaf n="1" mode="original" single="false" folio_number="121" conjoin="8" position="1" opposite="8"/>
    <leaf n="2" mode="original" single="false" folio_number="122" conjoin="7" position="2" opposite="7"/>
    <leaf n="3" mode="original" single="false" folio_number="123" conjoin="6" position="3" opposite="6"/>
    <leaf n="4" mode="original" single="false" folio_number="124" conjoin="5" position="4" opposite="5"/>
    <leaf n="5" mode="original" single="false" folio_number="125" conjoin="4" position="5" opposite="4"/>
    <leaf n="6" mode="original" single="false" folio_number="126" conjoin="3" position="6" opposite="3"/>
    <leaf n="7" mode="original" single="false" folio_number="127" conjoin="2" position="7" opposite="2"/>
    <leaf n="8" mode="original" single="false" folio_number="128" conjoin="1" position="8" opposite="1"/>
  </quire>
  <quire n="18">
    <leaf n="1" mode="original" single="false" folio_number="129" conjoin="6" position="1" opposite="6"/>
    <leaf n="2" mode="original" single="false" folio_number="130" conjoin="5" position="2" opposite="5"/>
    <leaf n="3" mode="original" single="false" folio_number="131" conjoin="4" position="3" opposite="4"/>
    <leaf n="4" mode="original" single="false" folio_number="132" conjoin="3" position="4" opposite="3"/>
    <leaf n="5" mode="original" single="false" folio_number="133" conjoin="2" position="5" opposite="2"/>
    <leaf n="6" mode="original" single="false" folio_number="134" conjoin="1" position="6" opposite="1"/>
  </quire>
  <quire n="19">
    <leaf n="1" mode="original" single="false" folio_number="135" conjoin="8" position="1" opposite="8"/>
    <leaf n="2" mode="original" single="false" folio_number="136" conjoin="7" position="2" opposite="7"/>
    <leaf n="3" mode="original" single="false" folio_number="137" conjoin="6" position="3" opposite="6"/>
    <leaf n="4" mode="original" single="false" folio_number="138" conjoin="5" position="4" opposite="5"/>
    <leaf n="5" mode="original" single="false" folio_number="139" conjoin="4" position="5" opposite="4"/>
    <leaf n="6" mode="original" single="false" folio_number="140" conjoin="3" position="6" opposite="3"/>
    <leaf n="7" mode="original" single="false" folio_number="141" conjoin="2" position="7" opposite="2"/>
    <leaf n="8" mode="original" single="false" folio_number="142" conjoin="1" position="8" opposite="1"/>
  </quire>
  <quire n="20">
    <leaf n="1" mode="original" single="false" folio_number="143" conjoin="10" position="1" opposite="10"/>
    <leaf n="2" mode="original" single="false" folio_number="144" conjoin="9" position="2" opposite="9"/>
    <leaf n="3" mode="original" single="false" folio_number="145" conjoin="8" position="3" opposite="8"/>
    <leaf n="4" mode="original" single="false" folio_number="146" conjoin="7" position="4" opposite="7"/>
    <leaf n="5" mode="original" single="false" folio_number="147" conjoin="6" position="5" opposite="6"/>
    <leaf n="6" mode="original" single="false" folio_number="148" conjoin="5" position="6" opposite="5"/>
    <leaf n="7" mode="original" single="false" folio_number="149" conjoin="4" position="7" opposite="4"/>
    <leaf n="8" mode="original" single="false" folio_number="150" conjoin="3" position="8" opposite="3"/>
    <leaf n="9" mode="original" single="false" folio_number="151" conjoin="2" position="9" opposite="2"/>
    <leaf n="10" mode="original" single="false" folio_number="152" conjoin="1" position="10" opposite="1"/>
  </quire>
  <quire n="21">
    <leaf n="1" mode="original" single="false" folio_number="153" conjoin="8" position="1" opposite="8"/>
    <leaf n="2" mode="original" single="false" folio_number="154" conjoin="7" position="2" opposite="7"/>
    <leaf n="3" mode="original" single="false" folio_number="155" conjoin="6" position="3" opposite="6"/>
    <leaf n="4" mode="original" single="false" folio_number="156" conjoin="5" position="4" opposite="5"/>
    <leaf n="5" mode="original" single="false" folio_number="157" conjoin="4" position="5" opposite="4"/>
    <leaf n="6" mode="original" single="false" folio_number="158" conjoin="3" position="6" opposite="3"/>
    <leaf n="7" mode="original" single="false" folio_number="159" conjoin="2" position="7" opposite="2"/>
    <leaf n="8" mode="original" single="false" folio_number="160" conjoin="1" position="8" opposite="1"/>
  </quire>
</manuscript>


text:
package org.apache.activemq.artemis.tests.integration.client;

import org.apache.activemq.artemis.api.core.QueueConfiguration;
import org.apache.activemq.artemis.api.core.client.ClientConsumer;
import org.apache.activemq.artemis.api.core.client.ClientMessage;
import org.apache.activemq.artemis.api.core.client.ClientProducer;
import org.apache.activemq.artemis.api.core.client.ClientSession;
import org.apache.activemq.artemis.api.core.client.ClientSessionFactory;
import org.apache.activemq.artemis.api.core.client.ServerLocator;
import org.apache.activemq.artemis.core.server.ActiveMQServer;
import org.apache.activemq.artemis.tests.util.ActiveMQTestBase;
import org.apache.activemq.artemis.utils.RandomUtil;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

public class SimpleSendMultipleQueuesTest extends ActiveMQTestBase {

   public static final String address = "testaddress";

   public static final String queueName = "testqueue";

   private ActiveMQServer server;

   private ClientSession session;

   private ClientProducer producer;

   private ClientConsumer consumer1;

   private ClientConsumer consumer2;

   private ClientConsumer consumer3;

   private ServerLocator locator;

   @Test
   public void testSimpleSend() throws Exception {
      for (int i = 0; i < 1000; i++) {
         ClientMessage message = session.createMessage(false);

         final String body = RandomUtil.randomString();

         message.getBodyBuffer().writeString(body);

         //  log.debug("sending message");
         producer.send(message);
         // log.debug("sent message");

         ClientMessage received1 = consumer1.receive(1000);
         Assert.assertNotNull(received1);
         Assert.assertEquals(body, received1.getBodyBuffer().readString());

         ClientMessage received2 = consumer2.receive(1000);
         Assert.assertNotNull(received2);
         Assert.assertEquals(body, received2.getBodyBuffer().readString());

         ClientMessage received3 = consumer3.receive(1000);
         Assert.assertNotNull(received3);
         Assert.assertEquals(body, received3.getBodyBuffer().readString());
      }
   }

   @Override
   @Before
   public void setUp() throws Exception {
      super.setUp();

      server = createServer(false, true);

      server.start();

      locator = createNettyNonHALocator();

      ClientSessionFactory cf = createSessionFactory(locator);

      session = cf.createSession();

      session.createQueue(new QueueConfiguration("queue1").setAddress(SimpleSendMultipleQueuesTest.address));
      session.createQueue(new QueueConfiguration("queue2").setAddress(SimpleSendMultipleQueuesTest.address));
      session.createQueue(new QueueConfiguration("queue3").setAddress(SimpleSendMultipleQueuesTest.address));

      producer = session.createProducer(SimpleSendMultipleQueuesTest.address);

      consumer1 = session.createConsumer("queue1");

      consumer2 = session.createConsumer("queue2");

      consumer3 = session.createConsumer("queue3");

      session.start();
   }
}


text:
class CreateOrders < ActiveRecord::Migration[5.2]
  def change
    create_table :orders do |t|
      t.belongs_to :user, index: true
      t.datetime :expired_at
      t.decimal :money, precision: 10, scale: 2

      t.timestamps null: false
    end
  end
end


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
An. Jard. bot. Madr. 1: 187 (1941)

#### Original name
Phyllosticta furcraeae Caball.

### Remarks
null


text:
const { expect } = require('chai');

function remove (app, serviceName) {
  describe('remove()', () => {
    it('should return empty array if no items have been removed (bulk)', () => {
      return app.service(serviceName)
        .remove(
          null,
          { query: { id: 'better-luck-next-time' } }
        )
        .then(results => {
          expect(results).to.be.an('array').and.be.empty;
        });
    });

    it('should remove an item with a specified parent', () => {
      return app.service('aka')
        .create({ name: 'Bobster', parent: 'bob', id: 'bobAka' })
        .then(() => {
          return app.service('aka').remove(
            'bobAka',
            { query: { parent: 'bob' } }
          );
        })
        .then(result => {
          expect(result.name).to.equal('Bobster');
        });
    });

    it('should remove items which have a parent (bulk)', () => {
      return app.service('aka')
        .create([
          { name: 'remove me', no: 1, parent: 'bob', aka: 'alias' },
          { name: 'remove me', no: 2, parent: 'moody', aka: 'alias' }
        ])
        .then(() => app.service('aka')
          .remove(
            null,
            { query: { name: 'remove me', $sort: { no: 1 } } }
          )
        )
        .then(results => {
          expect(results.length).to.equal(2);
          expect(results[0].name).to.equal('remove me');
          expect(results[0]._meta._parent).to.equal('bob');
          expect(results[1].name).to.equal('remove me');
          expect(results[1]._meta._parent).to.equal('moody');
        });
    });

    it('should remove items selected with pagination (bulk)', () => {
      return app.service(serviceName)
        .create([
          { name: 'remove me', no: 1 },
          { name: 'remove me', no: 2 }
        ])
        .then(() => app.service(serviceName)
          .remove(
            null,
            {
              query: { name: 'remove me', $sort: { no: 1 } },
              paginate: { default: 10, max: 10 }
            }
          )
        )
        .then(results => {
          expect(results).to.have.lengthOf(2);
          expect(results[0]).to.include({ name: 'remove me', no: 1 });
          expect(results[1]).to.include({ name: 'remove me', no: 2 });
        });
    });
  });
}

module.exports = remove;


text:
package com.quiptiq.wurmrest.api;

import javax.annotation.concurrent.Immutable;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.hibernate.validator.constraints.NotEmpty;

/**
 * Server announcement
 */
@Immutable
public class Announcement {
    private final String message;

    @JsonCreator
    public Announcement(@JsonProperty("message") @NotEmpty String message) {
        this.message = message;
    }

    public String getMessage() {
        return message;
    }
}


text:
package com.hazelcast.spi.impl.operationservice.impl;

import com.hazelcast.cluster.Member;
import com.hazelcast.core.IndeterminateOperationState;
import com.hazelcast.core.LocalMemberResetException;
import com.hazelcast.core.MemberLeftException;
import com.hazelcast.cp.CPGroupId;
import com.hazelcast.cp.CPMember;
import com.hazelcast.cp.exception.LeaderDemotedException;
import com.hazelcast.cp.exception.NotLeaderException;
import com.hazelcast.cp.exception.StaleAppendRequestException;
import com.hazelcast.cp.internal.IndeterminateOperationStateAware;
import com.hazelcast.cluster.Address;
import com.hazelcast.spi.exception.CallerNotMemberException;
import com.hazelcast.spi.exception.TargetNotMemberException;
import com.hazelcast.spi.impl.operationservice.ExceptionAction;
import com.hazelcast.spi.impl.operationservice.Operation;
import com.hazelcast.spi.impl.operationservice.impl.RaftInvocationContext.MemberCursor;

import static com.hazelcast.spi.impl.operationservice.ExceptionAction.RETRY_INVOCATION;
import static com.hazelcast.spi.impl.operationservice.ExceptionAction.THROW_EXCEPTION;
import static com.hazelcast.spi.impl.operationservice.InvocationBuilder.DEFAULT_DESERIALIZE_RESULT;

/**
 * A {@link Invocation} implementation that realizes an operation invocation on the leader node of the given Raft group.
 * Internally handles Raft-related exceptions.
 */
public class RaftInvocation extends Invocation<CPMember> {

    private final RaftInvocationContext raftInvocationContext;
    private final CPGroupId groupId;
    private volatile MemberCursor memberCursor;
    private volatile CPMember lastInvocationEndpoint;
    private volatile Throwable indeterminateException;

    public RaftInvocation(Context context, RaftInvocationContext raftInvocationContext, CPGroupId groupId, Operation op,
                          int retryCount, long retryPauseMillis, long callTimeoutMillis) {
        super(context, op, null, retryCount, retryPauseMillis, callTimeoutMillis, DEFAULT_DESERIALIZE_RESULT, null);
        this.raftInvocationContext = raftInvocationContext;
        this.groupId = groupId;

        int partitionId = raftInvocationContext.getCPGroupPartitionId(groupId);
        op.setPartitionId(partitionId);
    }

    @Override
    CPMember getInvocationTarget() {
        CPMember target = getTargetEndpoint();
        lastInvocationEndpoint = target;
        return target;
    }

    @Override
    Address toTargetAddress(CPMember target) {
        return target.getAddress();
    }

    @Override
    Member toTargetMember(CPMember target) {
        // CPMember.uuid can be different from Member.uuid
        // During split-brain merge, Member.uuid changes but CPMember.uuid remains the same.
        return context.clusterService.getMember(target.getAddress());
    }

    @Override
    void notifyNormalResponse(Object value, int expectedBackups) {
        assert !(value instanceof Throwable) : "Throwable value " + value + " not allowed";

        super.notifyNormalResponse(value, expectedBackups);
        // TODO [basri] maybe we should update known leader only if the result is not an exception?
        raftInvocationContext.setKnownLeader(groupId, lastInvocationEndpoint);
    }

    @Override
    void notifyError(Object error) {
        if (error instanceof Throwable
                && ((Throwable) error).getCause() instanceof LocalMemberResetException) {
            // Raft does not care about split-brain merge.
            return;
        }
        super.notifyError(error);
    }

    @Override
    protected void notifyThrowable(Throwable cause, int expectedBackups) {
        if (!(cause instanceof IndeterminateOperationState) && indeterminateException != null && isRetryable(cause)) {
            cause = indeterminateException;
        }
        super.notifyThrowable(cause, expectedBackups);
    }

    @Override
    protected ExceptionAction onException(Throwable t) {
        raftInvocationContext.updateKnownLeaderOnFailure(groupId, t);

        if (t instanceof IndeterminateOperationState) {
            if (isRetryableOnIndeterminateOperationState()) {
                if (indeterminateException == null) {
                    indeterminateException = t;
                }
                return RETRY_INVOCATION;
            } else if (shouldFailOnIndeterminateOperationState()) {
                return THROW_EXCEPTION;
            } else if (indeterminateException == null) {
                indeterminateException = t;
            }
        }

        return isRetryable(t) ? RETRY_INVOCATION : op.onInvocationException(t);
    }

    @SuppressWarnings("checkstyle:booleanexpressioncomplexity")
    private boolean isRetryable(Object cause) {
        return cause instanceof NotLeaderException
                || cause instanceof LeaderDemotedException
                || cause instanceof StaleAppendRequestException
                || cause instanceof MemberLeftException
                || cause instanceof CallerNotMemberException
                || cause instanceof TargetNotMemberException;
    }

    @Override
    boolean skipTimeoutDetection() {
        return false;
    }

    private CPMember getTargetEndpoint() {
        CPMember target = raftInvocationContext.getKnownLeader(groupId);
        if (target != null) {
            return target;
        }

        MemberCursor cursor = memberCursor;
        if (cursor == null || !cursor.advance()) {
            cursor = raftInvocationContext.newMemberCursor();
            if (!cursor.advance()) {
                return null;
            }
            memberCursor = cursor;
        }
        return cursor.get();
    }

    private boolean isRetryableOnIndeterminateOperationState() {
        if (op instanceof IndeterminateOperationStateAware) {
            return ((IndeterminateOperationStateAware) op).isRetryableOnIndeterminateOperationState();
        }

        return false;
    }

    @Override
    protected boolean shouldFailOnIndeterminateOperationState() {
        return raftInvocationContext.shouldFailOnIndeterminateOperationState();
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
         http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <artifactId>wings-pegasus-adapter</artifactId>
  <name>Wings Pegasus Adapter</name>
  <packaging>jar</packaging>
  <description>An adapter to help Wings connect with Pegasus</description>

  <parent>
    <groupId>edu.isi.wings</groupId>
    <artifactId>wings-pegasus</artifactId>
    <version>4.2.5</version>
    <relativePath>../pom.xml</relativePath>
  </parent>

  <repositories>
    <repository>
      <id>archiva.internal</id>
      <name>Internal Release Repository</name>
      <url>https://www.wings-workflows.org/archiva/repository/internal/</url>
    </repository>
    <repository>
      <id>archiva.snapshots</id>
      <name>Internal Snapshot Repository</name>
      <url>https://www.wings-workflows.org/archiva/repository/snapshots/</url>
    </repository>
  </repositories>

  <properties>
    <log4j.version>2.16.0</log4j.version>
    <commons-io.version>2.4</commons-io.version>
    <pegasus.version>4.9.0</pegasus.version>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
  </properties>

  <!-- Dependencies -->
  <dependencies>
    <dependency>
      <groupId>edu.isi.wings</groupId>
      <artifactId>wings-planner</artifactId>
      <version>${project.version}</version>
    </dependency>

    <dependency>
      <groupId>edu.isi.pegasus</groupId>
      <artifactId>pegasus</artifactId>
      <version>${pegasus.version}</version>
    </dependency>

    <!-- log4j -->
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>${log4j.version}</version>
    </dependency>

    <!-- Apache Commons IO -->
    <dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
      <version>${commons-io.version}</version>
    </dependency>
  </dependencies>
</project>


text:
package cmd

import (
	"github.com/spf13/cobra"
	"github.com/spf13/viper"
)

// yamlCmd represents the yaml command
var sqlCmd = &cobra.Command{
	Use:   "sql",
	Short: "generate sql script from yaml file",
	Run: func(cmd *cobra.Command, args []string) {
		GenerateSQL()
	},
}

func init() {
	RootCmd.AddCommand(sqlCmd)

	sqlCmd.PersistentFlags().StringP("input", "i", ".", "directory of yaml files")
	sqlCmd.PersistentFlags().StringP("driver", "d", "mysql", "database type")
	sqlCmd.PersistentFlags().StringP("model", "m", "", "model need to generate sql script")
	viper.BindPFlag("sql_input", sqlCmd.PersistentFlags().Lookup("input"))
	viper.BindPFlag("sql_model", sqlCmd.PersistentFlags().Lookup("model"))
	viper.BindPFlag("sql_driver", sqlCmd.PersistentFlags().Lookup("driver"))
}


text:
package org.apache.asterix.dataflow.data.nontagged.serde;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;

import org.apache.asterix.om.base.ADuration;
import org.apache.hyracks.api.dataflow.value.ISerializerDeserializer;
import org.apache.hyracks.api.exceptions.HyracksDataException;

public class ADurationSerializerDeserializer implements ISerializerDeserializer<ADuration> {

    private static final long serialVersionUID = 1L;

    public static final ADurationSerializerDeserializer INSTANCE = new ADurationSerializerDeserializer();

    private ADurationSerializerDeserializer() {
    }

    @Override
    public ADuration deserialize(DataInput in) throws HyracksDataException {
        try {
            return new ADuration(in.readInt(), in.readLong());
        } catch (IOException e) {
            throw new HyracksDataException(e);
        }
    }

    @Override
    public void serialize(ADuration instance, DataOutput out) throws HyracksDataException {
        try {
            out.writeInt(instance.getMonths());
            out.writeLong(instance.getMilliseconds());
        } catch (IOException e) {
            throw new HyracksDataException(e);
        }
    }

    /**
     * Get the year-month field of the duration as an integer number of days.
     *
     * @param data
     * @param offset
     * @return
     */
    public static int getYearMonth(byte[] data, int offset) {
        return AInt32SerializerDeserializer.getInt(data, offset + getYearMonthOffset());
    }

    /**
     * Get the day-time field of the duration as an long integer number of milliseconds.
     *
     * @param data
     * @param offset
     * @return
     */
    public static long getDayTime(byte[] data, int offset) {
        return AInt64SerializerDeserializer.getLong(data, offset + getDayTimeOffset());
    }

    public static int getYearMonthOffset() {
        return 0;
    }

    public static int getDayTimeOffset() {
        return 4;
    }
}