text:
/*!
 * \file
 */

#include "config.h"

#if EXCLUDE_GENA == 0
#ifdef INCLUDE_DEVICE_APIS

#include "gena.h"
#include "httpparser.h"
#include "httpreadwrite.h"
#include "parsetools.h"
#include "ssdplib.h"
#include "statcodes.h"
#include "sysdep.h"
#include "unixutil.h"
#include "upnpapi.h"
#include "uuid.h"

#ifdef WIN32
	#define snprintf _snprintf
#endif

/*!
 * \brief Unregisters a device.
 *
 * \return UPNP_E_SUCCESS on success, GENA_E_BAD_HANDLE on failure.
 */
int genaUnregisterDevice(
	/*! [in] Device handle. */
	UpnpDevice_Handle device_handle)
{
	int ret = 0;
	struct Handle_Info *handle_info;

	HandleLock();
	if (GetHandleInfo(device_handle, &handle_info) != HND_DEVICE) {
		UpnpPrintf(UPNP_CRITICAL, GENA, __FILE__, __LINE__,
			"genaUnregisterDevice: BAD Handle: %d\n",
			device_handle);
		ret = GENA_E_BAD_HANDLE;
	} else {
		freeServiceTable(&handle_info->ServiceTable);
		ret = UPNP_E_SUCCESS;
	}
	HandleUnlock();

	return ret;
}

/*!
 * \brief Generates XML property set for notifications.
 *
 * \return UPNP_E_SUCCESS if successful else returns GENA_E_BAD_HANDLE.
 *
 * \note The XML_VERSION comment is NOT sent due to interoperability issues
 * 	with other UPnP vendors.
 */
static int GeneratePropertySet(
	/*! [in] Array of variable names (go in the event notify). */
	char **names,
	/*! [in] Array of variable values (go in the event notify). */
	char **values,
	/*! [in] number of variables. */
	int count,
	/*! [out] PropertySet node in the string format. */
	DOMString *out)
{
	char *buffer;
	int counter = 0;
	size_t size = 0;

	/*size += strlen(XML_VERSION);*/
	size += strlen(XML_PROPERTYSET_HEADER);
	size += strlen("</e:propertyset>\n\n");
	for (counter = 0; counter < count; counter++) {
		size += strlen( "<e:property>\n</e:property>\n" );
		size += 2 * strlen(names[counter]) +
			strlen(values[counter]) +
			strlen("<></>\n");
	}

	buffer = (char *)malloc(size + 1);
	if (buffer == NULL)
		return UPNP_E_OUTOF_MEMORY;
	memset(buffer, 0, size + 1);
	/*
	strcpy(buffer,XML_VERSION);
	strcat(buffer, XML_PROPERTYSET_HEADER);
	*/
	strcpy(buffer, XML_PROPERTYSET_HEADER);
	for (counter = 0; counter < count; counter++) {
		strcat(buffer, "<e:property>\n");
		sprintf(&buffer[strlen(buffer)],
			"<%s>%s</%s>\n</e:property>\n",
			names[counter],
			values[counter],
			names[counter]);
	}
	strcat(buffer, "</e:propertyset>\n\n");
	*out = ixmlCloneDOMString(buffer);
	free(buffer);

	return XML_SUCCESS;
}

/*!
 * \brief Frees memory used in notify_threads if the reference count is 0,
 * otherwise decrements the refrence count.
 */
static void free_notify_struct(
	/*! [in] Notify structure. */
	notify_thread_struct *input)
{
	(*input->reference_count)--;
	if (*input->reference_count == 0) {
		free(input->headers);
		ixmlFreeDOMString(input->propertySet);
		free(input->servId);
		free(input->UDN);
		free(input->reference_count);
	}
	free(input);
}

/*!
 * \brief Sends the notify message and returns a reply.
 *
 * \return on success returns UPNP_E_SUCCESS, otherwise returns a UPNP error.
 *
 * \note called by genaNotify
 */
static UPNP_INLINE int notify_send_and_recv(
	/*! [in] subscription callback URL (URL of the control point). */
	uri_type *destination_url,
	/*! [in] Common HTTP headers. */
	membuffer *mid_msg,
	/*! [in] The evented XML. */
	char *propertySet,
	/*! [out] The response from the control point. */
	http_parser_t *response)
{
	uri_type url;
	SOCKET conn_fd;
	membuffer start_msg;
	int ret_code;
	int err_code;
	int timeout;
	SOCKINFO info;
	const char *CRLF = "\r\n";

	/* connect */
	UpnpPrintf(UPNP_ALL, GENA, __FILE__, __LINE__,
		"gena notify to: %.*s\n",
		(int)destination_url->hostport.text.size,
		destination_url->hostport.text.buff);

	conn_fd = http_Connect(destination_url, &url);
	if (conn_fd < 0)
		/* return UPNP error */
		return UPNP_E_SOCKET_CONNECT;
	ret_code = sock_init(&info, conn_fd);
	if (ret_code) {
		sock_destroy(&info, SD_BOTH);
		return ret_code;
	}
	/* make start line and HOST header */
	membuffer_init(&start_msg);
	if (http_MakeMessage(
			&start_msg, 1, 1,
			"q" "s",
			HTTPMETHOD_NOTIFY, &url,
			mid_msg->buf) != 0) {
		membuffer_destroy(&start_msg);
		sock_destroy(&info, SD_BOTH);
		return UPNP_E_OUTOF_MEMORY;
	}
	timeout = GENA_NOTIFICATION_SENDING_TIMEOUT;
	/* send msg (note: end of notification will contain "\r\n" twice) */
	ret_code = http_SendMessage(&info, &timeout,
		"bbb",
		start_msg.buf, start_msg.length,
		propertySet, strlen(propertySet),
		CRLF, strlen(CRLF));
	if (ret_code) {
		membuffer_destroy(&start_msg);
		sock_destroy(&info, SD_BOTH);
		return ret_code;
	}
	timeout = GENA_NOTIFICATION_ANSWERING_TIMEOUT;
	ret_code = http_RecvMessage(&info, response,
		HTTPMETHOD_NOTIFY, &timeout, &err_code);
	if (ret_code) {
		membuffer_destroy(&start_msg);
		sock_destroy(&info, SD_BOTH);
		httpmsg_destroy(&response->msg);
		return ret_code;
	}
	/* should shutdown completely when closing socket */
	sock_destroy(&info, SD_BOTH);
	membuffer_destroy(&start_msg);

	return UPNP_E_SUCCESS;
}

/*!
 * \brief Function to Notify a particular subscription of a particular event.
 *
 * In general the service should NOT be blocked around this call (this may
 * cause deadlock with a client).
 *
 * NOTIFY http request is sent and the reply is processed.
 *
 * \return GENA_SUCCESS if the event was delivered, otherwise returns the
 * 	appropriate error code.
 */
static int genaNotify(
	/*! [in] Null terminated, includes all headers (including \\r\\n) except SID and SEQ. */
	char *headers,
	/*! [in] The evented XML. */
	char *propertySet,
	/*! [in] subscription to be Notified, assumes this is valid for life of function. */
	subscription *sub)
{
	size_t i;
	membuffer mid_msg;
	uri_type *url;
	http_parser_t response;
	int return_code = -1;

	membuffer_init(&mid_msg);
	if (http_MakeMessage(&mid_msg, 1, 1,
			     "s" "ssc" "sdcc",
			     headers,
			     "SID: ", sub->sid,
			     "SEQ: ", sub->ToSendEventKey) != 0) {
		membuffer_destroy(&mid_msg);
		return UPNP_E_OUTOF_MEMORY;
	}
	/* send a notify to each url until one goes thru */
	for (i = 0; i < sub->DeliveryURLs.size; i++) {
		url = &sub->DeliveryURLs.parsedURLs[i];
		return_code = notify_send_and_recv(
			url, &mid_msg, propertySet, &response);
		if (return_code == UPNP_E_SUCCESS)
			break;
	}
	membuffer_destroy(&mid_msg);
	if (return_code == UPNP_E_SUCCESS) {
		if (response.msg.status_code == HTTP_OK)
			return_code = GENA_SUCCESS;
		else {
			if (response.msg.status_code == HTTP_PRECONDITION_FAILED)
				/*Invalid SID gets removed */
				return_code = GENA_E_NOTIFY_UNACCEPTED_REMOVE_SUB;
			else
				return_code = GENA_E_NOTIFY_UNACCEPTED;
		}
		httpmsg_destroy(&response.msg);
	}

	return return_code;
}

/*!
 * \brief Thread job to Notify a control point.
 *
 * It validates the subscription and copies the subscription. Also make sure
 * that events are sent in order.
 *
 * \note calls the genaNotify to do the actual work.
 */
static void genaNotifyThread(
	/*! [in] notify thread structure containing all the headers and property set info. */
	void *input)
{
	subscription *sub;
	service_info *service;
	subscription sub_copy;
	notify_thread_struct *in = (notify_thread_struct *) input;
	int return_code;
	struct Handle_Info *handle_info;
	ThreadPoolJob job;

	memset(&job, 0, sizeof(job));

	/* This should be a HandleLock and not a HandleReadLock otherwise if there
	 * is a lot of notifications, then multiple threads will acquire a read
	 * lock and the thread which sends the notification will be blocked forever
	 * on the HandleLock at the end of this function. */
	/*HandleReadLock(); */
	HandleLock();
	/* validate context */

	if (GetHandleInfo(in->device_handle, &handle_info) != HND_DEVICE) {
		free_notify_struct(in);
		HandleUnlock();
		return;
	}

	if (!(service = FindServiceId(&handle_info->ServiceTable, in->servId, in->UDN)) ||
	    !service->active ||
	    !(sub = GetSubscriptionSID(in->sid, service)) ||
	    copy_subscription(sub, &sub_copy) != HTTP_SUCCESS) {
		free_notify_struct(in);
		HandleUnlock();
		return;
	}
#ifdef UPNP_ENABLE_NOTIFICATION_REORDERING
	/*If the event is out of order push it back to the job queue */
	if (in->eventKey != sub->ToSendEventKey) {
		TPJobInit(&job, (start_routine) genaNotifyThread, input);
		TPJobSetFreeFunction(&job, (free_function) free_notify_struct);
		TPJobSetPriority(&job, MED_PRIORITY);
		/* Sleep a little before creating another thread otherwise if there is
		 * a lot of notifications to send, the device will take 100% of the CPU
		 * to create threads and push them back to the job queue. */
		imillisleep(1);
		ThreadPoolAdd(&gSendThreadPool, &job, NULL);
		freeSubscription(&sub_copy);
		HandleUnlock();
		return;
	}
#endif

	HandleUnlock();

	/* send the notify */
	return_code = genaNotify(in->headers, in->propertySet, &sub_copy);
	freeSubscription(&sub_copy);
	HandleLock();
	if (GetHandleInfo(in->device_handle, &handle_info) != HND_DEVICE) {
		free_notify_struct(in);
		HandleUnlock();
		return;
	}
	/* validate context */
	if (!(service = FindServiceId(&handle_info->ServiceTable, in->servId, in->UDN)) ||
	    !service->active ||
	    !(sub = GetSubscriptionSID(in->sid, service))) {
		free_notify_struct(in);
		HandleUnlock();
		return;
	}
	sub->ToSendEventKey++;
	if (sub->ToSendEventKey < 0)
		/* wrap to 1 for overflow */
		sub->ToSendEventKey = 1;
	if (return_code == GENA_E_NOTIFY_UNACCEPTED_REMOVE_SUB)
		RemoveSubscriptionSID(in->sid, service);
	free_notify_struct(in);

	HandleUnlock();
}

/*!
 * \brief Allocates the GENA header.
 *
 * \note The header must be destroyed after with a call to free(), otherwise
 * there will be a memory leak.
 *
 * \return The constructed header.
 */
static char *AllocGenaHeaders(
	/*! [in] The property set string. */
	const DOMString propertySet)
{
	static const char *HEADER_LINE_1 =
		"CONTENT-TYPE: text/xml; charset=\"utf-8\"\r\n";
	static const char *HEADER_LINE_2A =
		"CONTENT-LENGTH: ";
	static const char *HEADER_LINE_2B =
		"\r\n";
	static const char *HEADER_LINE_3 =
		"NT: upnp:event\r\n";
	static const char *HEADER_LINE_4 =
		"NTS: upnp:propchange\r\n";
	char *headers = NULL;
	size_t headers_size = 0;
	int line = 0;
	int rc = 0;

	headers_size =
		strlen(HEADER_LINE_1 ) +
		strlen(HEADER_LINE_2A) + MAX_CONTENT_LENGTH +
		strlen(HEADER_LINE_2B) +
		strlen(HEADER_LINE_3 ) +
		strlen(HEADER_LINE_4 ) + 1;
	headers = (char *)malloc(headers_size);
	if (headers == NULL) {
		line = __LINE__;
		goto ExitFunction;
	}
	rc = snprintf(headers, headers_size, "%s%s%"PRIzu"%s%s%s",
		HEADER_LINE_1,
		HEADER_LINE_2A,
		strlen(propertySet) + 1,
		HEADER_LINE_2B,
		HEADER_LINE_3,
		HEADER_LINE_4);

ExitFunction:
	if (headers == NULL || rc < 0 || (unsigned int) rc >= headers_size) {
		UpnpPrintf(UPNP_ALL, GENA, __FILE__, line,
			"AllocGenaHeaders(): Error UPNP_E_OUTOF_MEMORY\n");
	}
	return headers;
}

int genaInitNotify(
	UpnpDevice_Handle device_handle,
	char *UDN,
	char *servId,
	char **VarNames,
	char **VarValues,
	int var_count,
	const Upnp_SID sid)
{
	int ret = GENA_SUCCESS;
	int line = 0;

	int *reference_count = NULL;
	char *UDN_copy = NULL;
	char *servId_copy = NULL;
	DOMString propertySet = NULL;
	char *headers = NULL;
	notify_thread_struct *thread_struct = NULL;

	subscription *sub = NULL;
	service_info *service = NULL;
	struct Handle_Info *handle_info;
	ThreadPoolJob job;

	memset(&job, 0, sizeof(job));

	UpnpPrintf(UPNP_INFO, GENA, __FILE__, __LINE__,
		"GENA BEGIN INITIAL NOTIFY");

	reference_count = (int *)malloc(sizeof (int));
	if (reference_count == NULL) {
		line = __LINE__;
		ret = UPNP_E_OUTOF_MEMORY;
		goto ExitFunction;
	}
	*reference_count = 0;

	UDN_copy = (char *)malloc(strlen(UDN) + 1);
	if (UDN_copy == NULL) {
		line = __LINE__;
		ret = UPNP_E_OUTOF_MEMORY;
		goto ExitFunction;
	}

	servId_copy = (char *)malloc(strlen(servId) + 1);
	if (servId_copy == NULL) {
		line = __LINE__;
		ret = UPNP_E_OUTOF_MEMORY;
		goto ExitFunction;
	}

	memset(UDN_copy, 0, strlen(UDN) + 1);
	strncpy(UDN_copy, UDN, strlen(UDN));
	memset(servId_copy, 0, strlen(servId) + 1);
	strncpy(servId_copy, servId, strlen(servId));

	HandleLock();

	if (GetHandleInfo(device_handle, &handle_info) != HND_DEVICE) {
		line = __LINE__;
		ret = GENA_E_BAD_HANDLE;
		goto ExitFunction;
	}

	service = FindServiceId(&handle_info->ServiceTable, servId, UDN);
	if (service == NULL) {
		line = __LINE__;
		ret = GENA_E_BAD_SERVICE;
		goto ExitFunction;
	}
	UpnpPrintf(UPNP_INFO, GENA, __FILE__, __LINE__,
		"FOUND SERVICE IN INIT NOTFY: UDN %s, ServID: %s",
		UDN, servId);

	sub = GetSubscriptionSID(sid, service);
	if (sub == NULL || sub->active) {
		line = __LINE__;
		ret = GENA_E_BAD_SID;
		goto ExitFunction;
	}
	UpnpPrintf( UPNP_INFO, GENA, __FILE__, __LINE__,
		"FOUND SUBSCRIPTION IN INIT NOTIFY: SID %s", sid);
	sub->active = 1;

	if (var_count <= 0) {
		line = __LINE__;
		ret = GENA_SUCCESS;
		goto ExitFunction;
	}

	ret = GeneratePropertySet(VarNames, VarValues, var_count, &propertySet);
	if (ret != XML_SUCCESS) {
		line = __LINE__;
		goto ExitFunction;
	}
	UpnpPrintf(UPNP_INFO, GENA, __FILE__, __LINE__,
		"GENERATED PROPERTY SET IN INIT NOTIFY: %s",
		propertySet);

	headers = AllocGenaHeaders(propertySet);
	if (headers == NULL) {
		line = __LINE__;
		ret = UPNP_E_OUTOF_MEMORY;
		goto ExitFunction;
	}

	/* schedule thread for initial notification */

	thread_struct = (notify_thread_struct *)malloc(sizeof (notify_thread_struct));
	if (thread_struct == NULL) {
		line = __LINE__;
		ret = UPNP_E_OUTOF_MEMORY;
	} else {
		*reference_count = 1;
		thread_struct->servId = servId_copy;
		thread_struct->UDN = UDN_copy;
		thread_struct->headers = headers;
		thread_struct->propertySet = propertySet;
		memset(thread_struct->sid, 0, sizeof(thread_struct->sid));
		strncpy(thread_struct->sid, sid,
			sizeof(thread_struct->sid) - 1);
		thread_struct->eventKey = sub->eventKey++;
		thread_struct->reference_count = reference_count;
		thread_struct->device_handle = device_handle;

		TPJobInit(&job, (start_routine)genaNotifyThread, thread_struct);
		TPJobSetFreeFunction(&job, (free_routine)free_notify_struct);
		TPJobSetPriority(&job, MED_PRIORITY);

		ret = ThreadPoolAdd(&gSendThreadPool, &job, NULL);
		if (ret != 0) {
			if (ret == EOUTOFMEM) {
				line = __LINE__;
				ret = UPNP_E_OUTOF_MEMORY;
			}
		} else {
			line = __LINE__;
			ret = GENA_SUCCESS;
		}
	}

ExitFunction:
	if (ret != GENA_SUCCESS || var_count <= 0) {
		free(thread_struct);
		free(headers);
		ixmlFreeDOMString(propertySet);
		free(servId_copy);
		free(UDN_copy);
		free(reference_count);
	}

	HandleUnlock();

	UpnpPrintf(UPNP_INFO, GENA, __FILE__, line,
		"GENA END INITIAL NOTIFY, ret = %d",
		ret);

	return ret;
}

int genaInitNotifyExt(
	UpnpDevice_Handle device_handle,
	char *UDN,
	char *servId,
	IXML_Document *PropSet,
	const Upnp_SID sid)
{
	int ret = GENA_SUCCESS;
	int line = 0;

	int *reference_count = NULL;
	char *UDN_copy = NULL;
	char *servId_copy = NULL;
	DOMString propertySet = NULL;
	char *headers = NULL;
	notify_thread_struct *thread_struct = NULL;

	subscription *sub = NULL;
	service_info *service = NULL;
	struct Handle_Info *handle_info;
	ThreadPoolJob job;

	memset(&job, 0, sizeof(job));

	UpnpPrintf(UPNP_INFO, GENA, __FILE__, __LINE__,
		"GENA BEGIN INITIAL NOTIFY EXT");

	reference_count = (int *)malloc(sizeof (int));
	if (reference_count == NULL) {
		line = __LINE__;
		ret = UPNP_E_OUTOF_MEMORY;
		goto ExitFunction;
	}
	*reference_count = 0;

	UDN_copy = (char *)malloc(strlen(UDN) + 1);
	if (UDN_copy == NULL) {
		line = __LINE__;
		ret = UPNP_E_OUTOF_MEMORY;
		goto ExitFunction;
	}

	servId_copy = (char *)malloc(strlen(servId) + 1);
	if( servId_copy == NULL ) {
		line = __LINE__;
		ret = UPNP_E_OUTOF_MEMORY;
		goto ExitFunction;
	}

	memset(UDN_copy, 0, strlen(UDN) + 1);
	strncpy(UDN_copy, UDN, strlen(UDN));
	memset(servId_copy, 0, strlen(servId) + 1);
	strncpy(servId_copy, servId, strlen(servId));

	HandleLock();

	if (GetHandleInfo(device_handle, &handle_info) != HND_DEVICE) {
		line = __LINE__;
		ret = GENA_E_BAD_HANDLE;
		goto ExitFunction;
	}

	service = FindServiceId(&handle_info->ServiceTable, servId, UDN);
	if (service == NULL) {
		line = __LINE__;
		ret = GENA_E_BAD_SERVICE;
		goto ExitFunction;
	}
	UpnpPrintf(UPNP_INFO, GENA, __FILE__, __LINE__,
		"FOUND SERVICE IN INIT NOTFY EXT: UDN %s, ServID: %s",
		UDN, servId);

	sub = GetSubscriptionSID(sid, service);
	if (sub == NULL || sub->active) {
		line = __LINE__;
		ret = GENA_E_BAD_SID;
		goto ExitFunction;
	}
	UpnpPrintf( UPNP_INFO, GENA, __FILE__, __LINE__,
		"FOUND SUBSCRIPTION IN INIT NOTIFY EXT: SID %s", sid);
	sub->active = 1;

	if (PropSet == 0) {
		line = __LINE__;
		ret = GENA_SUCCESS;
		goto ExitFunction;
	}

	propertySet = ixmlPrintNode((IXML_Node *)PropSet);
	if (propertySet == NULL) {
		line = __LINE__;
		ret = UPNP_E_INVALID_PARAM;
		goto ExitFunction;
	}
	UpnpPrintf(UPNP_INFO, GENA, __FILE__, __LINE__,
		"GENERATED PROPERTY SET IN INIT EXT NOTIFY: %s",
		propertySet);

	headers = AllocGenaHeaders(propertySet);
	if (headers == NULL) {
		line = __LINE__;
		ret = UPNP_E_OUTOF_MEMORY;
		goto ExitFunction;
	}

	/* schedule thread for initial notification */

	thread_struct = (notify_thread_struct *)malloc(sizeof (notify_thread_struct));
	if (thread_struct == NULL) {
		line = __LINE__;
		ret = UPNP_E_OUTOF_MEMORY;
	} else {
		*reference_count = 1;
		thread_struct->servId = servId_copy;
		thread_struct->UDN = UDN_copy;
		thread_struct->headers = headers;
		thread_struct->propertySet = propertySet;
		memset(thread_struct->sid, 0, sizeof(thread_struct->sid));
		strncpy(thread_struct->sid, sid,
			sizeof(thread_struct->sid) - 1);
		thread_struct->eventKey = sub->eventKey++;
		thread_struct->reference_count = reference_count;
		thread_struct->device_handle = device_handle;

		TPJobInit(&job, (start_routine)genaNotifyThread, thread_struct);
		TPJobSetFreeFunction(&job, (free_routine)free_notify_struct);
		TPJobSetPriority(&job, MED_PRIORITY);

		ret = ThreadPoolAdd(&gSendThreadPool, &job, NULL);
		if (ret != 0) {
			if (ret == EOUTOFMEM) {
				line = __LINE__;
				ret = UPNP_E_OUTOF_MEMORY;
			}
		} else {
			line = __LINE__;
			ret = GENA_SUCCESS;
		}
	}

ExitFunction:
	if (ret != GENA_SUCCESS || PropSet == 0) {
		free(thread_struct);
		free(headers);
		ixmlFreeDOMString(propertySet);
		free(servId_copy);
		free(UDN_copy);
		free(reference_count);
	}

	HandleUnlock();

	UpnpPrintf(UPNP_INFO, GENA, __FILE__, line,
		"GENA END INITIAL NOTIFY EXT, ret = %d",
		ret);

	return ret;
}

int genaNotifyAllExt(
	UpnpDevice_Handle device_handle,
	char *UDN,
	char *servId,
	IXML_Document *PropSet)
{
	int ret = GENA_SUCCESS;
	int line = 0;

	int *reference_count = NULL;
	char *UDN_copy = NULL;
	char *servId_copy = NULL;
	DOMString propertySet = NULL;
	char *headers = NULL;
	notify_thread_struct *thread_struct = NULL;

	subscription *finger = NULL;
	service_info *service = NULL;
	struct Handle_Info *handle_info;
	ThreadPoolJob job;

	memset(&job, 0, sizeof(job));

	UpnpPrintf(UPNP_INFO, GENA, __FILE__, __LINE__,
		"GENA BEGIN NOTIFY ALL EXT");

	reference_count = (int *)malloc(sizeof (int));
	if (reference_count == NULL) {
		line = __LINE__;
		ret = UPNP_E_OUTOF_MEMORY;
		goto ExitFunction;
	}
	*reference_count = 0;

	UDN_copy = (char *)malloc(strlen(UDN) + 1);
	if (UDN_copy == NULL) {
		line = __LINE__;
		ret = UPNP_E_OUTOF_MEMORY;
		goto ExitFunction;
	}

	servId_copy = (char *)malloc(strlen(servId) + 1);
	if( servId_copy == NULL ) {
		line = __LINE__;
		ret = UPNP_E_OUTOF_MEMORY;
		goto ExitFunction;
	}

	memset(UDN_copy, 0, strlen(UDN) + 1);
	strncpy(UDN_copy, UDN, strlen(UDN));
	memset(servId_copy, 0, strlen(servId) + 1);
	strncpy(servId_copy, servId, strlen(servId));

	propertySet = ixmlPrintNode((IXML_Node *)PropSet);
	if (propertySet == NULL) {
		line = __LINE__;
		ret = UPNP_E_INVALID_PARAM;
		goto ExitFunction;
	}
	UpnpPrintf(UPNP_INFO, GENA, __FILE__, __LINE__,
		"GENERATED PROPERTY SET IN EXT NOTIFY: %s",
		propertySet);

	headers = AllocGenaHeaders(propertySet);
	if (headers == NULL) {
		line = __LINE__;
		ret = UPNP_E_OUTOF_MEMORY;
		goto ExitFunction;
	}

	HandleLock();

	if (GetHandleInfo(device_handle, &handle_info) != HND_DEVICE) {
		line = __LINE__;
		ret = GENA_E_BAD_HANDLE;
	} else {
		service = FindServiceId(&handle_info->ServiceTable, servId, UDN);
		if (service != NULL) {
			finger = GetFirstSubscription(service);
			while (finger) {
				thread_struct = (notify_thread_struct *)malloc(sizeof (notify_thread_struct));
				if (thread_struct == NULL) {
					line = __LINE__;
					ret = UPNP_E_OUTOF_MEMORY;
					break;
				}

				(*reference_count)++;
				thread_struct->reference_count = reference_count;
				thread_struct->UDN = UDN_copy;
				thread_struct->servId = servId_copy;
				thread_struct->headers = headers;
				thread_struct->propertySet = propertySet;
				memset(thread_struct->sid, 0,
					sizeof(thread_struct->sid));
				strncpy(thread_struct->sid, finger->sid,
					sizeof(thread_struct->sid) - 1);
				thread_struct->eventKey = finger->eventKey++;
				thread_struct->device_handle = device_handle;
				/* if overflow, wrap to 1 */
				if (finger->eventKey < 0) {
					finger->eventKey = 1;
				}

				TPJobInit(&job, (start_routine)genaNotifyThread, thread_struct);
				TPJobSetFreeFunction(&job, (free_routine)free_notify_struct);
				TPJobSetPriority(&job, MED_PRIORITY);
				ret = ThreadPoolAdd(&gSendThreadPool, &job, NULL);
				if (ret != 0) {
					line = __LINE__;
					if (ret == EOUTOFMEM) {
						line = __LINE__;
						ret = UPNP_E_OUTOF_MEMORY;
					}
					break;
				}

				finger = GetNextSubscription(service, finger);
			}
		} else {
			line = __LINE__;
			ret = GENA_E_BAD_SERVICE;
		}
	}

ExitFunction:
	if (ret != GENA_SUCCESS || *reference_count == 0) {
		free(headers);
		ixmlFreeDOMString(propertySet);
		free(servId_copy);
		free(UDN_copy);
		free(reference_count);
	}

	HandleUnlock();

	UpnpPrintf(UPNP_INFO, GENA, __FILE__, line,
		"GENA END NOTIFY ALL EXT, ret = %d",
		ret);

	return ret;
}

int genaNotifyAll(
	UpnpDevice_Handle device_handle,
	char *UDN,
	char *servId,
	char **VarNames,
	char **VarValues,
	int var_count)
{
	int ret = GENA_SUCCESS;
	int line = 0;

	int *reference_count = NULL;
	char *UDN_copy = NULL;
	char *servId_copy = NULL;
	DOMString propertySet = NULL;
	char *headers = NULL;
	notify_thread_struct *thread_struct = NULL;

	subscription *finger = NULL;
	service_info *service = NULL;
	struct Handle_Info *handle_info;
	ThreadPoolJob job;

	memset(&job, 0, sizeof(job));

	UpnpPrintf(UPNP_INFO, GENA, __FILE__, __LINE__,
		"GENA BEGIN NOTIFY ALL");

	reference_count = (int *)malloc(sizeof (int));
	if (reference_count == NULL) {
		line = __LINE__;
		ret = UPNP_E_OUTOF_MEMORY;
		goto ExitFunction;
	}
	*reference_count = 0;

	UDN_copy = (char *)malloc(strlen(UDN) + 1);
	if (UDN_copy == NULL) {
		line = __LINE__;
		ret = UPNP_E_OUTOF_MEMORY;
		goto ExitFunction;
	}

	servId_copy = (char *)malloc(strlen(servId) + 1);
	if( servId_copy == NULL ) {
		line = __LINE__;
		ret = UPNP_E_OUTOF_MEMORY;
		goto ExitFunction;
	}

	memset(UDN_copy, 0, strlen(UDN) + 1);
	strncpy(UDN_copy, UDN, strlen(UDN));
	memset(servId_copy, 0, strlen(servId) + 1);
	strncpy(servId_copy, servId, strlen(servId));

	ret = GeneratePropertySet(VarNames, VarValues, var_count, &propertySet);
	if (ret != XML_SUCCESS) {
		line = __LINE__;
		goto ExitFunction;
	}
	UpnpPrintf(UPNP_INFO, GENA, __FILE__, __LINE__,
		"GENERATED PROPERTY SET IN EXT NOTIFY: %s",
		propertySet);

	headers = AllocGenaHeaders(propertySet);
	if (headers == NULL) {
		line = __LINE__;
		ret = UPNP_E_OUTOF_MEMORY;
		goto ExitFunction;
	}

	HandleLock();

	if (GetHandleInfo(device_handle, &handle_info) != HND_DEVICE) {
		line = __LINE__;
		ret = GENA_E_BAD_HANDLE;
	} else {
		service = FindServiceId(&handle_info->ServiceTable, servId, UDN);
		if (service != NULL) {
			finger = GetFirstSubscription(service);
			while (finger) {
				thread_struct = (notify_thread_struct *)malloc(sizeof (notify_thread_struct));
				if (thread_struct == NULL) {
					line = __LINE__;
					ret = UPNP_E_OUTOF_MEMORY;
					break;
				}

				(*reference_count)++;
				thread_struct->reference_count = reference_count;
				thread_struct->UDN = UDN_copy;
				thread_struct->servId = servId_copy;
				thread_struct->headers = headers;
				thread_struct->propertySet = propertySet;
				memset(thread_struct->sid, 0,
					sizeof(thread_struct->sid));
				strncpy(thread_struct->sid, finger->sid,
					sizeof(thread_struct->sid) - 1);
				thread_struct->eventKey = finger->eventKey++;
				thread_struct->device_handle = device_handle;
				/* if overflow, wrap to 1 */
				if (finger->eventKey < 0) {
					finger->eventKey = 1;
				}

				TPJobInit(&job, (start_routine)genaNotifyThread, thread_struct);
				TPJobSetFreeFunction(&job, (free_routine)free_notify_struct);
				TPJobSetPriority(&job, MED_PRIORITY);
				ret = ThreadPoolAdd(&gSendThreadPool, &job, NULL);
				if (ret != 0) {
					line = __LINE__;
					if (ret == EOUTOFMEM) {
						line = __LINE__;
						ret = UPNP_E_OUTOF_MEMORY;
					}
					break;
				}

				finger = GetNextSubscription(service, finger);
			}
		} else {
			line = __LINE__;
			ret = GENA_E_BAD_SERVICE;
		}
	}

ExitFunction:
	if (ret != GENA_SUCCESS || *reference_count == 0) {
		free(headers);
		ixmlFreeDOMString(propertySet);
		free(servId_copy);
		free(UDN_copy);
		free(reference_count);
	}

	HandleUnlock();

	UpnpPrintf(UPNP_INFO, GENA, __FILE__, line,
		"GENA END NOTIFY ALL, ret = %d",
		ret);

	return ret;
}

/*!
 * \brief Returns OK message in the case of a subscription request.
 *
 * \return UPNP_E_SUCCESS if successful, otherwise the appropriate error code.
 */
static int respond_ok(
	/*! [in] Socket connection of request. */
	SOCKINFO *info,
	/*! [in] Accepted duration. */
	int time_out,
	/*! [in] Accepted subscription. */
	subscription *sub,
	/*! [in] Http request. */
	http_message_t *request)
{
    int major;
    int minor;
    membuffer response;
    int return_code;
    char timeout_str[100];
    int upnp_timeout = UPNP_TIMEOUT;
    int rc = 0;

    http_CalcResponseVersion( request->major_version,
                              request->minor_version, &major, &minor );

    if( time_out >= 0 ) {
        rc = snprintf( timeout_str, sizeof ( timeout_str ),
                       "TIMEOUT: Second-%d", time_out );
    } else {
        memset( timeout_str, 0, sizeof( timeout_str ) );
        strncpy( timeout_str, "TIMEOUT: Second-infinite",
                 sizeof ( timeout_str ) - 1);
    }
    if (rc < 0 || (unsigned int) rc >= sizeof ( timeout_str ) ) {
        error_respond( info, HTTP_INTERNAL_SERVER_ERROR, request );
        return UPNP_E_OUTOF_MEMORY;
    }

    membuffer_init( &response );
    response.size_inc = 30;
    if( http_MakeMessage(
        &response, major, minor,
        "R" "D" "S" "N" "Xc" "ssc" "scc",
        HTTP_OK,
        (off_t)0,
        X_USER_AGENT,
        "SID: ", sub->sid,
        timeout_str ) != 0 ) {
        membuffer_destroy( &response );
        error_respond( info, HTTP_INTERNAL_SERVER_ERROR, request );
        return UPNP_E_OUTOF_MEMORY;
    }

    return_code = http_SendMessage( info, &upnp_timeout, "b",
                                    response.buf, response.length );

    membuffer_destroy( &response );

    return return_code;
}

/*!
 * \brief Function to parse the Callback header value in subscription requests.
 *
 * Takes in a buffer containing URLS delimited by '<' and '>'. The entire buffer
 * is copied into dynamic memory and stored in the URL_list. Pointers to the
 * individual urls within this buffer are allocated and stored in the URL_list.
 * Only URLs with network addresses are considered (i.e. host:port or domain name).
 *
 * \return The number of URLs parsed if successful, otherwise UPNP_E_OUTOF_MEMORY.
 */
static int create_url_list(
	/*! [in] . */
	memptr *url_list,
	/*! [out] . */
	URL_list *out)
{
    size_t URLcount = 0;
    size_t i;
    int return_code = 0;
    uri_type temp;
    token urls;
    token *URLS;

    urls.buff = url_list->buf;
    urls.size = url_list->length;
    URLS = &urls;

    out->size = 0;
    out->URLs = NULL;
    out->parsedURLs = NULL;

    for( i = 0; i < URLS->size; i++ ) {
        if( ( URLS->buff[i] == '<' ) && ( i + 1 < URLS->size ) ) {
            if( ( ( return_code = parse_uri( &URLS->buff[i + 1],
                                             URLS->size - i + 1,
                                             &temp ) ) == HTTP_SUCCESS )
                && ( temp.hostport.text.size != 0 ) ) {
                URLcount++;
            } else {
                if( return_code == UPNP_E_OUTOF_MEMORY ) {
                    return return_code;
                }
            }
        }
    }

    if( URLcount > 0 ) {
        out->URLs = malloc(URLS->size + 1);
        out->parsedURLs = malloc(sizeof(uri_type) * URLcount);
        if (!out->URLs || !out->parsedURLs) {
            free(out->URLs);
            free(out->parsedURLs);
            out->URLs = NULL;
            out->parsedURLs = NULL;
            return UPNP_E_OUTOF_MEMORY;
        }
        memcpy( out->URLs, URLS->buff, URLS->size );
        out->URLs[URLS->size] = 0;
        URLcount = 0;
        for( i = 0; i < URLS->size; i++ ) {
            if( ( URLS->buff[i] == '<' ) && ( i + 1 < URLS->size ) ) {
                if( ( ( return_code =
                        parse_uri( &out->URLs[i + 1], URLS->size - i + 1,
                                   &out->parsedURLs[URLcount] ) ) ==
                      HTTP_SUCCESS )
                    && ( out->parsedURLs[URLcount].hostport.text.size !=
                         0 ) ) {
                    URLcount++;
                } else {
                    if( return_code == UPNP_E_OUTOF_MEMORY ) {
                        free( out->URLs );
                        free( out->parsedURLs );
                        out->URLs = NULL;
                        out->parsedURLs = NULL;
                        return return_code;
                    }
                }
            }
        }
    }
    out->size = URLcount;

    return (int)URLcount;
}

void gena_process_subscription_request(
    int iface,
	SOCKINFO *info,
	http_message_t *request)
{
	struct Upnp_Subscription_Request request_struct;
	Upnp_SID temp_sid;
	int return_code = 1;
	int time_out = 1801;
	service_info *service;
	subscription *sub;
	uuid_upnp uid;
	struct Handle_Info *handle_info;
	void *cookie;
	Upnp_FunPtr callback_fun;
	UpnpDevice_Handle device_handle;
	memptr nt_hdr;
	char *event_url_path = NULL;
	memptr callback_hdr;
	memptr timeout_hdr;
	int rc = 0;

	memset(&request_struct, 0, sizeof(request_struct));

	UpnpPrintf(UPNP_INFO, GENA, __FILE__, __LINE__,
		"Subscription Request Received:\n");

	if (httpmsg_find_hdr(request, HDR_NT, &nt_hdr) == NULL) {
		error_respond(info, HTTP_BAD_REQUEST, request);
		goto exit_function;
	}

	/* check NT header */
	/* Windows Millenium Interoperability: */
	/* we accept either upnp:event, or upnp:propchange for the NT header */
	if (memptr_cmp_nocase(&nt_hdr, "upnp:event") != 0) {
		error_respond(info, HTTP_PRECONDITION_FAILED, request);
		goto exit_function;
	}

	/* if a SID is present then the we have a bad request "incompatible headers" */
	if (httpmsg_find_hdr(request, HDR_SID, NULL) != NULL) {
		error_respond(info, HTTP_BAD_REQUEST, request);
		goto exit_function;
	}
	/* look up service by eventURL */
	event_url_path = str_alloc(request->uri.pathquery.buff, request->uri.pathquery.size);
	if (event_url_path == NULL) {
		error_respond(info, HTTP_INTERNAL_SERVER_ERROR, request);
		goto exit_function;
	}

	UpnpPrintf(UPNP_INFO, GENA, __FILE__, __LINE__,
		"SubscriptionRequest for event URL path: %s\n",
		event_url_path);

	HandleLock();

	/* CURRENTLY, ONLY ONE DEVICE */
	if (GetDeviceHandleInfo(iface, info->foreign_sockaddr.ss_family ,
	    &device_handle, &handle_info) != HND_DEVICE) {
		free(event_url_path);
		error_respond(info, HTTP_INTERNAL_SERVER_ERROR, request);
		HandleUnlock();
		goto exit_function;
	}
	service = FindServiceEventURLPath(&handle_info->ServiceTable, event_url_path);
	free(event_url_path);

	if (service == NULL || !service->active) {
		error_respond(info, HTTP_NOT_FOUND, request);
		HandleUnlock();
		goto exit_function;
	}

	UpnpPrintf(UPNP_INFO, GENA, __FILE__, __LINE__,
		"Subscription Request: Number of Subscriptions already %d\n "
		"Max Subscriptions allowed: %d\n",
		service->TotalSubscriptions,
		handle_info->MaxSubscriptions);

	/* too many subscriptions */
	if (handle_info->MaxSubscriptions != -1 &&
	    service->TotalSubscriptions >= handle_info->MaxSubscriptions) {
		error_respond(info, HTTP_INTERNAL_SERVER_ERROR, request);
		HandleUnlock();
		goto exit_function;
	}
	/* generate new subscription */
	sub = (subscription *)malloc(sizeof (subscription));
	if (sub == NULL) {
		error_respond(info, HTTP_INTERNAL_SERVER_ERROR, request);
		HandleUnlock();
		goto exit_function;
	}
	sub->eventKey = 0;
	sub->ToSendEventKey = 0;
	sub->active = 0;
	sub->next = NULL;
	sub->DeliveryURLs.size = 0;
	sub->DeliveryURLs.URLs = NULL;
	sub->DeliveryURLs.parsedURLs = NULL;

	/* check for valid callbacks */
	if (httpmsg_find_hdr( request, HDR_CALLBACK, &callback_hdr) == NULL) {
		error_respond(info, HTTP_PRECONDITION_FAILED, request);
		freeSubscriptionList(sub);
		HandleUnlock();
		goto exit_function;
	}
	return_code = create_url_list(&callback_hdr, &sub->DeliveryURLs);
	if (return_code == 0) {
		error_respond(info, HTTP_PRECONDITION_FAILED, request);
		freeSubscriptionList(sub);
		HandleUnlock();
		goto exit_function;
	}
	if (return_code == UPNP_E_OUTOF_MEMORY) {
		error_respond(info, HTTP_INTERNAL_SERVER_ERROR, request);
		freeSubscriptionList(sub);
		HandleUnlock();
		goto exit_function;
	}
	/* set the timeout */
	if (httpmsg_find_hdr(request, HDR_TIMEOUT, &timeout_hdr) != NULL) {
		if (matchstr(timeout_hdr.buf, timeout_hdr.length,
		    "%iSecond-%d%0", &time_out) == PARSE_OK) {
			/* nothing */
		} else if(memptr_cmp_nocase(&timeout_hdr, "Second-infinite") == 0) {
			/* infinite timeout */
			time_out = -1;
		} else {
			/* default is > 1800 seconds */
			time_out = DEFAULT_TIMEOUT;
		}
	}
	/* replace infinite timeout with max timeout, if possible */
	if (handle_info->MaxSubscriptionTimeOut != -1) {
		if (time_out == -1 ||
		    time_out > handle_info->MaxSubscriptionTimeOut) {
			time_out = handle_info->MaxSubscriptionTimeOut;
		}
	}
	if (time_out >= 0) {
		sub->expireTime = time(NULL) + time_out;
	} else {
		/* infinite time */
		sub->expireTime = 0;
	}

	/* generate SID */
	uuid_create(&uid);
	uuid_unpack(&uid, temp_sid);
	rc = snprintf(sub->sid, sizeof(sub->sid), "uuid:%s", temp_sid);

	/* respond OK */
	if (rc < 0 || (unsigned int) rc >= sizeof(sub->sid) ||
		(respond_ok(info, time_out,
		sub, request) != UPNP_E_SUCCESS)) {
		freeSubscriptionList(sub);
		HandleUnlock();
		goto exit_function;
	}
	/* add to subscription list */
	sub->next = service->subscriptionList;
	service->subscriptionList = sub;
	service->TotalSubscriptions++;

	/* finally generate callback for init table dump */
	request_struct.ServiceId = service->serviceId;
	request_struct.UDN = service->UDN;
	strncpy((char *)request_struct.Sid, sub->sid,
		sizeof(request_struct.Sid) - 1);

	/* copy callback */
	callback_fun = handle_info->Callback;
	cookie = handle_info->Cookie;

	HandleUnlock();

	/* make call back with request struct */
	/* in the future should find a way of mainting that the handle */
	/* is not unregistered in the middle of a callback */
	callback_fun(UPNP_EVENT_SUBSCRIPTION_REQUEST, &request_struct, cookie);

exit_function:
	return;
}

void gena_process_subscription_renewal_request(
    int iface,
	SOCKINFO *info,
	http_message_t *request)
{
    Upnp_SID sid;
    subscription *sub;
    int time_out = 1801;
    service_info *service;
    struct Handle_Info *handle_info;
    UpnpDevice_Handle device_handle;
    memptr temp_hdr;
    membuffer event_url_path;
    memptr timeout_hdr;

    /* if a CALLBACK or NT header is present, then it is an error */
    if( httpmsg_find_hdr( request, HDR_CALLBACK, NULL ) != NULL ||
        httpmsg_find_hdr( request, HDR_NT, NULL ) != NULL ) {
        error_respond( info, HTTP_BAD_REQUEST, request );
        return;
    }
    /* get SID */
    if( httpmsg_find_hdr( request, HDR_SID, &temp_hdr ) == NULL ||
        temp_hdr.length > SID_SIZE ) {
        error_respond( info, HTTP_PRECONDITION_FAILED, request );
        return;
    }
    memcpy( sid, temp_hdr.buf, temp_hdr.length );
    sid[temp_hdr.length] = '\0';

    /* lookup service by eventURL */
    membuffer_init( &event_url_path );
    if( membuffer_append( &event_url_path, request->uri.pathquery.buff,
                          request->uri.pathquery.size ) != 0 ) {
        error_respond( info, HTTP_INTERNAL_SERVER_ERROR, request );
        return;
    }

    HandleLock();

    /* CURRENTLY, ONLY SUPPORT ONE DEVICE */
    if( GetDeviceHandleInfo( iface, info->foreign_sockaddr.ss_family,
        &device_handle, &handle_info ) != HND_DEVICE ) {
        error_respond( info, HTTP_PRECONDITION_FAILED, request );
        membuffer_destroy( &event_url_path );
        HandleUnlock();
        return;
    }
    service = FindServiceEventURLPath( &handle_info->ServiceTable,
                                       event_url_path.buf );
    membuffer_destroy( &event_url_path );

    /* get subscription */
    if( service == NULL ||
        !service->active ||
        ( ( sub = GetSubscriptionSID( sid, service ) ) == NULL ) ) {
        error_respond( info, HTTP_PRECONDITION_FAILED, request );
        HandleUnlock();
        return;
    }

    UpnpPrintf( UPNP_INFO, GENA, __FILE__, __LINE__,
        "Renew request: Number of subscriptions already: %d\n "
        "Max Subscriptions allowed:%d\n",
        service->TotalSubscriptions,
        handle_info->MaxSubscriptions );
    /* too many subscriptions */
    if( handle_info->MaxSubscriptions != -1 &&
            service->TotalSubscriptions > handle_info->MaxSubscriptions ) {
        error_respond( info, HTTP_INTERNAL_SERVER_ERROR, request );
        RemoveSubscriptionSID( sub->sid, service );
        HandleUnlock();
        return;
    }
    /* set the timeout */
    if( httpmsg_find_hdr( request, HDR_TIMEOUT, &timeout_hdr ) != NULL ) {
        if( matchstr( timeout_hdr.buf, timeout_hdr.length,
                      "%iSecond-%d%0", &time_out ) == PARSE_OK ) {

            /*nothing */

        } else if( memptr_cmp_nocase( &timeout_hdr, "Second-infinite" ) ==
                   0 ) {

            time_out = -1;      /* inifinite timeout */

        } else {
            time_out = DEFAULT_TIMEOUT; /* default is > 1800 seconds */

        }
    }

    /* replace infinite timeout with max timeout, if possible */
    if( handle_info->MaxSubscriptionTimeOut != -1 ) {
        if( time_out == -1 ||
            time_out > handle_info->MaxSubscriptionTimeOut ) {
            time_out = handle_info->MaxSubscriptionTimeOut;
        }
    }

    if( time_out == -1 ) {
        sub->expireTime = 0;
    } else {
        sub->expireTime = time( NULL ) + time_out;
    }

    if( respond_ok( info, time_out, sub, request ) != UPNP_E_SUCCESS ) {
        RemoveSubscriptionSID( sub->sid, service );
    }

    HandleUnlock();
}

void gena_process_unsubscribe_request(
    int iface,
	SOCKINFO *info,
	http_message_t *request)
{
    Upnp_SID sid;
    service_info *service;
    struct Handle_Info *handle_info;
    UpnpDevice_Handle device_handle;

    memptr temp_hdr;
    membuffer event_url_path;

    /* if a CALLBACK or NT header is present, then it is an error */
    if( httpmsg_find_hdr( request, HDR_CALLBACK, NULL ) != NULL ||
        httpmsg_find_hdr( request, HDR_NT, NULL ) != NULL ) {
        error_respond( info, HTTP_BAD_REQUEST, request );
        return;
    }
    /* get SID */
    if( httpmsg_find_hdr( request, HDR_SID, &temp_hdr ) == NULL ||
        temp_hdr.length > SID_SIZE ) {
        error_respond( info, HTTP_PRECONDITION_FAILED, request );
        return;
    }
    memcpy( sid, temp_hdr.buf, temp_hdr.length );
    sid[temp_hdr.length] = '\0';

    /* lookup service by eventURL */
    membuffer_init( &event_url_path );
    if( membuffer_append( &event_url_path, request->uri.pathquery.buff,
                          request->uri.pathquery.size ) != 0 ) {
        error_respond( info, HTTP_INTERNAL_SERVER_ERROR, request );
        return;
    }

    HandleLock();

    /* CURRENTLY, ONLY SUPPORT ONE DEVICE */
    if( GetDeviceHandleInfo( iface, info->foreign_sockaddr.ss_family,
        &device_handle, &handle_info ) != HND_DEVICE ) {
        error_respond( info, HTTP_PRECONDITION_FAILED, request );
        membuffer_destroy( &event_url_path );
        HandleUnlock();
        return;
    }
    service = FindServiceEventURLPath( &handle_info->ServiceTable,
                                       event_url_path.buf );
    membuffer_destroy( &event_url_path );

    /* validate service */
    if( service == NULL ||
        !service->active || GetSubscriptionSID( sid, service ) == NULL )
    {
        error_respond( info, HTTP_PRECONDITION_FAILED, request );
        HandleUnlock();
        return;
    }

    RemoveSubscriptionSID(sid, service);
    error_respond(info, HTTP_OK, request);    /* success */

    HandleUnlock();
}

#endif /* INCLUDE_DEVICE_APIS */
#endif /* EXCLUDE_GENA */


text:
<?xml version="1.0" encoding="UTF-8"?>
<jbosscache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="urn:jboss:jbosscache-core:config:3.0">
    <locking isolationLevel="READ_COMMITTED" lockAcquisitionTimeout="10000" nodeLockingScheme="mvcc"
             concurrencyLevel="3000"/>
    <transaction transactionManagerLookupClass="org.jboss.cache.transaction.GenericTransactionManagerLookup"/>
    <clustering mode="replication" clusterName="JBossCache-Cluster">
        <stateRetrieval timeout="20000" fetchInMemoryState="false"/>
        <async serializationExecutorPoolSize="1000" serializationExecutorQueueSize="500000"/>
        <buddy enabled="true" poolName="myBuddyPoolReplicationGroup" communicationTimeout="2000">
            <dataGravitation auto="false" removeOnFind="true" searchBackupTrees="true"/>
            <locator class="org.jboss.cache.buddyreplication.NextMemberBuddyLocator">
                <properties>
                    numBuddies = 1
                    ignoreColocatedBuddies = true
                </properties>
            </locator>
        </buddy>
        <jgroupsConfig>
            <TCP discard_incompatible_packets="true" enable_bundling="false" enable_diagnostics="false"
                 enable_unicast_bundling="false" loopback="false" max_bundle_size="64000" max_bundle_timeout="30"
                 oob_thread_pool.enabled="true" oob_thread_pool.keep_alive_time="10000" oob_thread_pool.max_threads="4"
                 oob_thread_pool.min_threads="2" oob_thread_pool.queue_enabled="false"
                 oob_thread_pool.queue_max_size="10"
                 oob_thread_pool.rejection_policy="Run" recv_buf_size="20000000" thread_naming_pattern="pl"
                 thread_pool.enabled="true" thread_pool.keep_alive_time="30000" thread_pool.max_threads="4"
                 thread_pool.min_threads="1" thread_pool.queue_enabled="true" thread_pool.queue_max_size="50000"
                 thread_pool.rejection_policy="discard" use_concurrent_stack="true" use_incoming_packet_handler="true"
                 use_send_queues="false"/>
            <MPING mcast_addr="232.1.2.3" num_initial_members="3" timeout="2000"/>
            <MERGE2 max_interval="30000" min_interval="10000"/>
            <FD_SOCK/>
            <FD max_tries="5" shun="true" timeout="10000"/>
            <VERIFY_SUSPECT timeout="1500"/>
            <pbcast.NAKACK discard_delivered_msgs="true" gc_lag="0" retransmit_timeout="300,600,1200,2400,4800"
                           use_mcast_xmit="false"/>
            <pbcast.STABLE desired_avg_gossip="50000" max_bytes="400000" stability_delay="1000"/>
            <pbcast.GMS join_retry_timeout="2000" join_timeout="5000" print_local_addr="true" shun="false"
                        view_ack_collection_timeout="5000" view_bundling="true"/>
            <FC max_credits="5000000" min_threshold="0.20"/>
            <FRAG2 frag_size="60000"/>
            <pbcast.STREAMING_STATE_TRANSFER use_reading_thread="true"/>
            <pbcast.FLUSH timeout="0"/>
        </jgroupsConfig>
    </clustering>
</jbosscache>

redpajama_set_name: RedPajamaGithub


text:
var RcmCreateNewPasswordEdit = function (instanceId, container, pluginHandler) {

    /**
     * Always refers to this object unlike the 'this' JS variable;
     *
     * @type {RcmCreateNewPasswordEdit}
     */
    var me = this;

    /**
     * Settings from db
     * @type {Object}
     */
    var data;

    /**
     * Default settings from config json file
     * @type {Object}
     */
    var defaultData;

    /**
     * @type {AjaxPluginEditHelper}
     */
    var ajaxEditHelper = new AjaxPluginEditHelper(instanceId, container, pluginHandler);

    /**
     * Called by content management system to make this plugin user-editable
     */
    this.initEdit = function () {
        container.find('form').unbind('submit');
        container.find('form').submit(function () {
            return false;
        });

        ajaxEditHelper.ajaxGetInstanceConfigs(
            function (returnedData, returnedDefaultData) {
                data = returnedData;
                defaultData = returnedDefaultData;

                ajaxEditHelper.attachPropertiesDialog(me.showEditDialog);
            }
        );
    };

    /**
     * Called by content management system to get this plugins data for saving
     * on the server
     *
     * @return {Object}
     */
    this.getSaveData = function () {
        return data;
    };

    /**
     * Displays a dialog box to edit href and image src
     */
    this.showEditDialog = function () {

        var inputGroups = ajaxEditHelper.buildInputGroups(
            [
                'translate'
            ],
            data,
            defaultData
        );

        var tabsDiv = $('' +
            '
' +
            '
' +
            '
Form Text
' +
            '
Thanks Page
' +
            '
' +
            '
' +
            '
' +
            '
' +
            '
' +
            '
'
        );

        tabsDiv.find('#tabs-form')
            .append('
Translations:
')
            .appendMulti(inputGroups['translate'])

        tabsDiv.tabs();

        var thankYouInput =
            $.dialogIn('richEdit', 'Thank You Message', data['thankYou']);
        tabsDiv.find('#tabs-thank').append(thankYouInput);

        var form = $('<form></form>')
            .addClass('simple').append(tabsDiv)
            .dialog({
                title: 'Properties',
                modal: true,
                width: 620,
                buttons: {
                    Cancel: function () {
                        $(this).dialog("close");
                    },
                    Ok: function () {

                        data = ajaxEditHelper
                            .captureInputGroups(inputGroups, data);

                        $(this).dialog('close');
                    }
                }
            }
        );
    };
};


text:
package com.google.cloud.pubsublite.spark;

import static org.junit.Assert.assertThrows;

import com.google.api.gax.rpc.ApiException;
import com.google.common.collect.ImmutableMap;
import java.util.Map;
import org.junit.Test;

public class PslWriteDataSourceOptionsTest {

  @Test
  public void testInvalidTopicPath() {
    Map<String, String> options = ImmutableMap.of(Constants.TOPIC_CONFIG_KEY, "invalid/path");
    assertThrows(ApiException.class, () -> PslWriteDataSourceOptions.fromProperties(options));
  }
}


text:
#ifndef __CROSSNET_ARRAY_H__
#define __CROSSNET_ARRAY_H__

#include "CrossNetRuntime/System/ICloneable.h"
#include "CrossNetRuntime/System/Collections/IList.h"
#include "CrossNetRuntime/System/Collections/ICollection.h"
#include "CrossNetRuntime/System/Collections/IEnumerator.h"
#include "CrossNetRuntime/System/Collections/IEnumerable.h"
#include "CrossNetRuntime/System/Collections/Generic/IEnumerator__G1.h"
#include "CrossNetRuntime/System/Collections/Generic/IEnumerable__G1.h"
#include "CrossNetRuntime/System/Collections/Generic/IList__G1.h"
#include "CrossNetRuntime/System/Collections/Generic/ICollection__G1.h"
#include "CrossNetRuntime/GC/GCManager.h"
#include "CrossNetRuntime/Internal/Tracer.h"
#include "CrossNetRuntime/Internal/Typeof.h"

namespace System
{
    struct Decimal;
}

namespace System
{
    namespace Collections
    {
        class IComparer;

        namespace ObjectModel
        {
            template <typename T>
            class ReadOnlyCollection;
        }

        namespace Generic
        {
            template <typename T>
            class IComparer__G1;
        }
    }

    template <typename T>
    class Comparison__G1;

    template <typename T>
    class Array__G;

    // Abstract array class - base class for all arrays
    class Array : public System::Object
    {
    public:
        CN_DYNAMIC_ID();

        virtual void SetValue(System::Object * value, System::Int32 first) = 0;
        virtual void SetValue(System::Object * value, System::Array__G<System::Int32> *) = 0;
        virtual void SetValue(System::Object * value, System::Int64 first) = 0;
        virtual void SetValue(System::Object * value, System::Array__G<System::Int64> *) = 0;
        virtual void SetValue(System::Object * value, System::Int32 first, System::Int32 second) = 0;
        virtual void SetValue(System::Object * value, System::Int64 first, System::Int64 second) = 0;
        virtual void SetValue(System::Object * value, System::Int32 first, System::Int32 second, System::Int32 third) = 0;
        virtual void SetValue(System::Object * value, System::Int64 first, System::Int64 second, System::Int64 third) = 0;

        virtual System::Object * GetValue(System::Int32 first) = 0;
        virtual System::Object * GetValue(System::Array__G<System::Int32> *) = 0;
        virtual System::Object * GetValue(System::Int64 first) = 0;
        virtual System::Object * GetValue(System::Array__G<System::Int64> *) = 0;
        virtual System::Object * GetValue(System::Int32 first, System::Int32 second) = 0;
        virtual System::Object * GetValue(System::Int64 first, System::Int64 second) = 0;
        virtual System::Object * GetValue(System::Int32 first, System::Int32 second, System::Int32 third) = 0;
        virtual System::Object * GetValue(System::Int64 first, System::Int64 second, System::Int64 third) = 0;

        virtual int get_Length() const = 0;
        virtual Int32 GetLength(Int32 dimension) = 0;
        virtual Int32 get_Rank() = 0;
        virtual Int32 GetLowerBound(Int32 dimension) = 0;
        virtual Int32 GetUpperBound(Int32 dimension) = 0;

        // So we can do some type safety, at the item level
        virtual void * * GetItemInterfaceMap() = 0;

        Boolean get_IsFixedSize()
        {
            return (true);
        }

        Boolean get_IsReadOnly()
        {
            return (false);
        }

        Int32 IList__Add(System::Object * /*value*/)
        {
            CROSSNET_DONT_CALL();
            return (-1);
        }

        void IList__Clear()
        {
            CROSSNET_DONT_CALL();
        }

        // Use const for these versions so they don't collide with generic version
        System::Boolean Contains(System::Object * value) const
        {
            return (IndexOf(value) >= 0);
        }

        // Use const for these versions so they don't collide with generic version
        virtual System::Int32 IndexOf(System::Object * value) const = 0;

        void IList__Insert(System::Int32 /*index*/, System::Object * /*value*/)
        {
            CROSSNET_DONT_CALL();
        }

        void IList__Remove(System::Object * /*value*/)
        {
            CROSSNET_DONT_CALL();
        }

        void IList__RemoveAt(System::Int32 /*index*/)
        {
            CROSSNET_DONT_CALL();
        }

        Boolean get_IsSynchronized()
        {
            return (false);
        }

        System::Object * get_SyncRoot()
        {
            return (this);
        }

        System::Object * Clone();

        void CopyTo(System::Array * array, System::Int32 index)
        {
            // Make sure that both arrays are of the same type
            CROSSNET_ASSERT(m__InterfaceMap__ == array->m__InterfaceMap__, "");

            int sizeOfT = GetSizeOfT();
            int length = get_Length();

            // Make sure that the destination array is long enough
            CROSSNET_ASSERT(length + index <= array->get_Length(), "");

            void * arraySrcItems = GetAddressOfFirstItem();
            void * arrayDstItems = (void *)((int)(array->GetAddressOfFirstItem()) + (index * sizeOfT));

            __memcopy__(arrayDstItems, arraySrcItems, length * sizeOfT);
        }

        static void Copy(System::Array *, System::Array *, int);
        static void Copy(System::Array *, System::Array *, long);
        static void Copy(System::Array *, int, System::Array *, int, int);
        static void Copy(System::Array *, long, System::Array *, long, long);
        static void Clear(System::Array *, System::Int32, System::Int32);

        static void Reverse(System::Array * array)
        {
            array->Reverse();
        }
        static void Reverse(System::Array *, System::Int32, System::Int32);

        // Dynamic creation of the type - don't expect this to be implemented soon
        // I believe this could be implemented by hacking things around,
        // Like by getting the size of the corresponding size, allocating correctly, clearing up the buffer
        // (as if the type is a class, it contains null references, if that's a struct, all the members are null,
        // it could be different for enums though - value of the first enum?)
        // We would have to see how the Id would be determined...
        static System::Array * CreateInstance(System::Type *, System::Int32);
        static System::Array * CreateInstance(System::Type *, System::Array__G<System::Int32> *);
        static System::Array * CreateInstance(System::Type *, System::Array__G<System::Int64> *);
        static System::Array * CreateInstance(System::Type *, System::Int32, System::Int32);
        static System::Array * CreateInstance(System::Type *, System::Array__G<System::Int32> *, System::Array__G<System::Int32> *);
        static System::Array * CreateInstance(System::Type *, System::Int32, System::Int32, System::Int32);

        static System::Int32 IndexOf(System::Array *, System::Object *);
        static System::Int32 IndexOf(System::Array *, System::Object *, System::Int32);
        static System::Int32 IndexOf(System::Array *, System::Object *, System::Int32, System::Int32);
        template <typename T>
        static System::Int32 IndexOf__G1(System::Array__G<T> *, T);
        template <typename T>
        static System::Int32 IndexOf__G1(System::Array__G<T> *, T, System::Int32);
        template <typename T>
        static System::Int32 IndexOf__G1(System::Array__G<T> *, T, System::Int32, System::Int32);

        static System::Int32 LastIndexOf(System::Array *, System::Object *);
        static System::Int32 LastIndexOf(System::Array *, System::Object *, System::Int32);
        static System::Int32 LastIndexOf(System::Array *, System::Object *, System::Int32, System::Int32);
        template <typename T>
        static System::Int32 LastIndexOf__G1(System::Array__G<T> *, T);
        template <typename T>
        static System::Int32 LastIndexOf__G1(System::Array__G<T> *, T, System::Int32);
        template <typename T>
        static System::Int32 LastIndexOf__G1(System::Array__G<T> *, T, System::Int32, System::Int32);

        template <typename T>
        static System::Collections::ObjectModel::ReadOnlyCollection<T> * AsReadOnly__G1(System::Array__G<T> *);

        static System::Int32 BinarySearch(System::Array *, System::Object *);
        static System::Int32 BinarySearch(System::Array *, System::Object *, System::Collections::IComparer *);
        static System::Int32 BinarySearch(System::Array *, System::Int32, System::Int32, System::Object *);
        static System::Int32 BinarySearch(System::Array *, System::Int32, System::Int32, System::Object *, System::Collections::IComparer *);

        template <typename T>
        static System::Int32 BinarySearch__G1(System::Array__G<T> *, T);
        template <typename T>
        static System::Int32 BinarySearch__G1(System::Array__G<T> *, T, System::Collections::Generic::IComparer__G1<T> *);
        template <typename T>
        static System::Int32 BinarySearch__G1(System::Array__G<T> *, System::Int32, System::Int32, T);
        template <typename T>
        static System::Int32 BinarySearch__G1(System::Array__G<T> *, System::Int32, System::Int32, T, System::Collections::Generic::IComparer__G1<T> *);

        static void Sort(System::Array *);
        static void Sort(System::Array *, System::Array *);
        static void Sort(System::Array *, System::Collections::IComparer *);
        static void Sort(System::Array *, System::Array *, System::Collections::IComparer *);

        static void Sort(System::Array *, System::Int32, System::Int32);
        static void Sort(System::Array *, System::Array *, System::Int32, System::Int32);
        static void Sort(System::Array *, System::Int32, System::Int32, System::Collections::IComparer *);
        static void Sort(System::Array *, System::Array *, System::Int32, System::Int32, System::Collections::IComparer *);

        template <typename T>
        static void Sort__G1(System::Array__G<T> *)
        {
            CROSSNET_NOT_IMPLEMENTED();
        }
        template <typename T>
        static void Sort__G1(System::Array__G<T> *, Comparison__G1<T> *);
        template <typename T>
        static void Sort__G1(System::Array__G<T> *, T, System::Collections::Generic::IComparer__G1<T> *);
        template <typename T>
        static void Sort__G1(System::Array__G<T> *, System::Int32, System::Int32);
        template <typename T>
        static void Sort__G1(System::Array__G<T> *, System::Int32, System::Int32, System::Collections::Generic::IComparer__G1<T> *);

        template <typename TKey, typename TValue>
        static void Sort__G2(System::Array__G<TKey> *, System::Array__G<TValue> *);
        template <typename TKey, typename TValue>
        static void Sort__G2(System::Array__G<TKey> *, System::Array__G<TValue> *, System::Collections::Generic::IComparer__G1<TKey> *);
        template <typename TKey, typename TValue>
        static void Sort__G2(System::Array__G<TKey> *, System::Array__G<TValue> *, System::Int32, System::Int32);
        template <typename TKey, typename TValue>
        static void Sort__G2(System::Array__G<TKey> *, System::Array__G<TValue> *, System::Int32, System::Int32, System::Collections::Generic::IComparer__G1<TKey> *);

    protected:
        CROSSNET_FINLINE
        Array()
            :   Object(__ARRAY__)           // Tells that's a dynamically sized object
        {
            // Do nothing...
        }

        CROSSNET_FINLINE
        ~Array()
        {
            // Do nothing...
        }

        virtual void Reverse() = 0;
        virtual int GetSizeOfT() = 0;
        virtual void * GetAddressOfFirstItem() = 0;

    private:
        Array(const Array & other);
        Array & operator=(const Array & other);
    };

    template<class T>
    class Array__G : public Array
    {
    public:
        CN_MULTIPLE_DYNAMIC_OBJECT_ID
        (
            sizeof(Array__G),
            __W7__
            (
                CN_IMPLEMENT(Wrapper__ICloneable),
                CN_IMPLEMENT(Wrapper__IList),
                CN_IMPLEMENT(Wrapper__ICollection),
                CN_IMPLEMENT(Wrapper__IEnumerable),
                CN_IMPLEMENT(Wrapper__IList__G1),
                CN_IMPLEMENT(Wrapper__ICollection__G1),
                CN_IMPLEMENT(Wrapper__IEnumerable__G1)
            )
            ,
            NULL
        )

        static Array__G * __Create__(int first, T * initValues = NULL)
        {
            Array__G * array = (Array__G *)operator new(sizeof(Array__G) + (sizeof(T) * first));
            array->Array__G::Array__G(first, initValues);
            return (array);
        }

        static Array__G * __Create__(int first, int second, T * initValues = NULL)
        {
            Array__G * array = (Array__G *)operator new(sizeof(Array__G) + (sizeof(T) * first * second));
            array->Array__G::Array__G(first, second, initValues);
            return (array);
        }

        static Array__G * __Create__(int first, int second, int third, T * initValues = NULL)
        {
            Array__G * array = (Array__G *)operator new(sizeof(Array__G) + (sizeof(T) * first * second * third));
            array->Array__G::Array__G(first, second, third, initValues);
            return (array);
        }

        static Array__G * __Create__(int first, int second, int third, int fourth, T * initValues = NULL);
        static Array__G * __Create__(int first, int second, int third, int fourth, int fifth, T * initValues = NULL);
        static Array__G * __Create__(int first, int second, int third, int fourth, int fifth, int sixth, T * initValues = NULL);

        virtual int __GetVariableSize__()
        {
            int size = sizeof(Array__G);
            size += sizeof(T) * GetSize();
            return (size);
        }

        T * __ToPointer__()
        {
            return (mItems);
        }

        const T & Item(int first) const
        {
            CROSSNET_ASSERT(mSecond == 0, "This is not a one dimension array!");
            CROSSNET_ASSERT(((first >= 0) && (first < mFirst)), "Out of bound!");
            int index = first;
            return (*(mItems + index));
        }

        T & Item(int first)
        {
            CROSSNET_ASSERT(mSecond == 0, "This is not a one dimension array!");
            CROSSNET_ASSERT(((first >= 0) && (first < mFirst)), "Out of bound!");
            int index = first;
            return (*(mItems + index));
        }

        const T & Item(int first, int second) const
        {
            CROSSNET_ASSERT(mThird == 0, "This is not a two dimensions array!");
            CROSSNET_ASSERT(((first >= 0) && (first < mFirst)), "Out of bound!");
            CROSSNET_ASSERT(((second >= 0) && (second < mSecond)), "Out of bound!");
            int index = (first * mSecond) + second;
            return (*(mItems + index));
        }

        T & Item(int first, int second)
        {
            CROSSNET_ASSERT(mThird == 0, "This is not a two dimensions array!");
            CROSSNET_ASSERT(((first >= 0) && (first < mFirst)), "Out of bound!");
            CROSSNET_ASSERT(((second >= 0) && (second < mSecond)), "Out of bound!");
            int index = (first * mSecond) + second;
            return (*(mItems + index));
        }

        const T & Item(int first, int second, int third) const
        {
            CROSSNET_ASSERT(mThird != 0, "This is not a three dimensions array!");
            CROSSNET_ASSERT(((first >= 0) && (first < mFirst)), "Out of bound!");
            CROSSNET_ASSERT(((second >= 0) && (second < mSecond)), "Out of bound!");
            CROSSNET_ASSERT(((third >= 0) && (third < mThird)), "Out of bound!");
            int index = (((first * mSecond) + second) * mThird) + third;
            return (*(mItems + index));
        }

        T & Item(int first, int second, int third)
        {
            CROSSNET_ASSERT(mThird != 0, "This is not a three dimensions array!");
            CROSSNET_ASSERT(((first >= 0) && (first < mFirst)), "Out of bound!");
            CROSSNET_ASSERT(((second >= 0) && (second < mSecond)), "Out of bound!");
            CROSSNET_ASSERT(((third >= 0) && (third < mThird)), "Out of bound!");
            int index = (((first * mSecond) + second) * mThird) + third;
            return (*(mItems + index));
        }

        const T & SingleDimensionItem(int first) const
        {
            CROSSNET_ASSERT(((first >= 0) && (first < GetSize())), "Out of bound!");
            int index = first;
            return (*(mItems + index));
        }

        T & SingleDimensionItem(int first)
        {
            CROSSNET_ASSERT(((first >= 0) && (first < GetSize())), "Out of bound!");
            int index = first;
            return (*(mItems + index));
        }

        void SetValue(System::Object * value, System::Int32 first)
        {
            T temp = CrossNetRuntime::Unbox<CrossNetRuntime::BaseTypeWrapper<T>::BoxeableType >(value);
            Item(first) = temp;
        }

        virtual void SetValue(System::Object *, System::Array__G<System::Int32> *)
        {
            CROSSNET_NOT_IMPLEMENTED();
        }

        virtual void SetValue(System::Object * value, System::Int64 first)
        {
            T temp = CrossNetRuntime::Unbox<CrossNetRuntime::BaseTypeWrapper<T>::BoxeableType >(value);
            Item((int)first) = temp;
        }

        virtual void SetValue(System::Object *, System::Array__G<System::Int64> *)
        {
            CROSSNET_NOT_IMPLEMENTED();
        }

        virtual void SetValue(System::Object * value, System::Int32 first, System::Int32 second)
        {
            T temp = CrossNetRuntime::Unbox<CrossNetRuntime::BaseTypeWrapper<T>::BoxeableType >(value);
            Item(first, second) = temp;
        }

        virtual void SetValue(System::Object * value, System::Int64 first, System::Int64 second)
        {
            T temp = CrossNetRuntime::Unbox<CrossNetRuntime::BaseTypeWrapper<T>::BoxeableType >(value);
            Item((int)first, (int)second) = temp;
        }

        virtual void SetValue(System::Object * value, System::Int32 first, System::Int32 second, System::Int32 third)
        {
            T temp = CrossNetRuntime::Unbox<CrossNetRuntime::BaseTypeWrapper<T>::BoxeableType >(value);
            Item(first, second, third) = temp;
        }

        virtual void SetValue(System::Object * value, System::Int64 first, System::Int64 second, System::Int64 third)
        {
            T temp = CrossNetRuntime::Unbox<CrossNetRuntime::BaseTypeWrapper<T>::BoxeableType >(value);
            Item((int)first, (int)second, (int)third) = temp;
        }

        virtual System::Object * GetValue(System::Int32 first)
        {
            const T & temp = Item(first);
            return (CrossNetRuntime::Box<System::Object>(temp));
        }

        virtual System::Object * GetValue(System::Array__G<System::Int32> *)
        {
            CROSSNET_NOT_IMPLEMENTED();
            return (NULL);
        }

        virtual System::Object * GetValue(System::Int64 first)
        {
            const T & temp = Item((int)first);
            return (CrossNetRuntime::Box<System::Object>(temp));
        }

        virtual System::Object * GetValue(System::Array__G<System::Int64> *)
        {
            CROSSNET_NOT_IMPLEMENTED();
            return (NULL);
        }

        virtual System::Object * GetValue(System::Int32 first, System::Int32 second)
        {
            const T & temp = Item(first, second);
            return (CrossNetRuntime::Box<System::Object>(temp));
        }

        virtual System::Object * GetValue(System::Int64 first, System::Int64 second)
        {
            const T & temp = Item((int)first, (int)second);
            return (CrossNetRuntime::Box<System::Object>(temp));
        }

        virtual System::Object * GetValue(System::Int32 first, System::Int32 second, System::Int32 third)
        {
            const T & temp = Item(first, second, third);
            return (CrossNetRuntime::Box<System::Object>(temp));
        }

        virtual System::Object * GetValue(System::Int64 first, System::Int64 second, System::Int64 third)
        {
            const T & temp = Item((int)first, (int)second, (int)third);
            return (CrossNetRuntime::Box<System::Object>(temp));
        }

        int get_Length() const
        {
            return (GetSize());
        }

        // This method is an explicit implementation of ICollection.get_Count()
        // Keep it public for the wrappers...
        int ICollection__get_Count()
        {
            return (GetSize());
        }

        Int32 GetLength(Int32 dimension)
        {
            switch (dimension)
            {
            case 0:
                return (mFirst);

            case 1:
                CROSSNET_ASSERT(mSecond != 0, "This is not a two dimensions array!");
                return (mSecond);

            case 2:
                CROSSNET_ASSERT(mThird != 0, "This is not a three dimensions array!");
                return (mThird);

            default:
                CROSSNET_FAIL("Dimension is bigger than rank!");
                return (0);
            }
        }

        Int32 get_Rank()
        {
            if (mThird != 0)
            {
                return (3);
            }
            if (mSecond != 0)
            {
                return (2);
            }
            return (1);
        }

        Int32 GetLowerBound(Int32 dimension)
        {
            switch (dimension)
            {
            case 0:
                return (0);

            case 1:
                CROSSNET_ASSERT(mSecond != 0, "This is not a two dimensions array!");
                return (0);

            case 2:
                CROSSNET_ASSERT(mThird != 0, "This is not a three dimensions array!");
                return (0);

            default:
                CROSSNET_FAIL("Dimension is bigger than rank!");
                return (0);
            }
        }

        Int32 GetUpperBound(Int32 dimension)
        {
            switch (dimension)
            {
            case 0:
                return (mFirst - 1);

            case 1:
                CROSSNET_ASSERT(mSecond != 0, "This is not a two dimensions array!");
                return (mSecond - 1);

            case 2:
                CROSSNET_ASSERT(mThird != 0, "This is not a three dimensions array!");
                return (mThird - 1);

            default:
                CROSSNET_FAIL("Dimension is bigger than rank!");
                return (0);
            }
        }

        virtual void Reverse()
        {
            int size = GetSize();

            T * first = mItems;
            T * last = mItems + size - 1;

            T temp;

            while (first < last)
            {
                // Don't use copy constructor / operator, just copy byte by byte
                // The compiler should inline that correctly
                // Depending of the compiler / profiling we might want to actually use the copy operator
                __memcopy__(&temp, first, sizeof(T));
                __memcopy__(first, last, sizeof(T));
                __memcopy__(last, &temp, sizeof(T));
                ++first;
                --last;
            }
        }

        virtual void * * GetItemInterfaceMap()
        {
            return (CrossNetRuntime::GetInterfaceMap<T>());
        }

        class ArrayEnumerator : public System::Object
        {
        public:
            CN_MULTIPLE_DYNAMIC_OBJECT_ID
            (
                sizeof(ArrayEnumerator),
                __W3__
                (
                    CN_IMPLEMENT(ArrayEnumerator__IEnumerator),
                    CN_IMPLEMENT(ArrayEnumerator__IEnumerator__G1),
                    CN_IMPLEMENT(ArrayEnumerator__IDisposable)
                )
                ,
                NULL
            )

            ArrayEnumerator(Array__G * array)
                :
                mArray(array),
                mIndex(-1)
            {
                m__InterfaceMap__ = __GetInterfaceMap__();
                mSize = array->GetSize();
            }

            System::Object * get_Current()
            {
                return (CrossNetRuntime::Box<System::Object>(mArray->SingleDimensionItem(mIndex)));
            }

            T IEnumerator__G1__get_Current()
            {
                return (mArray->SingleDimensionItem(mIndex));
            }

            System::Boolean MoveNext()
            {
                ++mIndex;
                return (mIndex < mSize);
            }

            void Reset()
            {
                mIndex = -1;
            }

            void Dispose()
            {
                // Do nothing...
            }

            class ArrayEnumerator__IEnumerator : public System::Collections::IEnumerator
            {
            public:
                System::Object *    get_Current(void * __instance__)
                {
                    ArrayEnumerator * enumerator = static_cast<ArrayEnumerator *>(__instance__);
                    return (enumerator->get_Current());
                }

                System::Boolean     MoveNext(void * __instance__)
                {
                    ArrayEnumerator * enumerator = static_cast<ArrayEnumerator *>(__instance__);
                    return (enumerator->MoveNext());
                }

                void    Reset(void * __instance__)
                {
                    ArrayEnumerator * enumerator = static_cast<ArrayEnumerator *>(__instance__);
                    enumerator->Reset();
                }
            };

            class ArrayEnumerator__IEnumerator__G1 : public System::Collections::Generic::IEnumerator__G1<T>
            {
            public:
                T   get_Current(void * __instance__)
                {
                    ArrayEnumerator * enumerator = static_cast<ArrayEnumerator *>(__instance__);
                    return (enumerator->IEnumerator__G1__get_Current());
                }
            };

            class ArrayEnumerator__IDisposable : public System::IDisposable
            {
            public:
                void Dispose(void * __instance__)
                {
                    ArrayEnumerator * enumerator = static_cast<ArrayEnumerator *>(__instance__);
                    enumerator->Dispose();
                }
            };

        private:
            Array__G *  mArray;
            Int32       mIndex;
            Int32       mSize;
        };

        System::Collections::IEnumerator * GetEnumerator()
        {
            return (CrossNetRuntime::FastCast<System::Collections::IEnumerator>(new ArrayEnumerator(this)));
        }

        System::Collections::Generic::IEnumerator__G1<T> *  IEnumerator__G1__GetEnumerator()
        {
            return (CrossNetRuntime::FastCast<System::Collections::Generic::IEnumerator__G1<T> >(new ArrayEnumerator(this)));
        }

        System::Object * Clone()
        {
            Int32 rank = get_Rank();
            T * initValues = mItems;
            switch (rank)
            {
            case 1:
                return (__Create__(mFirst, initValues));

            case 2:
                return (__Create__(mFirst, mSecond, initValues));

            case 3:
                return (__Create__(mFirst, mSecond, mThird, initValues));

            default:
                CROSSNET_NOT_IMPLEMENTED();
                return (NULL);
            }
        }

        void IList__G1__Insert(::System::Int32 /*index*/, T /*item*/)
        {
            CROSSNET_DONT_CALL();
        }

        void IList__G1__Add(T /*item*/)
        {
            CROSSNET_DONT_CALL();
        }

        ::System::Boolean IList__G1__Remove(T /*item*/)
        {
            CROSSNET_DONT_CALL();
            return (false);
        }

        ::System::Int32 IndexOf(T item)
        {
            Int32 length = get_Length();

            // Optimized version should use traits to compare,
            // that way no boxing would be necessary nor slow Equals(Object *).
            System::Object * tempObj = CrossNetRuntime::Box<System::Object>(item);
            for (Int32 i = 0 ; i < length ; ++i)
            {
                if (CrossNetRuntime::GenWrapperConvert(mItems[i])->Equals(tempObj))
                {
                    return (i);
                }
            }
            return (-1);
        }

        ::System::Boolean Contains(T item)
        {
            Int32 length = get_Length();

            // Optimized version should use traits to compare,
            // that way no boxing would be necessary nor slow Equals(Object *).
            System::Object * tempObj = CrossNetRuntime::Box<System::Object>(item);
            for (Int32 i = 0 ; i < length ; ++i)
            {
                if (CrossNetRuntime::GenWrapperConvert(mItems[i])->Equals(tempObj))
                {
                    return (true);
                }
            }
            return (false);
        }

        virtual System::Int32 IndexOf(System::Object * value) const
        {
            Int32 length = get_Length();
            for (Int32 i = 0 ; i < length ; ++i)
            {
                if (CrossNetRuntime::GenWrapperConvert(mItems[i])->Equals(value))
                {
                    return (i);
                }
            }
            return (-1);
        }

        class Wrapper__ICloneable : public System::ICloneable
        {
        public:
            virtual System::Object *    Clone(void * __instance__)
            {
                Array__G * __temp__ = static_cast<Array__G *>(__instance__);
                return (__temp__->Clone());
            }
        };

        class Wrapper__IList : public System::Collections::IList
        {
        public:
            virtual System::Boolean get_IsFixedSize(void * __instance__)
            {
                Array__G * __temp__ = static_cast<Array__G *>(__instance__);
                return (__temp__->get_IsFixedSize());

            }
            virtual System::Boolean get_IsReadOnly(void * __instance__)
            {
                Array__G * __temp__ = static_cast<Array__G *>(__instance__);
                return (__temp__->get_IsReadOnly());
            }
            virtual System::Object * get_Item(void * __instance__, System::Int32 index)
            {
                Array__G * __temp__ = static_cast<Array__G *>(__instance__);
                return (__temp__->GetValue(index));
            }

            virtual System::Object * set_Item(void * __instance__, System::Int32 index, System::Object * value)
            {
                Array__G * __temp__ = static_cast<Array__G *>(__instance__);
                __temp__->SetValue(value, index);
                return (value);
            }

            virtual System::Int32 Add(void * __instance__, System::Object * value)
            {
                Array__G * __temp__ = static_cast<Array__G *>(__instance__);
                return (__temp__->IList__Add(value));
            }

            virtual void Clear(void * __instance__)
            {
                Array__G * __temp__ = static_cast<Array__G *>(__instance__);
                __temp__->IList__Clear();
            }

            virtual System::Boolean Contains(void * __instance__, System::Object * value)
            {
                Array__G * __temp__ = static_cast<Array__G *>(__instance__);
                return (__temp__->System::Array::Contains(value));          // Fully qualify it remove ambiguity
            }

            virtual System::Int32 IndexOf(void * __instance__, System::Object * value)
            {
                const Array__G * __temp__ = static_cast<const Array__G *>(__instance__);
                return (__temp__->Array__G::IndexOf(value));                // Fully qualify it remove ambiguity
            }

            virtual void Insert(void * __instance__, System::Int32 index, System::Object * value)
            {
                Array__G * __temp__ = static_cast<Array__G *>(__instance__);
                __temp__->IList__Insert(index, value);
            }

            virtual void Remove(void * __instance__, System::Object * value)
            {
                Array__G * __temp__ = static_cast<Array__G *>(__instance__);
                __temp__->IList__Remove(value);
            }

            virtual void RemoveAt(void * __instance__, System::Int32 index)
            {
                Array__G * __temp__ = static_cast<Array__G *>(__instance__);
                __temp__->IList__RemoveAt(index);
            }
        };

        class Wrapper__ICollection : public System::Collections::ICollection
        {
        public:
            virtual System::Int32 get_Count(void * __instance__)
            {
                Array__G * __temp__ = static_cast<Array__G *>(__instance__);
                return (__temp__->ICollection__get_Count());
            }

            virtual System::Boolean get_IsSynchronized(void * __instance__)
            {
                Array__G * __temp__ = static_cast<Array__G *>(__instance__);
                return (__temp__->get_IsSynchronized());
            }
            virtual System::Object * get_SyncRoot(void * __instance__)
            {
                Array__G * __temp__ = static_cast<Array__G *>(__instance__);
                return (__temp__->get_SyncRoot());
            }
            virtual void CopyTo(void * __instance__, System::Array * array, System::Int32 index)
            {
                Array__G * __temp__ = static_cast<Array__G *>(__instance__);
                __temp__->CopyTo(array, index);
            }
        };

        class Wrapper__IEnumerable : public System::Collections::IEnumerable
        {
        public:
            virtual System::Collections::IEnumerator * GetEnumerator(void * __instance__)
            {
                Array__G * __temp__ = static_cast<Array__G *>(__instance__);
                return (__temp__->GetEnumerator());
            }
        };

        class Wrapper__IList__G1 : public System::Collections::Generic::IList__G1<T>
        {
        public:
            virtual T get_Item(void * __instance__, ::System::Int32 index)
            {
                Array__G * __temp__ = static_cast<Array__G *>(__instance__);
                return (__temp__->Item(index));
            }
            virtual T set_Item(void * __instance__, ::System::Int32 index, T value)
            {
                Array__G * __temp__ = static_cast<Array__G *>(__instance__);
                return (__temp__->Item(index) = value);
            }
            virtual ::System::Int32 IndexOf(void * __instance__, T item)
            {
                Array__G * __temp__ = static_cast<Array__G *>(__instance__);
                return (__temp__->IndexOf(item));
            }
            virtual void Insert(void * __instance__, ::System::Int32 index, T item)
            {
                Array__G * __temp__ = static_cast<Array__G *>(__instance__);
                __temp__->IList__G1__Insert(index, item);
            }
            virtual void RemoveAt(void * __instance__, ::System::Int32 index)
            {
                Array__G * __temp__ = static_cast<Array__G *>(__instance__);
                __temp__->IList__RemoveAt(index);
            }
        };

        class Wrapper__ICollection__G1 : public System::Collections::Generic::ICollection__G1<T>
        {
        public:
            virtual ::System::Int32 get_Count(void * __instance__)
            {
                Array__G * __temp__ = static_cast<Array__G *>(__instance__);
                return (__temp__->get_Length());
            }
            virtual ::System::Boolean get_IsReadOnly(void * __instance__)
            {
                Array__G * __temp__ = static_cast<Array__G *>(__instance__);
                return (__temp__->get_IsReadOnly());
            }
            virtual void Add(void * __instance__, T item)
            {
                Array__G * __temp__ = static_cast<Array__G *>(__instance__);
                __temp__->IList__G1__Add(item);
            }
            virtual void Clear(void * __instance__)
            {
                Array__G * __temp__ = static_cast<Array__G *>(__instance__);
                __temp__->IList__Clear();
            }
            virtual ::System::Boolean Contains(void * __instance__, T item)
            {
                Array__G * __temp__ = static_cast<Array__G *>(__instance__);
                return (__temp__->Contains(item));
            }
            virtual void CopyTo(void * __instance__, typename ::System::Array__G< T > * array, ::System::Int32 arrayIndex)
            {
                Array__G * __temp__ = static_cast<Array__G *>(__instance__);
                __temp__->CopyTo(array, arrayIndex);
            }
            virtual ::System::Boolean Remove(void * __instance__, T item)
            {
                Array__G * __temp__ = static_cast<Array__G *>(__instance__);
                return (__temp__->IList__G1__Remove(item));
            }
        };

        class Wrapper__IEnumerable__G1 : public System::Collections::Generic::IEnumerable__G1<T>
        {
        public:
            virtual System::Collections::Generic::IEnumerator__G1<T> *    GetEnumerator(void * __instance__)
            {
                Array__G * __temp__ = static_cast<Array__G *>(__instance__);
                return (__temp__->IEnumerator__G1__GetEnumerator());
            }
        };

        virtual void __Trace__(unsigned char currentMark)
        {
            ::CrossNetRuntime::Tracer::DoTrace(currentMark, mItems, GetSize());
        }

    protected:
        ~Array__G()
        {
            // Do nothing...
            // The items are not destroyed yet...
            // For classes it doesn't matter as pointer will be collected
            // But for struct with finalizers, they won't be called
            // We might want to create a traits to detect this case...
            // TODO: Add support for finalizers when T is a struct
        }

        virtual int GetSizeOfT()
        {
            return (sizeof(T));
        }

        virtual void * GetAddressOfFirstItem()
        {
            return (mItems);
        }

    private:
        explicit
        Array__G(int first, T * initValues = NULL)
            :   mFirst(first),
                mSecond(0),
                mThird(0)
        {
            Init(initValues);
        }

        Array__G(int first, int second, T * initValues = NULL)
            :   mFirst(first),
                mSecond(second),
                mThird(0)
        {
            Init(initValues);
        }

        Array__G(int first, int second, int third, T * initValues = NULL)
            :   mFirst(first),
                mSecond(second),
                mThird(third)
        {
            Init(initValues);
        }

        void Init(T * initValues)
        {
            m__InterfaceMap__ = __GetInterfaceMap__();

            int size = GetSize();
            // Copy the objects
            if (initValues != NULL)
            {
                memcpy(mItems, initValues, sizeof(T) * size);
            }
            else
            {
                // No initial values, set the memory to zero
                // Default value for base types (and thus struct members) as well as GC pointers...
                __memclear__(mItems, sizeof(T) * size);
            }
        }

        int GetSize() const
        {
            Int32   size = mFirst;
            if (mSecond != 0)
            {
                size *= mSecond;
                if (mThird != 0)
                {
                    size *= mThird;
                }
            }
            return (size);
        }

        // It seems that in fact, these three integers should actually be a dynamic C++ array
        Int32   mFirst;
        Int32   mSecond;
        Int32   mThird;
        mutable T mItems[0];
    };
}

#endif	//	__CROSSNET_ARRAY_H__


text:
let hBookmark;

function warmUp() {
    utils.include("btil.js");
    let global = loadAutoloader("chrome://hatenabookmark/content/addPanel.xml");
    hBookmark = global.hBookmark;
    // EXPORT に含まれていないメンバもテストするため直接読み込む。
    Components.classes["@mozilla.org/moz/jssubscript-loader;1"]
              .getService(Components.interfaces.mozIJSSubScriptLoader)
              .loadSubScript("chrome://hatenabookmark/content/addPanel/20-URLSuggestion.js", hBookmark);
}

function testEffectiveDomain() {
    assert.isTrue(hBookmark.isSameEffectiveDomain(
        "http://www.hatena.ne.jp/",
        "http://b.hatena.ne.jp/"));
    assert.isFalse(hBookmark.isSameEffectiveDomain(
        "http://www.hatena.ne.jp/",
        "http://www.goo.ne.jp/"));
}

function testMetaSuggestor() {
    let suggestors = hBookmark.URLSuggestion.suggestors;
    assert.equals(
        "http://b.hatena.ne.jp/guide/staff_bookmark_04",
        suggestors.meta("http://b.hatena.ne.jp/entry/http://b.hatena.ne.jp/guide/staff_bookmark_04", null))
    assert.equals(
        null,
        suggestors.meta("http://b.hatena.ne.jp/entry/12345", null))
}

function testCanonicalResponseSuggestor() {
    let suggestor = hBookmark.URLSuggestion.responseSuggestors.canonical;
    let response = {
        responseText:

                <link rel="canonical" href="http://example.org/canonical"/>

Hello, world

        .toXMLString()
    }
    assert.equals("http://example.org/canonical",
                  suggestor("http://example.org/", response));

    response.responseText =

            <link href="canonical-url" rel="canonical"/>

Hello, world

    .toXMLString();
    assert.equals("http://example.org/canonical-url",
                  suggestor("http://example.org/", response));
    assert.equals("http://example.org/canonical-url#fragment",
                  suggestor("http://example.org/#fragment", response));
}


text:
package computerdatabase // 1

import io.gatling.core.Predef._ // 2
import io.gatling.http.Predef._
import scala.concurrent.duration._

class JerseySimulation extends Simulation { // 3

  val httpConf = http // 4
    .baseURL("http://localhost:8090") // 5
    .acceptHeader("application/json;q=0.9,*/*;q=0.8") // 6
    .doNotTrackHeader("1")
    .acceptLanguageHeader("en-US,en;q=0.5")
    .acceptEncodingHeader("gzip, deflate")

  val scn = scenario("JerseySimulation")  // 7
  .during(300){
     exec(http("request_1")  // 8
    .get("/jerseyendpoint?size=100")) // 9
     .pause(1000 milliseconds, 3000 milliseconds) // 10
	}
  setUp( // 11
    scn.inject(atOnceUsers(3000)) // 12
  ).protocols(httpConf) // 13
}


text:
Template.registerHelper("sections", function() {
  let ret = [];

  let walk = (items, depth) => {
    _.each(items, item => {
      // Work around (eg) accidental trailing commas leading to spurious holes
      // in IE8.
      if (! item) {
        return;
      }

      if (item instanceof Array) {
        walk(item, depth + 1);

        if (depth === 2) {
          ret.push({ type: "spacer", depth: 2 });
        }
      } else {
        if (typeof(item) === "string") {
          item = {name: item};
        }

        let id = item.name.replace(/[.#]/g, "-");

        ret.push(_.extend({ type: "section", depth: depth, id: id, }, item));
      }
    });
  };

  let namespaces = _.groupBy(DocsNames, name => name.split('.')[0]);

  let toc = _.chain(namespaces).map(
    (functions, namespace) => [namespace, functions]
  ).flatten(true).value();

  walk(toc, 1);

  return ret;
});

Template.registerHelper("type", function(what) {
  return this.type === what;
});

Template.registerHelper("depthIs", function(n) {
  return this.depth === n;
});


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.invbf.adminclientesweb.util;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.nio.file.Files;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author ideacentre
 */
@WebServlet("/image/*")
public class ImageServlet extends HttpServlet {

    // Properties ---------------------------------------------------------------------------------

    private String imagePath;

    // Init ---------------------------------------------------------------------------------------

    public void init() throws ServletException {

        // Define base path somehow. You can define it as init-param of the servlet.
        StringBuilder sb = new StringBuilder();
        sb.append(System.getProperty("APP_CONF")).append(System.getProperty("file.separator")).append("images").append(System.getProperty("file.separator")).append("inversiones");

        this.imagePath = sb.toString();

        // In a Windows environment with the Applicationserver running on the
        // c: volume, the above path is exactly the same as "c:\var\webapp\images".
        // In Linux/Mac/UNIX, it is just straightforward "/var/webapp/images".
    }

    // Actions ------------------------------------------------------------------------------------

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        // Get requested image by path info.
        String requestedImage = request.getPathInfo();

        // Check if file name is actually supplied to the request URI.
        if (requestedImage == null) {
            // Do your thing if the image is not supplied to the request URI.
            // Throw an exception, or send 404, or show default/warning image, or just ignore it.
            response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
            return;
        }

        // Decode the file name (might contain spaces and on) and prepare file object.
        File image = new File(imagePath, URLDecoder.decode(requestedImage, "UTF-8"));

        // Check if file actually exists in filesystem.
        if (!image.exists()) {
            // Do your thing if the file appears to be non-existing.
            // Throw an exception, or send 404, or show default/warning image, or just ignore it.
            response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
            return;
        }

        // Get content type by filename.
        String contentType = getServletContext().getMimeType(image.getName());

        // Check if file is actually an image (avoid download of other files by hackers!).
        // For all content types, see: http://www.w3schools.com/media/media_mimeref.asp
        if (contentType == null || !contentType.startsWith("image")) {
            // Do your thing if the file appears not being a real image.
            // Throw an exception, or send 404, or show default/warning image, or just ignore it.
            response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
            return;
        }

        // Init servlet response.
        response.reset();
        response.setContentType(contentType);
        response.setHeader("Content-Length", String.valueOf(image.length()));

        // Write image content to response.
        Files.copy(image.toPath(), response.getOutputStream());
    }

}


text:
using Microsoft.EntityFrameworkCore;
using NullDesk.Extensions.Mailer.Core;

namespace NullDesk.Extensions.Mailer.History.EntityFramework.SqlServer
{
    /// <summary>
    ///     Settings for an entity framework history store using SQL Server.
    /// </summary>
    /// <seealso cref="NullDesk.Extensions.Mailer.Core.StandardHistoryStoreSettings" />
    public class SqlEntityHistoryStoreSettings : StandardHistoryStoreSettings
    {
        /// <summary>
        ///     The SQL connection string for the history context.
        /// </summary>
        /// <value>The connection string.</value>
        public string ConnectionString { get; set; }

        /// <summary>
        ///     Indicates whether to automatically initialize the database on startup.
        /// </summary>
        /// <value><c>true</c> to automatically initialize database; otherwise, <c>false</c>.</value>
        public bool AutoInitializeDatabase { get; } = true;

        /// <summary>
        ///     Performs an implicit conversion from <see cref="SqlEntityHistoryStoreSettings" /> to
        ///     <see cref="EntityHistoryStoreSettings" />.
        /// </summary>
        /// <param name="sqlSettings">The d.</param>
        /// <returns>The result of the conversion.</returns>
        public static implicit operator EntityHistoryStoreSettings(SqlEntityHistoryStoreSettings sqlSettings)
        {
            return new EntityHistoryStoreSettings
            {
                AutoInitializeDatabase = sqlSettings.AutoInitializeDatabase,
                IsEnabled = sqlSettings.IsEnabled,
                StoreAttachmentContents = sqlSettings.StoreAttachmentContents,
                SourceApplicationName = sqlSettings.SourceApplicationName,
                DbOptions = new DbContextOptionsBuilder<HistoryContext>()
                    .UseSqlServer(sqlSettings.ConnectionString)
                    .Options
            };
        }
    }
}


text:
Cheney is now less popular than Dan Quayle was as Vice President

Vice President Dick Cheney's popularity has hit an all-time low, with recent polling by The New York Times and CBS News suggesting that he has replaced Dan Quayle as the most unpopular vice president in recent history.


text:
GiantSquid::GiantSquid() {
    name = "Giant Squid";
    ExperienceAmount = 50;
    CoinsDrop = Common::RandomInt(0, 99);
}

EnemyType GiantSquid::GetType() {
    return etGiantSquid;
}

int GiantSquid::ReturnDamage() {
    return Common::RandomInt(7, 14);
}

int GiantSquid::ReturnRiskAttackDamage() {
    int selector = Common::RandomInt(0, 5);
    switch(selector) {
    case 0:
    case 1:
    case 2:
    case 3:
        return 0;
        break;
    case 4:
    case 5:
        return 20;
        break;
    default:
        return 0;
        break;
    }
}

int GiantSquid::ReturnHealAmount() {
    return Common::RandomInt(5, 11);
}

std::string GiantSquid::GetIntro() {
    return "With a thunderous splash...";
}


text:
({
	insertTableTitle: "Wstawianie tabeli",
	modifyTableTitle: "Modyfikowanie tabeli",
	rows: "Wiersze:",
	columns: "Kolumny:",
	align: "Wyrównanie:",
	cellPadding: "Dopełnianie komórek:",
	cellSpacing: "Odstępy między komórkami:",
	tableWidth: "Szerokość tabeli:",
	backgroundColor: "Kolor tła:",
	borderColor: "Kolor ramki:",
	borderThickness: "Grubość ramki",
	percent: "procent",
	pixels: "piksle",
	"default": "domyślna",
	left: "lewa strona",
	center: "środek",
	right: "prawa strona",
	buttonSet: "Ustaw", // translated elsewhere?
	buttonInsert: "Wstaw",

	selectTableLabel: "Wybierz tabelę",
	insertTableRowBeforeLabel: "Dodaj wiersz przed",
	insertTableRowAfterLabel: "Dodaj wiersz po",
	insertTableColumnBeforeLabel: "Dodaj kolumnę przed",
	insertTableColumnAfterLabel: "Dodaj kolumnę po",
	deleteTableRowLabel: "Usuń wiersz",
	deleteTableColumnLabel: "Usuń kolumnę"
})