text:
/*
 * BP_LinkedList.cc
 *
 *  Created on: Aug 27, 2013
 *      Author: root
 */

#include "../../include/BP-Main.h"

// creates a new linked list head object
P_BP_LINKL BP_CreateLinkL(char *description, BP_BOOL thread_safe)
{

	// allocate the new list item
	P_BP_LINKL list = (P_BP_LINKL) bpcalloc(sizeof(BP_LINKL), 1);
	if(!list)
		return NULL;

	if(thread_safe)
	{

		// set thread safe enabling here
		list->thread_safe_enabled = true;

		// initialize semaphore
		sem_init(&list->thread_safe_semaphore, 0, 1);

	}

	// reconfigure semaphore
	if(list->thread_safe_enabled)
		sem_wait(&list->thread_safe_semaphore);

	// initialize the queue
	TAILQ_INIT(&list->head);

	// copy in the description
	if(description)
		strncpy((char *) &list->description, description, sizeof(list->description)-1);

	// assign the uuid as a new random UUID
	list->uuid = NEW_RANDOM_UUID;

	// reconfigure semaphore
	if(list->thread_safe_enabled)
		sem_post(&list->thread_safe_semaphore);

	// return the filled out list
	return list;

}

// adds data to the front of the list (push front)
BP_ERROR_T BP_AddDataToLinkLHead(P_BP_LINKL head, void * data, size_t data_size,  BP_MEMPROF_ALLOC_TYPE type, BPLN_PARMS)
{

	if(!head)
		return ERR_FAILURE;
	if(!data)
		return ERR_FAILURE;
	if(!data_size)
		return ERR_FAILURE;

	// create new data
	P_BP_LINKL_DATA new_data = (P_BP_LINKL_DATA) bpcalloc(sizeof(BP_LINKL_DATA), 1);
	if(!new_data)
		return ERR_FAILURE;

	new_data->data      = data;
	new_data->data_size = data_size;
	new_data->data_type = type;

	// add debugging info if set
	if(file_name)
		new_data->file = (char *) bpstrdup(file_name);
	if(line_number)
		new_data->line_number = line_number;
	if(func)
		new_data->function = (char *) bpstrdup(func);

	// reconfigure semaphore
	if(head->thread_safe_enabled)
		sem_wait(&head->thread_safe_semaphore);

	// insert a new item into the queue
	TAILQ_INSERT_HEAD(&head->head, new_data, linkl_data);

	// increment the data size
	head->total_size += data_size;
	head->total_allocations++;

	// reconfigure semaphore
	if(head->thread_safe_enabled)
		sem_post(&head->thread_safe_semaphore);

	// return indicating success
	return ERR_SUCCESS;

}

// adds data to the end of a list (push tail)
BP_ERROR_T BP_AddDataToLinkLTail(P_BP_LINKL head, void * data, size_t data_size,  BP_MEMPROF_ALLOC_TYPE type, BPLN_PARMS)
{

	if(!head)
		return ERR_FAILURE;
	if(!data)
		return ERR_FAILURE;
	if(!data_size)
		return ERR_FAILURE;

	// create new data
	P_BP_LINKL_DATA new_data = (P_BP_LINKL_DATA) bpcalloc(sizeof(BP_LINKL_DATA), 1);
	if(!new_data)
		return ERR_FAILURE;

	new_data->data      = data;
	new_data->data_size = data_size;
	new_data->data_type = type;

	// add debugging info if set
	if(file_name)
		new_data->file = (char *) bpstrdup(file_name);
	if(line_number)
		new_data->line_number = line_number;
	if(func)
		new_data->function = (char *) bpstrdup(func);

	// reconfigure semaphore
	if(head->thread_safe_enabled)
		sem_wait(&head->thread_safe_semaphore);

	// insert a new item into the queue
	TAILQ_INSERT_TAIL(&head->head, new_data, linkl_data);

	// increment the data size
	head->total_size += data_size;
	head->total_allocations++;

	// reconfigure semaphore
	if(head->thread_safe_enabled)
		sem_post(&head->thread_safe_semaphore);

	// return indicating success
	return ERR_SUCCESS;

}

// adds data to the end of a list (push tail)
BP_ERROR_T BP_AddAfterLinkL(P_BP_LINKL head, P_BP_LINKL_DATA insert_after_this, void * data, size_t data_size,  BP_MEMPROF_ALLOC_TYPE type, BPLN_PARMS)
{

	if(!head)
		return ERR_FAILURE;
	if(!insert_after_this)
		return ERR_FAILURE;
	if(!data)
		return ERR_FAILURE;
	if(!data_size)
		return ERR_FAILURE;

	// create new data
	P_BP_LINKL_DATA new_data = (P_BP_LINKL_DATA) bpcalloc(sizeof(BP_LINKL_DATA), 1);
	if(!new_data)
		return ERR_FAILURE;

	new_data->data      = data;
	new_data->data_size = data_size;
	new_data->data_type = type;

	// add debugging info if set
	if(file_name)
		new_data->file = (char *) bpstrdup(file_name);
	if(line_number)
		new_data->line_number = line_number;
	if(func)
		new_data->function = (char *) bpstrdup(func);

	// reconfigure semaphore
	if(head->thread_safe_enabled)
		sem_wait(&head->thread_safe_semaphore);

	// insert a new item into the queue
	TAILQ_INSERT_AFTER(&head->head, insert_after_this, new_data, linkl_data);

	// increment the data size
	head->total_size += data_size;
	head->total_allocations++;

	// reconfigure semaphore
	if(head->thread_safe_enabled)
		sem_post(&head->thread_safe_semaphore);

	// return indicating success
	return ERR_SUCCESS;

}

// adds data to the end of a list (push tail)
BP_ERROR_T BP_AddBeforeLinkL(P_BP_LINKL head, P_BP_LINKL_DATA insert_before_this, void * data, size_t data_size,  BP_MEMPROF_ALLOC_TYPE type, BPLN_PARMS)
{

	if(!head)
		return ERR_FAILURE;
	if(!insert_before_this)
		return ERR_FAILURE;
	if(!data)
		return ERR_FAILURE;
	if(!data_size)
		return ERR_FAILURE;

	// create new data
	P_BP_LINKL_DATA new_data = (P_BP_LINKL_DATA) bpcalloc(sizeof(BP_LINKL_DATA), 1);
	if(!new_data)
		return ERR_FAILURE;

	new_data->data      = data;
	new_data->data_size = data_size;
	new_data->data_type = type;

	// add debugging info if set
	if(line_number)
		new_data->line_number = line_number;
	if(func)
		new_data->function = (char *) bpstrdup(func);

	// reconfigure semaphore
	if(head->thread_safe_enabled)
		sem_wait(&head->thread_safe_semaphore);

	// insert a new item into the queue
	TAILQ_INSERT_BEFORE(insert_before_this, new_data, linkl_data);

	// increment the data size
	head->total_size += data_size;
	head->total_allocations++;

	// reconfigure semaphore
	if(head->thread_safe_enabled)
		sem_post(&head->thread_safe_semaphore);

	// return indicating success
	return ERR_SUCCESS;

}

// destroys a linked list item
BP_ERROR_T BP_DestroyLinkLItem(P_BP_LINKL head, P_BP_LINKL_DATA item)
{

	if(!head)
		return ERR_FAILURE;
	if(!item)
		return ERR_FAILURE;

	// reconfig semaphore
	if(head->thread_safe_enabled)
		sem_wait(&head->thread_safe_semaphore);

	// remove item from the list
	TAILQ_REMOVE(&head->head, item, linkl_data);

	// subtract the total size
	head->total_size = head->total_size - item->data_size;
	head->total_allocations--;

	if(item->data)
	{
		bpfree(item->data);
		item->data = NULL;
	}

	if(item->file)
	{
		bpfree(item->file);
		item->file = NULL;
	}

	if(item->function)
	{
		bpfree(item->function);
		item->function = NULL;
	}

	// destroy the actual item
	bpfree(item);
	item = NULL;

	// reconfig semaphore
	if(head->thread_safe_enabled)
		sem_post(&head->thread_safe_semaphore);

	// return indicating success
	return ERR_SUCCESS;

}

// destroys an entire linked list
BP_ERROR_T BP_DestroyLinkL(P_BP_LINKL head, BP_BOOL destroy_head)
{

	// ensure we have a structure
	if(!head)
		return ERR_FAILURE;

	// reconfig semaphore
	if(head->thread_safe_enabled)
		sem_wait(&head->thread_safe_semaphore);

	// destroy flat buffer data if set
	if(head->flat_buff)
	{
		BP_LinkLDestroyFlatStringData(head);
		head->flat_buff   = NULL;
		head->flat_buff_n = 0;
	}

	// fast method recommended by documentation (faster than using TAILQ_REMOVE)
	P_BP_LINKL_DATA data = NULL;
	while((data = TAILQ_FIRST(&head->head)))
	{

		// remove the item
		TAILQ_REMOVE(&head->head, data, linkl_data);

		// destroy data if set
		if(data->data)
		{
			bpfree(data->data);
			data->data = NULL;
		}

		// destroy function if set
		if(data->function)
		{
			bpfree(data->function);
			data->function = NULL;
		}
		if(data->file)
		{
			bpfree(data->file);
			data->file = NULL;
		}

		// destroy the data
		bpfree(data);
		data = NULL;

	}

	// reconfig semaphore
	if(head->thread_safe_enabled)
		sem_post(&head->thread_safe_semaphore);

	// ensure we destroy the lingering UUID
	if(head->uuid)
	{
		bpfree(head->uuid);
		head->uuid = NULL;
	}

	// free structure at his point
	if(destroy_head)
		bpfree(head);

	// return indicating success
	return ERR_SUCCESS;

}

// displays head data only
BP_ERROR_T BP_DisplayLinkLHeadDataOnly(P_BP_LINKL head)
{

	// check head
	if(!head)
		return ERR_FAILURE;

	printf("\n [+] LinkL TailQ: %p", head);
	printf("\n\t description:            %s", head->description);
	printf("\n\t thread_safe_enabled:    %u", head->thread_safe_enabled);
	printf("\n\t thread_safe_semaphore:  %u", head->thread_safe_semaphore);
	printf("\n\t uuid:                   %s", head->uuid);
	printf("\n\t total_size:             %u", head->total_size);
	printf("\n\t total_allocations:      %u", head->total_allocations);
	printf("\n\t &head:                  %p", (void*) &head->head);
	printf("\n");

	// return indicating success
	return ERR_SUCCESS;

}

// displays the current tail queue
BP_ERROR_T BP_DisplayLinkL(P_BP_LINKL head)
{

	// check head
	if(!head)
		return ERR_FAILURE;

	// attempt to get the first item
	P_BP_LINKL_DATA first_item = TAILQ_FIRST(&head->head);

	// ensure we have a first item
	if(!first_item)
		return ERR_FAILURE;

	printf("\n [+] LinkL TailQ: %p", head);
	printf("\n\t description:            %s", head->description);
	printf("\n\t thread_safe_enabled:    %u", head->thread_safe_enabled);
	printf("\n\t thread_safe_semaphore:  %u", head->thread_safe_semaphore);
	printf("\n\t uuid:                   %s", head->uuid);
	printf("\n\t total_size:             %u", head->total_size);
	printf("\n\t total_allocations:      %u", head->total_allocations);
	printf("\n\t &head:                  %p", (void*) &head->head);
	printf("\n");

	// looks for a pointer in the item
	TAILQ_FOREACH(first_item, &head->head, linkl_data)
	{

		BP_DisplayLinkLItem(first_item);

	}

	// return indicating success
	return ERR_SUCCESS;

}

// displays a single linked list item
BP_ERROR_T BP_DisplayLinkLItem(P_BP_LINKL_DATA item)
{

	// ensure we have an item
	if(!item)
		return ERR_FAILURE;

	printf("\n\t [+] List Item: %p", item);
	// display source debug information if necessary
	if(item->file)
		printf("\n\t\t allocated at: (%s:%u) : %s", item->file, item->line_number, item->function);

	printf("\n\t\t data:        %p", item->data);
	printf("\n\t\t data_size:   %u", item->data_size);
	printf("\n\t\t data_type:   ");

	switch(item->data_type)
	{
		case BP_MEMPROF_ALLOC_TYPE_UNSET:
			printf("BP_MEMPROF_ALLOC_TYPE_UNSET");
			break;
		case BP_MEMPROF_ALLOC_TYPE_MALLOC:
			printf("BP_MEMPROF_ALLOC_TYPE_MALLOC");
			break;
		case BP_MEMPROF_ALLOC_TYPE_CALLOC:
			printf("BP_MEMPROF_ALLOC_TYPE_CALLOC");
			break;
		case BP_MEMPROF_ALLOC_TYPE_STRDUP:
			printf("BP_MEMPROF_ALLOC_TYPE_STRDUP");
			break;
		case BP_MEMPROF_ALLOC_TYPE_STRNDUP:
			printf("BP_MEMPROF_ALLOC_TYPE_STRNDUP");
			break;
		case BP_MEMPROF_ALLOC_TYPE_REALLOC:
			printf("BP_MEMPROF_ALLOC_TYPE_REALLOC");
			break;
		case BP_MEMPROF_ALLOC_TYPE_USER_DEFINED_ASCII:
			printf("BP_MEMPROF_ALLOC_TYPE_USER_DEFINED_ASCII");
			break;
		default:
			printf("UNKNOWN TYPE");
			break;

	}

	// add trailing newline
	printf("\n");

	// return indicating success
	return ERR_SUCCESS;

}

// attemts to forward lookup a pointer
P_BP_LINKL_DATA BP_ForwardLookupDataItemFromPointer(P_BP_LINKL head, void *ptr)
{

	if(!ptr)
		return NULL;

	// attempt to get the first item
	P_BP_LINKL_DATA first_item = TAILQ_FIRST(&head->head);

	// ensure we have a first item
	if(!first_item)
		return NULL;

	// looks for a pointer in the item
	TAILQ_FOREACH(first_item, &head->head, linkl_data)
	{
		if(first_item->data == ptr)
			return first_item;
	}

	// return no ptr
	return NULL;

}

// attempts to backward lookup
P_BP_LINKL_DATA BP_BackwardLookupDataItemFromPointer(P_BP_LINKL head, void *ptr  )
{

	if(!ptr)
		return NULL;

	// set item
	P_BP_LINKL_DATA item = TAILQ_FIRST(&head->head);

	// looks for a pointer in the item
	TAILQ_FOREACH(item, &head->head, linkl_data) {
		if(item->data == ptr)
			return item;
	}

	// return no ptr
	return NULL;

}

// ==== string searching ========================

// attempts to search all elements for a string
char * BP_LinkLSearchForString(P_BP_LINKL head, char *search_string, size_t search_string_len)
{

	// run checks
	if(!head)
		return NULL;
	if(!search_string)
		return NULL;
	if(!search_string_len)
		return NULL;

	// attempt to get the first item
	P_BP_LINKL_DATA first_item = TAILQ_FIRST(&head->head);

	// ensure we have a first item
	if(!first_item)
		return NULL;

	// looks for a pointer in the item
	TAILQ_FOREACH(first_item, &head->head, linkl_data)
	{

		// only work with strndup/strdup types
		if
		(
			first_item->data_type != BP_MEMPROF_ALLOC_TYPE_STRDUP   &&
			first_item->data_type != BP_MEMPROF_ALLOC_TYPE_STRNDUP
		)
		{
			continue;
		}

		// ensure lengths match
		if(bpstrlen(search_string) != bpstrlen((char *) first_item->data))
			continue;

		// if the strings match, return the data
		if(memcmp((void *) first_item->data, (void *) search_string, search_string_len) == 0)
			return (char *) first_item->data;

	}

	// return null if we can't find the string
	return NULL;

}

// ==== list flateners ==========================

// This will take each element in the array, create a buffer of appropriate length
// and store each element within the newly created buffer essentially creating a
// flat unsigned char array representing the entire list.
BP_ERROR_T BP_LinkLFlattenRaw(P_BP_LINKL head)
{

	// ensure we have a head
	if(!head)
		return ERR_FAILURE;

	// destroy flattened data if it already exists
	if(head->flat_buff)
	{
		bpfree(head->flat_buff);
		head->flat_buff_n = 0;
		head->flat_buff   = NULL;
	}

	// ensure the list has a total size
	if(!head->total_size)
		return ERR_FAILURE;

	// attempt to get the first item
	P_BP_LINKL_DATA first_item = TAILQ_FIRST(&head->head);

	// ensure we have a first item
	if(!first_item)
		return ERR_FAILURE;

	// current position, used for writing data to the string
	size_t current_pos = 0;

	// inner iterator for data
	size_t n = 0;

	// allocate space for the buffer (+1 for mandatory null termination)
	head->flat_buff = (unsigned char *) bpcalloc(head->total_size+1, 1);
	head->flat_buff_n = head->total_size;

	// since void has no type, we need a temporary data pointer
	unsigned char * data = NULL;

	// looks for a pointer in the item
	TAILQ_FOREACH(first_item, &head->head, linkl_data)
	{

		// set temporary pointer
		data = (unsigned char *) first_item->data;

		// now write the buffer into position
		for(n=0; n < first_item->data_size; n++)
		{
			head->flat_buff[current_pos] = (unsigned char) data[n];
			current_pos++;
 		}

	}

	// return indicating success
	return ERR_SUCCESS;

}

// This flattens the the linkl string elements into a
// joined single string.  It removes the null terminators
// from existing strings when joining.  If you want to
// flatten raw data, use the raw version.
BP_ERROR_T BP_LinkLFlattenJoinStringElements(P_BP_LINKL head)
{

	// ensure we have a head
	if(!head)
		return ERR_FAILURE;

	// destroy flattened data if it already exists
	if(head->flat_buff)
	{
		bpfree(head->flat_buff);
		head->flat_buff_n = 0;
		head->flat_buff   = NULL;
	}

	// ensure the list has a total size
	if(!head->total_size)
		return ERR_FAILURE;

	// attempt to get the first item
	P_BP_LINKL_DATA first_item = TAILQ_FIRST(&head->head);

	// ensure we have a first item
	if(!first_item)
		return ERR_FAILURE;

	// current position, used for writing data to the string
	size_t current_pos = 0;

	// inner iterator for data
	size_t n = 0;

	// allocate space for the buffer (+1 for mandatory null termination)
	head->flat_buff   = (unsigned char *) bpcalloc(head->total_size+1, 1);
	head->flat_buff_n = head->total_size;

	// since void has no type, we need a temporary data pointer
	unsigned char * data = NULL;

	// looks for a pointer in the item
	TAILQ_FOREACH(first_item, &head->head, linkl_data)
	{

		// ensure we have a string chunk
		if(
			(first_item->data_type == BP_MEMPROF_ALLOC_TYPE_STRDUP)  ||
			(first_item->data_type == BP_MEMPROF_ALLOC_TYPE_STRNDUP) ||
			(first_item->data_type == BP_MEMPROF_ALLOC_TYPE_USER_DEFINED_ASCII)
		)
		{

			// set temporary pointer
			data = (unsigned char *) first_item->data;

			// now write the buffer into position
			for(n=0; n < (strnlen((char *) first_item->data, first_item->data_size)); n++)
			{

				head->flat_buff[current_pos] = (unsigned char) data[n];
				current_pos++;

	 		}

		}

	}

	// return indicating success
	return ERR_SUCCESS;

}

// This will destroy flattened data generated by the linkl flattener.
BP_ERROR_T BP_LinkLDestroyFlatStringData(P_BP_LINKL head)
{

	// check to make sure we have a head pointer
	if(!head)
		return ERR_FAILURE;

	// destroy flattened data if it already exists
	if(head->flat_buff)
	{

		// free the buffer
		bpfree(head->flat_buff);

		// reset values
		head->flat_buff_n = 0;
		head->flat_buff = NULL;

	}

	// return indicating success
	return ERR_SUCCESS;

}

// ==== list to array utilities =================

// This routine takes a linkl and copies all data within into an external
// pointer array.  The elements in the array are the linear progression of
// data within the list.
void ** BP_LinkLToBPCallocPointerArray(P_BP_LINKL head)
{

	// run checks
	if(!head)
		return NULL;

	// attempt to get the first item
	P_BP_LINKL_DATA first_item = TAILQ_FIRST(&head->head);

	// ensure we have a first item
	if(!first_item)
		return NULL;

	// ensure we have a total allocation count
	if(!head->total_allocations)
		return NULL;

	// create array (total allocs + 1)
	void ** ret_array = (void **) bpcalloc(sizeof(void *) * (head->total_allocations + 1), 1);

	// index iterator
	size_t index_iter = 0;

	// looks for a pointer in the item
	TAILQ_FOREACH(first_item, &head->head, linkl_data)
	{

		// allocate space for the memory copy
		ret_array[index_iter] = (void *) bpcalloc(first_item->data_size+1, 1);

		// Ensure we have a ret array index created, if not fail-hard and destroy all external
		// memory.
		if(!ret_array[index_iter])
		{

			// destroy the pointer array
			BP_DestroyPointerArrayNullTerminated(ret_array);

			// destroy the returned array after elements are freed
			bpfree(ret_array);

			// return null
			return NULL;

		}

		// copy in the data
		memcpy(ret_array[index_iter], first_item->data, first_item->data_size);

		// increment the index iterator
		index_iter++;

	}

	// return null if we can't find the string
	return ret_array;

}

// ==== print utilities =========================

// Attempts to print all string elements out to standard out, mostly for
// debugging/development testing.
BP_ERROR_T BP_LinkLPrintStringElementsToStdout(P_BP_LINKL head)
{

	// ensure we have a head
	if(!head)
		return ERR_FAILURE;

	// ensure the list has a total size
	if(!head->total_size)
		return ERR_FAILURE;

	// attempt to get the first item
	P_BP_LINKL_DATA first_item = TAILQ_FIRST(&head->head);

	// ensure we have a first item
	if(!first_item)
		return ERR_FAILURE;

	// string index used to display
	size_t string_index = 0;

	// looks for a pointer in the item
	TAILQ_FOREACH(first_item, &head->head, linkl_data)
	{

		// display header if we don't have a string index
		if(string_index == 0)
			printf("\n [+] Displaying String Elements for List %p", head);

		// only work with strndup/strdup types
		if
		(
			first_item->data_type != BP_MEMPROF_ALLOC_TYPE_STRDUP   &&
			first_item->data_type != BP_MEMPROF_ALLOC_TYPE_STRNDUP
		)
		{

			// increase the string index
			string_index++;
			continue;

		}

		// display string index
		printf("\n\t [%u] - %s", string_index, (char *) first_item->data);

		// increase the string index
		string_index++;

	}

	// return indicating success
	return ERR_SUCCESS;

}

// ==== allocator Functions =====================

char * tq_strdup (P_BP_LINKL head, char * dupe, BPLN_PARMS)
{

	// ensure we have a head entry to work with
	if(!head)
		return NULL;

	// allocate chunk space
	char * chunk = bpstrdup( dupe );
	if(!chunk)
		return NULL;

	// get the dupe length
	size_t dup_len = bpstrlen((char *) chunk);

	// attempt to add the chunk and return directly
	if(BP_AddDataToLinkLTail(head, chunk, dup_len+1 , BP_MEMPROF_ALLOC_TYPE_STRDUP, file_name, line_number, func) != ERR_SUCCESS)
	{
		bpfree(chunk);
		chunk = NULL;
		return NULL;
	}

	// return the chunk
	return chunk;
}

char * tq_strndup(P_BP_LINKL head, char *dup, size_t n,  BPLN_PARMS)
{

	// ensure we have a head entry to work with
	if(!head)
		return NULL;

	// allocate chunk space
	char * chunk = bpstrndup( dup, n );
	if(!chunk)
		return NULL;

	// attempt to add the chunk and return directly
	if(BP_AddDataToLinkLTail(head, chunk, n+1 , BP_MEMPROF_ALLOC_TYPE_STRNDUP, file_name, line_number, func) != ERR_SUCCESS)
	{
		bpfree(chunk);
		chunk = NULL;
		return NULL;
	}

	// return the chunk
	return chunk;

}

// unique version of strdup (only will dupe a string if it doesn't already
// exist in the linkl.
char * tq_strdup_unique (P_BP_LINKL head, char *dup, BPLN_PARMS)
{

	// ensure we have a head and a dup
	if(!head)
		return NULL;

	// ensure we have a string to duplicate
	if(!dup)
		return NULL;

	// calculate duplicate length
	size_t dup_len = bpstrlen(dup);

	// attempt to lookup the string
	char * search_str = BP_LinkLSearchForString(head, dup, dup_len);

	// if we found the string in the list, return null
	if(search_str)
		return NULL;

	// run actual strdup now
	return tq_strdup(head, dup, BPLN);

}

// unique version of strndup (only will dupe a string if it doesn't already
// exist in the linkl.
char * tq_strndup_unique(P_BP_LINKL head, char *dup, size_t n, BPLN_PARMS)
{

	// ensure we have a head and a dup
	if(!head)
		return NULL;

	// ensure we have a string to duplicate
	if(!dup)
		return NULL;

	// ensure we have a length for the string we're duplicating
	if(!n)
		return NULL;

	// attempt to lookup the string
	char * search_str = BP_LinkLSearchForString(head, dup, n);

	// if we found the string in the list, return null
	if(search_str)
		return NULL;

	// run actual strndup now
	return tq_strndup(head, dup, n, BPLN);

}

// reallocate data
void * tq_realloc(P_BP_LINKL head, void * addr, size_t size,  BPLN_PARMS)
{

	// ensure we have a head entry to work with
	if(!head)
		return NULL;

	// chunk to be returned
	void * chunk = NULL;

	// lookup item if necessary
	P_BP_LINKL_DATA item = (P_BP_LINKL_DATA) BP_ForwardLookupDataItemFromPointer(head, addr);

	// if the item already exists (from previous allocation)
	if(item)
	{

		// subtrack previous size from total
		head->total_size = head->total_size - item->data_size;

		// realloc the actual chunk value
		item->data      = bprealloc( item->data, size );
		item->data_size = size;

		// recalculate the total size
		head->total_size = head->total_size + item->data_size;

		// ensure we have allocated data
		if(!item->data)
		{
			BP_DestroyLinkLItem(head, item);
			return NULL;
		}

		// return the new data
		return item->data;

	}
	else
	{
		// allocate chunk space
		chunk = bprealloc( addr, size );

	}

	if(!chunk)
		return NULL;

	// attempt to add the chunk to the list if it wasn't already found
	if(BP_AddDataToLinkLTail(head, chunk, size , BP_MEMPROF_ALLOC_TYPE_REALLOC, file_name, line_number, func) != ERR_SUCCESS)
	{
		bpfree(chunk);
		chunk = NULL;
		return NULL;
	}

	// return the chunk
	return chunk;
}

void * tq_malloc (P_BP_LINKL head, size_t size,  BPLN_PARMS)
{
	// ensure we have a head entry to work with
	if(!head)
		return NULL;

	// allocate chunk space
	void * chunk = bpmalloc( size );
	if(!chunk)
		return NULL;;

	// attempt to add the chunk and return directly
	if(BP_AddDataToLinkLTail(head, chunk, size , BP_MEMPROF_ALLOC_TYPE_MALLOC, file_name, line_number, func) != ERR_SUCCESS)
	{
		bpfree(chunk);
		chunk = NULL;
		return NULL;
	}

	// return the chunk
	return chunk;

}

void * tq_calloc (P_BP_LINKL head, size_t size, size_t size_n,  BPLN_PARMS)
{

	// ensure we have a head entry to work with
	if(!head)
		return NULL;

	// allocate chunk space
	void * chunk = bpcalloc( 1, size);
	if(!chunk)
		return NULL;

	// attempt to add the chunk and return directly
	if(BP_AddDataToLinkLTail(head, chunk, size , BP_MEMPROF_ALLOC_TYPE_CALLOC, file_name, line_number, func) != ERR_SUCCESS)
	{
		bpfree(chunk);
		chunk = NULL;
		return NULL;
	}

	// return the chunk
	return chunk;

}

// Duplicate a chunk of memory into our linkl (adds memory to the end of the list)
void * tq_memdup (P_BP_LINKL head, void *data,  size_t size,    BPLN_PARMS)
{

	// run basic checks
	if(!head)
		return NULL;
	if(!data)
		return NULL;
	if(!size)
		return NULL;

	// allocate chunk space
	void * chunk = bpcalloc( 1, size);
	if(!chunk)
		return NULL;

	// copy data into chunk
	memcpy(chunk, data, size);

	// attempt to add the chunk and return directly
	if(BP_AddDataToLinkLTail(head, chunk, size , BP_MEMPROF_ALLOC_TYPE_CALLOC, file_name, line_number, func) != ERR_SUCCESS)
	{
		bpfree(chunk);
		chunk = NULL;
		return NULL;
	}

	// return the chunk
	return chunk;

}

// free's chunks and deletes link elements.  Can be used with
// chunks that may not be in the list (makes implementations easier)
void   tq_free   (P_BP_LINKL head, void * addr)
{

	if(!addr)
		return;
	if(!head)
	{
		printf("\n [+] Error: Cannot free a list element without an accompanying head.");
		return;
	}

	// look for item (returns null if it doesn't exist)
	P_BP_LINKL_DATA item = (P_BP_LINKL_DATA) BP_ForwardLookupDataItemFromPointer(head, addr);

	// destroy the individual link item
	BP_DestroyLinkLItem(head, item);

}

// Adds tabs to a string element in the linked list.  Typically used when generating
// large JSON buffers.
char * tq_tabs   (P_BP_LINKL head, size_t tab_count, BPLN_PARMS)
{

	// if we don't have a head, return null immediately
	if(!head)
		return NULL;

	// ceate tab buffer
	return BP_CreateTabBuffer(tab_count, head);

}

// links an existing chunk into a tailqueue
BP_ERROR_T tq_link(P_BP_LINKL head, void * addr, size_t size, BPLN_PARMS)
{

	// ensure we have a head entry to work with
	if(!head)
		return ERR_SUCCESS;

	if(!addr || !size)
		return ERR_FAILURE;

	// attempt to add the chunk and return directly
	if(BP_AddDataToLinkLTail(head, addr, size , BP_MEMPROF_ALLOC_TYPE_MALLOC, file_name, line_number, func) != ERR_SUCCESS)
	{
		return ERR_FAILURE;
	}

	// return indicating success
	return ERR_SUCCESS;

}

// links an existing chunk into a tailqueue (does a length check, max 100mb length)
BP_ERROR_T tq_link_str(P_BP_LINKL head, char * addr,BPLN_PARMS)
{

	// ensure we have a head entry to work with
	if(!head)
		return ERR_FAILURE;

	if(!addr)
		return ERR_FAILURE;

	// set max lookup for strnlen(might fault anyway)
	size_t max_len = 100 * BP_MEGABYTE;

	// get length
	size_t length = strnlen(addr, max_len);

	// don't link strings > 100mb
	if(length >= max_len)
		return ERR_FAILURE;

	// attempt to add the chunk and return directly
	if(BP_AddDataToLinkLTail(head, addr, length , BP_MEMPROF_ALLOC_TYPE_STRDUP, file_name, line_number, func) != ERR_SUCCESS)
	{
		return ERR_FAILURE;
	}

	// return indicating success
	return ERR_SUCCESS;

}

// links a pointer array to a tailqueue
BP_ERROR_T tq_link_ptr_array(P_BP_LINKL head, void ** ptrs, size_t ptr_n, size_t *lengths, BP_BOOL link_ptr_container, BPLN_PARMS)
{

	// ensure we have a head entry to work with
	if(!head)
		return ERR_FAILURE;

	if(!ptrs || !ptr_n || !lengths)
		return ERR_FAILURE;

	// walk pointers and link
	size_t n = 0;
	for(; n < ptr_n; n++)
	{

		// link the item
		// tq_link(head, ptrs[n], lengths[n], file_name, line_number, func);

		if(BP_AddDataToLinkLTail(head, (void *) ptrs[n], 100, BP_MEMPROF_ALLOC_TYPE_MALLOC, file_name, line_number, func) != ERR_SUCCESS)
		{
			printf("\n Failed to link.");
		}

	}

	if(BP_AddDataToLinkLTail(head, (void *) ptrs, ptr_n*sizeof(size_t) , BP_MEMPROF_ALLOC_TYPE_MALLOC, file_name, line_number, func) != ERR_SUCCESS)
	{
		printf("\n Failed to link.");
	}

	// return indicating success
	return ERR_SUCCESS;

}


text:
#ifndef __D3D10PREREQUISITES_H__
#define __D3D10PREREQUISITES_H__

#include "OgrePrerequisites.h"
#include "WIN32/OgreMinGWSupport.h" // extra defines for MinGW to deal with DX SDK

// Define versions for if DirectX is in use (Win32 only)
#define DIRECT3D_VERSION 0x0900

// some D3D commonly used macros
#define SAFE_DELETE(p)       { if(p) { delete (p);     (p)=NULL; } }
#define SAFE_DELETE_ARRAY(p) { if(p) { delete[] (p);   (p)=NULL; } }
#define SAFE_RELEASE(p)      { if(p) { (p)->Release(); (p)=NULL; } }

#if !defined(NOMINMAX) && defined(_MSC_VER)
#	define NOMINMAX // required to stop windows.h messing up std::min
#endif

#include <d3d10_1.h>
#include <d3d10.h>
#include <d3dx10.h>
#include <d3d10_1shader.h>

namespace Ogre
{
	// Predefine classes
	class D3D10RenderSystem;
	class D3D10RenderWindow;
	class D3D10Texture;
	class D3D10TextureManager;
	class D3D10Driver;
	class D3D10DriverList;
	class D3D10VideoMode;
	class D3D10VideoModeList;
	class D3D10GpuProgram;
	class D3D10GpuProgramManager;
	class D3D10HardwareBufferManager;
	class D3D10HardwareIndexBuffer;
	class D3D10HLSLProgramFactory;
	class D3D10HLSLProgram;
	class D3D10VertexDeclaration;
	class D3D10Device;
	class D3D10HardwareBuffer;
	class D3D10HardwarePixelBuffer;

	// Should we ask D3D to manage vertex/index buffers automatically?
	// Doing so avoids lost devices, but also has a performance impact
	// which is unacceptably bad when using very large buffers
#define OGRE_D3D_MANAGE_BUFFERS 1

	//-------------------------------------------
	// Windows setttings
	//-------------------------------------------
#if (OGRE_PLATFORM == OGRE_PLATFORM_WIN32) && !defined(OGRE_STATIC_LIB)
#	ifdef OGRED3DENGINEDLL_EXPORTS
#		define _OgreD3D10Export __declspec(dllexport)
#	else
#       if defined( __MINGW32__ )
#           define _OgreD3D10Export
#       else
#    		define _OgreD3D10Export __declspec(dllimport)
#       endif
#	endif
#else
#	define _OgreD3D10Export
#endif	// OGRE_WIN32
}
#endif

redpajama_set_name: RedPajamaGithub


text:
package cdv.stb.subscription;

import cdv.stb.telegram.protocol.Chat;
import cdv.stb.telegram.protocol.Message;
import cdv.stb.telegram.TelegramApiClient;
import org.junit.Test;

import static org.junit.Assert.*;
import static org.mockito.Matchers.anyLong;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

/**
 * @author Dmitry Coolga
 *         19.02.2017 11:07
 */
public class SubscriptionHandlerTest {

    private final TelegramApiClient clientMock = mock(TelegramApiClient.class);

    private final SubscriptionManager subscriptionManagerMock = mock(SubscriptionManager.class);

    private final SubscriptionHandler handler = new SubscriptionHandler(
            clientMock,
            subscriptionManagerMock);

    @Test
    public void testMatch() {
        assertTrue(handler.match(new Message(0, null, null, 0, "Бот, подписка")));
    }

    @Test
    public void testNotMatch() {
        assertFalse(handler.match(new Message(0, null, null, 0, null)));
        assertFalse(handler.match(new Message(0, null, null, 0, "")));
        assertFalse(handler.match(new Message(0, null, null, 0, "подписка")));
        assertFalse(handler.match(new Message(0, null, null, 0, "Бот, Подписка")));
    }

    @Test
    public void testFireSubscriptionRegistrationSucceeded() {
        testFire(true, "Подписка успешно зарегистрирована");
    }

    @Test
    public void testFireSubscriptionRegistrationFailed() {
        testFire(false, "Не удалось зарегистрировать подписку");
    }

    private void testFire(boolean subscribedSuccessfully, String expectedMessage) {

        when(subscriptionManagerMock.registerSubscription(anyLong()))
                .thenReturn(subscribedSuccessfully);

        Chat chat = new Chat(42, null, null, null, null);
        Message message = new Message(0, null, chat, 0, null);
        handler.handle(message);

        verify(clientMock).sendMessage(expectedMessage, 42);
        verify(subscriptionManagerMock).registerSubscription(42);
    }

}


text:
<?php

class Genmato_MultistoreSearchFields_Model_System_Config_Source_Search_Attributes
{

    public function toOptionArray()
    {
        $fields = array();

        $collection = Mage::getResourceModel('catalog/product_attribute_collection')
            ->addFilter('is_visible_in_advanced_search', 1);

        foreach ($collection as $attr) {
            $fields[] = array(
                'label' => $attr->getFrontendLabel(),
                'value' => $attr->getId()
            );
        }

        return $fields;
    }
}


text:
<?php
/**
 * Created by PhpStorm.
 * User : xin.zhang
 * Date : 15/7/13
 * Time : 下午5:59
 * Email: zhangxinmailvip@foxmail.com
 */

namespace common\components;

class SiteUrl {

    public static function getTripUrl($tripId)
    {
        $baseUrl=\Yii::$app->params['front_suiuu_url'];
        return $baseUrl."/view-trip/info/".$tripId.".html";
    }

    public static function getTripSearchUrl($keywords)
    {
        $baseUrl=\Yii::$app->params['front_suiuu_url'];
        return $baseUrl."/view-trip/list?s=".$keywords;
    }
    public static function getTripActivityUrl($keywords)
    {
        $baseUrl=\Yii::$app->params['front_suiuu_url'];
        return $baseUrl."/view-trip/list?a=".$keywords;
    }

    public static function getViewUserUrl($userId)
    {
        $baseUrl=\Yii::$app->params['front_suiuu_url'];
        return $baseUrl."/view-user/info/".$userId.".html";
    }

    public static function getEditTripUrl($tripId)
    {
        $baseUrl=\Yii::$app->params['front_suiuu_url'];
        return $baseUrl."/trip/edit-trip?trip=".$tripId;
    }

    public static function getOrderPayUrl($orderNumber)
    {
        $baseUrl=\Yii::$app->params['front_suiuu_url'];
        return $baseUrl."/user-order/info?orderNumber=".$orderNumber;

    }

}


text:
package org.asteriskjava.pbx.agi;

import java.util.concurrent.CountDownLatch;

import org.asteriskjava.fastagi.AgiChannel;
import org.asteriskjava.fastagi.AgiException;
import org.asteriskjava.pbx.AgiChannelActivityAction;
import org.asteriskjava.pbx.Channel;

public class AgiChannelActivityBlindTransfer implements AgiChannelActivityAction
{

    CountDownLatch latch = new CountDownLatch(1);
    private String target;
    private String sipHeader;
    int timeout = 30;
    private String callerId;

    public AgiChannelActivityBlindTransfer(String fullyQualifiedName, String sipHeader, String callerId)
    {
        this.target = fullyQualifiedName;
        this.sipHeader = sipHeader;
        this.callerId = callerId;
        if (sipHeader == null)
        {
            this.sipHeader = "";
        }
    }

    @Override
    public void execute(AgiChannel channel, Channel ichannel) throws AgiException, InterruptedException
    {

        channel.setVariable("__SIPADDHEADER", sipHeader);
        channel.setCallerId(callerId);
        ichannel.setCurrentActivityAction(new AgiChannelActivityHold());
        channel.dial(target, timeout, "");

    }

    @Override
    public boolean isDisconnect()
    {
        return false;
    }

    @Override
    public void cancel()
    {
        latch.countDown();

    }
}


text:
package proguard.gui.splash;

/**
 * This Timing ramps up linearly from 0 to 1 in a given repeated time interval.
 *
 * @author Eric Lafortune
 */
public class SawToothTiming implements Timing
{
    private final long period;
    private final long phase;

    /**
     * Creates a new SawToothTiming.
     * @param period the time period for a full cycle.
     * @param phase  the phase of the cycle, which is added to the actual time.
     */
    public SawToothTiming(long period, long phase)
    {
        this.period = period;
        this.phase  = phase;
    }

    // Implementation for Timing.

    public double getTiming(long time)
    {
        // Compute the translated and scaled saw-tooth function.
        return (double)((time + phase) % period) / (double)period;
    }
}


text:
@class GGComment;
@interface GGCommentCell : UITableViewCell

@property(nonatomic,strong) GGComment  * comment;

@end


text: A metacello repository in a directory


text:
import collections
import copy

from absl.testing import parameterized
import tensorflow as tf

from tensorflow_federated.python.learning.optimizers import optimizer as optimizer_base
from tensorflow_federated.python.learning.optimizers import optimizer_test_utils
from tensorflow_federated.python.learning.optimizers import sgdm

_SCALAR_SPEC = tf.TensorSpec([1], tf.float32)
_STRUCT_SPEC = [tf.TensorSpec([2], tf.float32), tf.TensorSpec([3], tf.float32)]
_NESTED_SPEC = [
    tf.TensorSpec([10], tf.float32),
    [tf.TensorSpec([20], tf.float32), [tf.TensorSpec([30], tf.float32)]]
]

class SGDTest(optimizer_test_utils.TestCase, parameterized.TestCase):

  def test_state_structure(self):
    optimizer = sgdm.build_sgdm(0.01)
    state = optimizer.initialize(_SCALAR_SPEC)
    self.assertLen(state, 1)
    self.assertIn(optimizer_base.LEARNING_RATE_KEY, state)

  def test_state_structure_momentum(self):
    optimizer = sgdm.build_sgdm(0.01, momentum=0.9)
    state = optimizer.initialize(_SCALAR_SPEC)
    self.assertLen(state, 3)
    self.assertIn(optimizer_base.LEARNING_RATE_KEY, state)
    self.assertIn(sgdm._MOMENTUM_KEY, state)
    self.assertIn(sgdm._ACCUMULATOR_KEY, state)

  def test_math_no_momentum(self):
    weights = tf.constant([1.0], tf.float32)
    gradients = tf.constant([2.0], tf.float32)
    optimizer = sgdm.build_sgdm(0.01)
    history = [weights]

    state = optimizer.initialize(_SCALAR_SPEC)

    for _ in range(4):
      state, weights = optimizer.next(state, weights, gradients)
      history.append(weights)
    self.assertAllClose([[1.0], [0.98], [0.96], [0.94], [0.92]], history)

  def test_math_momentum_0_5(self):
    weights = tf.constant([1.0], tf.float32)
    gradients = tf.constant([2.0], tf.float32)
    optimizer = sgdm.build_sgdm(0.01, momentum=0.5)
    history = [weights]

    state = optimizer.initialize(_SCALAR_SPEC)

    for _ in range(4):
      state, weights = optimizer.next(state, weights, gradients)
      history.append(weights)
    self.assertAllClose([[1.0], [0.98], [0.95], [0.915], [0.8775]], history)

  @parameterized.named_parameters(
      ('scalar_spec', _SCALAR_SPEC, None),
      ('struct_spec', _STRUCT_SPEC, None),
      ('nested_spec', _NESTED_SPEC, None),
      ('scalar_spec_and_momentum', _SCALAR_SPEC, 0.5),
      ('struct_spec_and_momentum', _STRUCT_SPEC, 0.5),
      ('nested_spec_and_momentum', _NESTED_SPEC, 0.5),
  )
  def test_executes_with(self, spec, momentum):
    weights = tf.nest.map_structure(lambda s: tf.ones(s.shape, s.dtype), spec)
    gradients = tf.nest.map_structure(lambda s: tf.ones(s.shape, s.dtype), spec)
    optimizer = sgdm.build_sgdm(0.01, momentum=momentum)

    state = optimizer.initialize(spec)
    for _ in range(10):
      state, weights = optimizer.next(state, weights, gradients)

    tf.nest.map_structure(lambda w: self.assertTrue(all(tf.math.is_finite(w))),
                          weights)

  def test_executes_with_indexed_slices(self):
    # TF can represent gradients as tf.IndexedSlices. This test makes sure this
    # case is supported by the optimizer.
    weights = tf.ones([4, 2])
    gradients = tf.IndexedSlices(
        values=tf.constant([[1.0, 1.0], [1.0, 1.0]]),
        indices=tf.constant([0, 2]),
        dense_shape=tf.constant([4, 2]))
    optimizer = sgdm.build_sgdm(0.5)

    state = optimizer.initialize(tf.TensorSpec([4, 2]))
    _, weights = optimizer.next(state, weights, gradients)
    self.assertAllClose([[0.5, 0.5], [1.0, 1.0], [0.5, 0.5], [1.0, 1.0]],
                        weights)

  @parameterized.named_parameters(('no_momentum', None), ('momentum_0_5', 0.5))
  def test_convergence(self, momentum):
    init_w, fn, grad_fn = optimizer_test_utils.test_quadratic_problem()
    weights = init_w()
    self.assertGreater(fn(weights), 5.0)

    optimizer = sgdm.build_sgdm(0.1, momentum=momentum)
    state = optimizer.initialize(tf.TensorSpec(weights.shape, weights.dtype))

    for _ in range(100):
      gradients = grad_fn(weights)
      state, weights = optimizer.next(state, weights, gradients)
    self.assertLess(fn(weights), 0.005)

  @parameterized.named_parameters(('lr_0_1_m_none', 0.1, None),
                                  ('lr_0_01_m_0_9', 0.01, 0.9))
  def test_build_sgdm(self, learning_rate, momentum):
    optimizer = sgdm.build_sgdm(learning_rate, momentum)
    self.assertIsInstance(optimizer, optimizer_base.Optimizer)
    self.assertEqual(learning_rate, optimizer._lr)
    self.assertEqual(momentum, optimizer._momentum)

  @parameterized.named_parameters(('lr_0_1_m_0', 0.1, 0.),
                                  ('lr_0_01_m_0_9', 0.01, 0.9))
  def test_match_keras(self, learning_rate, momentum):
    weight_spec = [
        tf.TensorSpec([10, 2], tf.float32),
        tf.TensorSpec([2], tf.float32)
    ]
    steps = 10
    genarator = tf.random.Generator.from_seed(2021)

    def random_vector():
      return [
          genarator.normal(shape=s.shape, dtype=s.dtype) for s in weight_spec
      ]

    intial_weight = random_vector()
    model_variables_fn = lambda: [tf.Variable(v) for v in intial_weight]
    gradients = [random_vector() for _ in range(steps)]
    tff_optimizer_fn = lambda: sgdm.build_sgdm(learning_rate, momentum)

    def keras_optimizer_fn():
      return tf.keras.optimizers.SGD(learning_rate, momentum)

    self.assert_optimizers_numerically_close(model_variables_fn, gradients,
                                             tff_optimizer_fn,
                                             keras_optimizer_fn)

  @parameterized.named_parameters(
      ('negative_lr', -1.0, 0.9, 'learning rate'),
      ('negative_momentum', 1.0, -0.9, 'Momentum'),
      ('momentum_one', 1.0, 1.0, 'Momentum'),
  )
  def test_invalid_args_raises(self, lr, momentum, regex):
    with self.assertRaisesRegex(ValueError, regex):
      sgdm.build_sgdm(lr, momentum)

  def test_weights_gradients_mismatch_raises(self):
    optimizer = sgdm.build_sgdm(0.1)
    state = optimizer.initialize(_SCALAR_SPEC)
    with self.assertRaises(ValueError):
      optimizer.next(state, tf.zeros([1]), tf.zeros([2]))

  def test_initialize_next_weights_mismatch_raises(self):
    optimizer = sgdm.build_sgdm(0.1, momentum=0.9)
    state = optimizer.initialize(_SCALAR_SPEC)
    with self.assertRaises(ValueError):
      optimizer.next(state, tf.zeros([2]), tf.zeros([2]))

  @parameterized.named_parameters(
      ('scalar_spec', _SCALAR_SPEC),
      ('struct_spec', _STRUCT_SPEC),
      ('nested_spec', _NESTED_SPEC),
  )
  def test_get_hparams_returns_expected_result_without_momentum(self, spec):
    optimizer = sgdm.build_sgdm(learning_rate=0.1, momentum=None)
    state = optimizer.initialize(spec)
    expected_hparams = collections.OrderedDict(learning_rate=0.1)
    actual_hparams = optimizer.get_hparams(state)
    self.assertIsInstance(actual_hparams, collections.OrderedDict)
    self.assertEqual(actual_hparams, expected_hparams)

  @parameterized.named_parameters(
      ('scalar_spec', _SCALAR_SPEC),
      ('struct_spec', _STRUCT_SPEC),
      ('nested_spec', _NESTED_SPEC),
  )
  def test_get_hparams_returns_expected_result_with_momentum(self, spec):
    optimizer = sgdm.build_sgdm(learning_rate=0.1, momentum=0.9)
    state = optimizer.initialize(spec)
    expected_hparams = collections.OrderedDict(learning_rate=0.1, momentum=0.9)
    actual_hparams = optimizer.get_hparams(state)
    self.assertIsInstance(actual_hparams, collections.OrderedDict)
    self.assertEqual(actual_hparams, expected_hparams)

  @parameterized.named_parameters(
      ('scalar_spec', _SCALAR_SPEC),
      ('struct_spec', _STRUCT_SPEC),
      ('nested_spec', _NESTED_SPEC),
  )
  def test_set_hparams_returns_expected_result_with_momentum_none(self, spec):
    optimizer = sgdm.build_sgdm(learning_rate=0.1, momentum=None)
    state = optimizer.initialize(spec)
    hparams = collections.OrderedDict(learning_rate=0.5)
    expected_state = copy.deepcopy(state)
    expected_state['learning_rate'] = 0.5
    updated_state = optimizer.set_hparams(state, hparams)
    self.assertIsInstance(updated_state, collections.OrderedDict)
    self.assertEqual(updated_state, expected_state)

  @parameterized.named_parameters(
      ('scalar_spec', _SCALAR_SPEC),
      ('struct_spec', _STRUCT_SPEC),
      ('nested_spec', _NESTED_SPEC),
  )
  def test_set_hparams_returns_expected_result_with_momentum_zero(self, spec):
    optimizer = sgdm.build_sgdm(learning_rate=0.1, momentum=0.0)
    state = optimizer.initialize(spec)
    hparams = collections.OrderedDict(learning_rate=0.5)
    expected_state = copy.deepcopy(state)
    expected_state['learning_rate'] = 0.5
    updated_state = optimizer.set_hparams(state, hparams)
    self.assertIsInstance(updated_state, collections.OrderedDict)
    self.assertEqual(updated_state, expected_state)

  @parameterized.named_parameters(
      ('scalar_spec', _SCALAR_SPEC),
      ('struct_spec', _STRUCT_SPEC),
      ('nested_spec', _NESTED_SPEC),
  )
  def test_set_hparams_returns_expected_result_with_momentum(self, spec):
    optimizer = sgdm.build_sgdm(learning_rate=0.1, momentum=0.9)
    state = optimizer.initialize(spec)
    hparams = collections.OrderedDict(learning_rate=0.5, momentum=0.8)
    expected_state = copy.deepcopy(state)
    for k, v in hparams.items():
      expected_state[k] = v
    updated_state = optimizer.set_hparams(state, hparams)
    self.assertIsInstance(updated_state, collections.OrderedDict)
    self.assertEqual(updated_state, expected_state)

  @parameterized.named_parameters(
      ('scalar_spec', _SCALAR_SPEC),
      ('struct_spec', _STRUCT_SPEC),
      ('nested_spec', _NESTED_SPEC),
  )
  def test_set_get_hparams_is_no_op_without_momentum(self, spec):
    optimizer = sgdm.build_sgdm(learning_rate=0.1, momentum=None)
    state = optimizer.initialize(spec)
    hparams = optimizer.get_hparams(state)
    updated_state = optimizer.set_hparams(state, hparams)
    self.assertEqual(state, updated_state)

  @parameterized.named_parameters(
      ('scalar_spec', _SCALAR_SPEC),
      ('struct_spec', _STRUCT_SPEC),
      ('nested_spec', _NESTED_SPEC),
  )
  def test_set_get_hparams_is_no_op_with_momentum(self, spec):
    optimizer = sgdm.build_sgdm(learning_rate=0.1, momentum=0.9)
    state = optimizer.initialize(spec)
    hparams = optimizer.get_hparams(state)
    updated_state = optimizer.set_hparams(state, hparams)
    self.assertEqual(state, updated_state)

if __name__ == '__main__':
  tf.test.main()


text:
<!doctype html>

Our list is below here

First item

Second item

Third item

Fourth item


text:
#include "palabos2D.h"
#include "palabos2D.hh"
#include <vector>
#include <cmath>
#include <iostream>
#include <fstream>
#include <iomanip>
#include "poiseuille.h"
#include "poiseuille.hh"
#include "cylinder.h"
#include "cylinder.hh"

using namespace plb;
using namespace plb::descriptors;
using namespace std;

typedef double T;
#define DESCRIPTOR D2Q9Descriptor

void defineCylinderGeometry( MultiBlockLattice2D<T,DESCRIPTOR>& lattice,
                             IncomprFlowParam<T> const& parameters )
{
    const plint nx = parameters.getNx();
    const plint ny = parameters.getNy();

    int cx     = nx/4;
    int cy     = ny/2+ny/10;
    int radius = cy/4;

    createCylinder(lattice, cx, cy, radius);
}

void setupInletAndBulk( MultiBlockLattice2D<T,DESCRIPTOR>& lattice,
                        IncomprFlowParam<T> const& parameters,
                        OnLatticeBoundaryCondition2D<T,DESCRIPTOR>& boundaryCondition )
{
    const plint ny = parameters.getNy();

    // Create Velocity boundary conditions on inlet
    boundaryCondition.addVelocityBoundary0N(Box2D(   0,   0,   0,ny-1), lattice);

    setBoundaryVelocity (
            lattice, Box2D(   0,   0,   0,ny-1),
            PoiseuilleVelocity<T>(parameters) );
    initializeAtEquilibrium (
            lattice, lattice.getBoundingBox(),
            PoiseuilleVelocityAndDensity<T,DESCRIPTOR>(parameters) );
}

void copyUnknownOnOutlet( MultiBlockLattice2D<T,DESCRIPTOR>& lattice,
                          IncomprFlowParam<T> const& parameters,
                          OnLatticeBoundaryCondition2D<T,DESCRIPTOR>& boundaryCondition )
{
    const plint nx = parameters.getNx();
    const plint ny = parameters.getNy();

    // On the right boundary, we copy the unknown populations from previous locations
    integrateProcessingFunctional(new CopyUnknownPopulationsFunctional2D<T,DESCRIPTOR, 0, +1>,
                                  Box2D(nx-1,nx-1, 0,ny-1), lattice);
}

void velocityNeumannOutlet( MultiBlockLattice2D<T,DESCRIPTOR>& lattice,
                            IncomprFlowParam<T> const& parameters,
                            OnLatticeBoundaryCondition2D<T,DESCRIPTOR>& boundaryCondition )
{
    const plint nx = parameters.getNx();
    const plint ny = parameters.getNy();

    boundaryCondition.addVelocityBoundary0P (
            Box2D(nx-1,nx-1, 0,ny-1), lattice, boundary::outflow );
}

void writeGifs(MultiBlockLattice2D<T,DESCRIPTOR>& lattice, plint iter)
{
    const plint imSize = 600;

    ImageWriter<T> imageWriter("leeloo");
    imageWriter.writeScaledGif(createFileName("u", iter, 6),
                               *computeVelocityNorm(lattice),
                               imSize, imSize );
}

void writeVTK(MultiBlockLattice2D<T,DESCRIPTOR>& lattice,
              IncomprFlowParam<T> const& parameters, plint iter)
{
    T dx = parameters.getDeltaX();
    T dt = parameters.getDeltaT();
    VtkImageOutput2D<T> vtkOut(createFileName("vtk", iter, 6), dx);
    vtkOut.writeData<float>(*computeVelocityNorm(lattice), "velocityNorm", dx/dt);
    vtkOut.writeData<2,float>(*computeVelocity(lattice), "velocity", dx/dt);
}

int main(int argc, char* argv[]) {
    plbInit(&argc, &argv);

    global::directories().setOutputDir("./tmp/");

    IncomprFlowParam<T> parameters(
            (T) 1e-2,  // uMax
            (T) 300.,  // Re
            100,       // N
            5.,        // lx
            1.         // ly
    );
    const T logT     = (T)0.02;
    const T imSave   = (T)0.1;
    const T vtkSave  = (T)3.;
    const T maxT     = (T)10.1;

    writeLogFile(parameters, "Poiseuille flow");

    MultiBlockLattice2D<T, DESCRIPTOR> lattice (
            parameters.getNx(), parameters.getNy(),
            new BGKdynamics<T,DESCRIPTOR>(parameters.getOmega()) );

    lattice.periodicity().toggle(0, false);

    OnLatticeBoundaryCondition2D<T,DESCRIPTOR>*
        //boundaryCondition = createInterpBoundaryCondition2D<T,DESCRIPTOR>();
        boundaryCondition = createLocalBoundaryCondition2D<T,DESCRIPTOR>();

    defineCylinderGeometry(lattice, parameters);
    setupInletAndBulk(lattice, parameters, *boundaryCondition);
    //copyUnknownOnOutlet(lattice, parameters, *boundaryCondition);
    velocityNeumannOutlet(lattice, parameters, *boundaryCondition);
    lattice.initialize();

    // Main loop over time iterations.
    for (plint iT=0; iT*parameters.getDeltaT()<maxT; ++iT) {
        if ((iT+1)%parameters.nStep(logT)==0) {
            pcout << computeAverageDensity(lattice) << endl;
            pcout << computeAverageEnergy(lattice) << endl;
        }
        if (iT%parameters.nStep(logT)==0) {
            pcout << "step " << iT
                  << "; lattice time=" << lattice.getTimeCounter().getTime()
                  << "; t=" << iT*parameters.getDeltaT()
                  << "; av energy="
                  << setprecision(10) << getStoredAverageEnergy<T>(lattice)
                  << "; av rho="
                  << getStoredAverageDensity<T>(lattice) << endl;
        }

        if (iT%parameters.nStep(imSave)==0) {
            pcout << "Saving Gif ..." << endl;
            writeGifs(lattice, iT);
        }

        if (iT%parameters.nStep(vtkSave)==0 && iT>0) {
            pcout << "Saving VTK file ..." << endl;
            writeVTK(lattice, parameters, iT);
        }

        // Lattice Boltzmann iteration step.
        lattice.collideAndStream();
    }

    delete boundaryCondition;
}


text:
package org.uberfire.ext.wires.core.trees.client.layout.treelayout;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;

import org.uberfire.commons.validation.PortablePreconditions;

/**
 * Implements the actual tree layout algorithm.
 *

 * The nodes with their final layout can be retrieved through
 * {@link #getNodeBounds()}.
 *

 * @param <TreeNode>

 *

 * Adapted from https://code.google.com/p/treelayout/ to be available to GWT clients
 *

 * @author Udo Borkowski (ub@abego.org)
 */
public class TreeLayout<TreeNode> {
    /*
     * Differences between this implementation and original algorithm
	 * --------------------------------------------------------------
	 *
	 * For easier reference the same names (or at least similar names) as in the
	 * paper of Buchheim, Jünger, and Leipert are used in this
	 * implementation. However in the external interface "first" and "last" are
	 * used instead of "left most" and "right most". The implementation also
	 * supports tree layouts with the root at the left (or right) side. In that
	 * case using "left most" would refer to the "top" child, i.e. using "first"
	 * is less confusing.
	 *
	 * Also the y coordinate is not the level but directly refers the y
	 * coordinate of a level, taking node's height and gapBetweenLevels into
	 * account. When the root is at the left or right side the y coordinate
	 * actually becomes an x coordinate.
	 *
	 * Instead of just using a constant "distance" to calculate the position to
	 * the next node we refer to the "size" (width or height) of the node and a
	 * "gapBetweenNodes".
	 */

    // ------------------------------------------------------------------------
    // tree

    private final TreeForTreeLayout<TreeNode> tree;

    /**
     * Returns the Tree the layout is created for.
     */
    public TreeForTreeLayout<TreeNode> getTree() {
        return tree;
    }

    // ------------------------------------------------------------------------
    // nodeExtentProvider

    private final NodeExtentProvider<TreeNode> nodeExtentProvider;

    /**
     * Returns the {@link NodeExtentProvider} used by this {@link TreeLayout}.
     */
    public NodeExtentProvider<TreeNode> getNodeExtentProvider() {
        return nodeExtentProvider;
    }

    private double getNodeHeight( TreeNode node ) {
        return nodeExtentProvider.getHeight( node );
    }

    private double getNodeWidth( TreeNode node ) {
        return nodeExtentProvider.getWidth( node );
    }

    private double getWidthOrHeightOfNode( TreeNode treeNode,
                                           boolean returnWidth ) {
        return returnWidth ? getNodeWidth( treeNode ) : getNodeHeight( treeNode );
    }

    /**
     * When the level changes in Y-axis (i.e. root location Top or Bottom) the
     * height of a node is its thickness, otherwise the node's width is its
     * thickness.
     *

     * The thickness of a node is used when calculating the locations of the
     * levels.
     * @param treeNode
     * @return
     */
    private double getNodeThickness( TreeNode treeNode ) {
        return getWidthOrHeightOfNode( treeNode,
                                       !isLevelChangeInYAxis() );
    }

    /**
     * When the level changes in Y-axis (i.e. root location Top or Bottom) the
     * width of a node is its size, otherwise the node's height is its size.
     *

     * The size of a node is used when calculating the distance between two
     * nodes.
     * @param treeNode
     * @return
     */
    private double getNodeSize( TreeNode treeNode ) {
        return getWidthOrHeightOfNode( treeNode,
                                       isLevelChangeInYAxis() );
    }

    // ------------------------------------------------------------------------
    // configuration

    private final Configuration<TreeNode> configuration;

    /**
     * Returns the Configuration used by this {@link TreeLayout}.
     */
    public Configuration<TreeNode> getConfiguration() {
        return configuration;
    }

    private boolean isLevelChangeInYAxis() {
        Configuration.Location rootLocation = configuration.getRootLocation();
        return rootLocation == Configuration.Location.Top || rootLocation == Configuration.Location.Bottom;
    }

    private int getLevelChangeSign() {
        Configuration.Location rootLocation = configuration.getRootLocation();
        return rootLocation == Configuration.Location.Bottom
                || rootLocation == Configuration.Location.Right ? -1 : 1;
    }

    // ------------------------------------------------------------------------
    // bounds

    private double boundsLeft = Double.MAX_VALUE;
    private double boundsRight = Double.MIN_VALUE;
    private double boundsTop = Double.MAX_VALUE;
    private double boundsBottom = Double.MIN_VALUE;

    private void updateBounds( TreeNode node,
                               double centerX,
                               double centerY ) {
        double width = getNodeWidth( node );
        double height = getNodeHeight( node );
        double left = centerX - width / 2;
        double right = centerX + width / 2;
        double top = centerY - height / 2;
        double bottom = centerY + height / 2;
        if ( boundsLeft > left ) {
            boundsLeft = left;
        }
        if ( boundsRight < right ) {
            boundsRight = right;
        }
        if ( boundsTop > top ) {
            boundsTop = top;
        }
        if ( boundsBottom < bottom ) {
            boundsBottom = bottom;
        }
    }

    /**
     * Returns the bounds of the tree layout.
     *

     * The bounds of a TreeLayout is the smallest rectangle containing the
     * bounds of all nodes in the layout. It always starts at (0,0).
     * @return the bounds of the tree layout
     */
    public Rectangle2D getBounds() {
        return new Rectangle2D( 0,
                                0,
                                boundsRight - boundsLeft,
                                boundsBottom - boundsTop );
    }

    // ------------------------------------------------------------------------
    // size of level

    private final List<Double> sizeOfLevel = new ArrayList<Double>();

    private void calcSizeOfLevels( TreeNode node,
                                   int level ) {
        double oldSize;
        if ( sizeOfLevel.size() <= level ) {
            sizeOfLevel.add( Double.valueOf( 0 ) );
            oldSize = 0;
        } else {
            oldSize = sizeOfLevel.get( level );
        }

        double size = getNodeThickness( node );
        // size = nodeExtentProvider.getHeight(node);
        if ( oldSize < size ) {
            sizeOfLevel.set( level,
                             size );
        }

        if ( !tree.isLeaf( node ) ) {
            for ( TreeNode child : tree.getChildren( node ) ) {
                calcSizeOfLevels( child,
                                  level + 1 );
            }
        }
    }

    /**
     * Returns the number of levels of the tree.
     * @return [level > 0]
     */
    public int getLevelCount() {
        return sizeOfLevel.size();
    }

    /**
     * Returns the size of a level.
     *

     * When the root is located at the top or bottom the size of a level is the
     * maximal height of the nodes of that level. When the root is located at
     * the left or right the size of a level is the maximal width of the nodes
     * of that level.
     * @param level
     * @return the size of the level [level >= 0 && level < levelCount]
     */
    public double getSizeOfLevel( int level ) {
        PortablePreconditions.checkCondition( "level must be >= 0",
                                              level >= 0 );
        PortablePreconditions.checkCondition( "level must be < levelCount",
                                              level < getLevelCount() );

        return sizeOfLevel.get( level );
    }

    // ------------------------------------------------------------------------
    // NormalizedPosition

    /**
     * The algorithm calculates the position starting with the root at 0. I.e.
     * the left children will get negative positions. However we want the result
     * to be normalized to (0,0).
     *

     * {@link NormalizedPosition} will normalize the position (given relative to
     * the root position), taking the current bounds into account. This way the
     * left most node bounds will start at x = 0, the top most node bounds at y
     * = 0.
     */
    private class NormalizedPosition extends Point2D {

        private double x_relativeToRoot;
        private double y_relativeToRoot;

        public NormalizedPosition( double x_relativeToRoot,
                                   double y_relativeToRoot ) {
            setLocation( x_relativeToRoot,
                         y_relativeToRoot );
        }

        @Override
        public double getX() {
            return x_relativeToRoot - boundsLeft;
        }

        @Override
        public double getY() {
            return y_relativeToRoot - boundsTop;
        }

        @Override
        // never called from outside
        public void setLocation( double x_relativeToRoot,
                                 double y_relativeToRoot ) {
            this.x_relativeToRoot = x_relativeToRoot;
            this.y_relativeToRoot = y_relativeToRoot;
        }
    }

    // ------------------------------------------------------------------------
    // The Algorithm

    private final boolean useIdentity;

    private final Map<TreeNode, Double> mod;
    private final Map<TreeNode, TreeNode> thread;
    private final Map<TreeNode, Double> prelim;
    private final Map<TreeNode, Double> change;
    private final Map<TreeNode, Double> shift;
    private final Map<TreeNode, TreeNode> ancestor;
    private final Map<TreeNode, Integer> number;
    private final Map<TreeNode, Point2D> positions;

    private double getMod( TreeNode node ) {
        Double d = mod.get( node );
        return d != null ? d.doubleValue() : 0;
    }

    private void setMod( TreeNode node,
                         double d ) {
        mod.put( node, d );
    }

    private TreeNode getThread( TreeNode node ) {
        TreeNode n = thread.get( node );
        return n != null ? n : null;
    }

    private void setThread( TreeNode node,
                            TreeNode thread ) {
        this.thread.put( node,
                         thread );
    }

    private TreeNode getAncestor( TreeNode node ) {
        TreeNode n = ancestor.get( node );
        return n != null ? n : node;
    }

    private void setAncestor( TreeNode node,
                              TreeNode ancestor ) {
        this.ancestor.put( node,
                           ancestor );
    }

    private double getPrelim( TreeNode node ) {
        Double d = prelim.get( node );
        return d != null ? d.doubleValue() : 0;
    }

    private void setPrelim( TreeNode node,
                            double d ) {
        prelim.put( node, d );
    }

    private double getChange( TreeNode node ) {
        Double d = change.get( node );
        return d != null ? d.doubleValue() : 0;
    }

    private void setChange( TreeNode node,
                            double d ) {
        change.put( node, d );
    }

    private double getShift( TreeNode node ) {
        Double d = shift.get( node );
        return d != null ? d.doubleValue() : 0;
    }

    private void setShift( TreeNode node,
                           double d ) {
        shift.put( node, d );
    }

    /**
     * The distance of two nodes is the distance of the centers of both noded.
     *

     * I.e. the distance includes the gap between the nodes and half of the
     * sizes of the nodes.
     * @param v
     * @param w
     * @return the distance between node v and w
     */
    private double getDistance( TreeNode v,
                                TreeNode w ) {
        double sizeOfNodes = getNodeSize( v ) + getNodeSize( w );

        double distance = sizeOfNodes / 2 + configuration.getGapBetweenNodes( v, w );
        return distance;
    }

    private TreeNode nextLeft( TreeNode v ) {
        return tree.isLeaf( v ) ? getThread( v ) : tree.getFirstChild( v );
    }

    private TreeNode nextRight( TreeNode v ) {
        return tree.isLeaf( v ) ? getThread( v ) : tree.getLastChild( v );
    }

    /**
     * @param node [tree.isChildOfParent(node, parentNode)]
     * @param parentNode parent of node
     * @return
     */
    private int getNumber( TreeNode node,
                           TreeNode parentNode ) {
        Integer n = number.get( node );
        if ( n == null ) {
            int i = 1;
            for ( TreeNode child : tree.getChildren( parentNode ) ) {
                number.put( child, i++ );
            }
            n = number.get( node );
        }

        return n.intValue();
    }

    /**
     * @param vIMinus
     * @param v
     * @param parentOfV
     * @param defaultAncestor
     * @return the greatest distinct ancestor of vIMinus and its right neighbor
     *         v
     */
    private TreeNode ancestor( TreeNode vIMinus,
                               TreeNode v,
                               TreeNode parentOfV,
                               TreeNode defaultAncestor ) {
        TreeNode ancestor = getAncestor( vIMinus );

        // when the ancestor of vIMinus is a sibling of v (i.e. has the same
        // parent as v) it is also the greatest distinct ancestor vIMinus and
        // v. Otherwise it is the defaultAncestor

        return tree.isChildOfParent( ancestor, parentOfV ) ? ancestor : defaultAncestor;
    }

    private void moveSubtree( TreeNode wMinus,
                              TreeNode wPlus,
                              TreeNode parent,
                              double shift ) {

        int subtrees = getNumber( wPlus,
                                  parent ) - getNumber( wMinus,
                                                        parent );
        setChange( wPlus,
                   getChange( wPlus ) - shift / subtrees );
        setShift( wPlus,
                  getShift( wPlus ) + shift );
        setChange( wMinus,
                   getChange( wMinus ) + shift / subtrees );
        setPrelim( wPlus,
                   getPrelim( wPlus ) + shift );
        setMod( wPlus,
                getMod( wPlus ) + shift );
    }

    /**
     * In difference to the original algorithm we also pass in the leftSibling
     * and the parent of v.
     *

     * Why adding the parameter 'parent of v' (parentOfV) ?
     *

     * In this method we need access to the parent of v. Not every tree
     * implementation may support efficient (i.e. constant time) access to it.
     * On the other hand the (only) caller of this method can provide this
     * information with only constant extra time.
     *

     * Also we need access to the "left most sibling" of v. Not every tree
     * implementation may support efficient (i.e. constant time) access to it.
     * On the other hand the "left most sibling" of v is also the "first child"
     * of the parent of v. The first child of a parent node we can get in
     * constant time. As we got the parent of v we can so also get the
     * "left most sibling" of v in constant time.
     *

     * Why adding the parameter 'leftSibling' ?
     *

     * In this method we need access to the "left sibling" of v. Not every tree
     * implementation may support efficient (i.e. constant time) access to it.
     * However it is easy for the caller of this method to provide this
     * information with only constant extra time.
     *

     *

     *

     * In addition these extra parameters avoid the need for
     * {@link TreeForTreeLayout} to include extra methods "getParent",
     * "getLeftSibling", or "getLeftMostSibling". This keeps the interface
     * {@link TreeForTreeLayout} small and avoids redundant implementations.
     * @param v
     * @param defaultAncestor
     * @param leftSibling [nullable] the left sibling v, if there is any
     * @param parentOfV the parent of v
     * @return the (possibly changes) defaultAncestor
     */
    private TreeNode apportion( TreeNode v,
                                TreeNode defaultAncestor,
                                TreeNode leftSibling,
                                TreeNode parentOfV ) {
        TreeNode w = leftSibling;
        if ( w == null ) {
            // v has no left sibling
            return defaultAncestor;
        }
        // v has left sibling w

        // The following variables "v..." are used to traverse the contours to
        // the subtrees. "Minus" refers to the left, "Plus" to the right
        // subtree. "I" refers to the "inside" and "O" to the outside contour.
        TreeNode vOPlus = v;
        TreeNode vIPlus = v;
        TreeNode vIMinus = w;
        // get leftmost sibling of vIPlus, i.e. get the leftmost sibling of
        // v, i.e. the leftmost child of the parent of v (which is passed
        // in)
        TreeNode vOMinus = tree.getFirstChild( parentOfV );

        Double sIPlus = getMod( vIPlus );
        Double sOPlus = getMod( vOPlus );
        Double sIMinus = getMod( vIMinus );
        Double sOMinus = getMod( vOMinus );

        TreeNode nextRightVIMinus = nextRight( vIMinus );
        TreeNode nextLeftVIPlus = nextLeft( vIPlus );

        while ( nextRightVIMinus != null && nextLeftVIPlus != null ) {
            vIMinus = nextRightVIMinus;
            vIPlus = nextLeftVIPlus;
            vOMinus = nextLeft( vOMinus );
            vOPlus = nextRight( vOPlus );
            setAncestor( vOPlus, v );
            double shift = ( getPrelim( vIMinus ) + sIMinus )
                    - ( getPrelim( vIPlus ) + sIPlus )
                    + getDistance( vIMinus, vIPlus );

            if ( shift > 0 ) {
                moveSubtree( ancestor( vIMinus, v,
                                       parentOfV,
                                       defaultAncestor ),
                             v,
                             parentOfV,
                             shift );
                sIPlus = sIPlus + shift;
                sOPlus = sOPlus + shift;
            }
            sIMinus = sIMinus + getMod( vIMinus );
            sIPlus = sIPlus + getMod( vIPlus );
            sOMinus = sOMinus + getMod( vOMinus );
            sOPlus = sOPlus + getMod( vOPlus );

            nextRightVIMinus = nextRight( vIMinus );
            nextLeftVIPlus = nextLeft( vIPlus );
        }

        if ( nextRightVIMinus != null && nextRight( vOPlus ) == null ) {
            setThread( vOPlus, nextRightVIMinus );
            setMod( vOPlus, getMod( vOPlus ) + sIMinus - sOPlus );
        }

        if ( nextLeftVIPlus != null && nextLeft( vOMinus ) == null ) {
            setThread( vOMinus,
                       nextLeftVIPlus );
            setMod( vOMinus,
                    getMod( vOMinus ) + sIPlus - sOMinus );
            defaultAncestor = v;
        }
        return defaultAncestor;
    }

    /**
     * @param v [!tree.isLeaf(v)]
     */
    private void executeShifts( TreeNode v ) {
        double shift = 0;
        double change = 0;
        for ( TreeNode w : tree.getChildrenReverse( v ) ) {
            change = change + getChange( w );
            setPrelim( w,
                       getPrelim( w ) + shift );
            setMod( w,
                    getMod( w ) + shift );
            shift = shift + getShift( w ) + change;
        }
    }

    /**
     * In difference to the original algorithm we also pass in the leftSibling
     * (see {@link #apportion(Object, Object, Object, Object)} for a
     * motivation).
     * @param v
     * @param leftSibling [nullable] the left sibling v, if there is any
     */
    private void firstWalk( TreeNode v,
                            TreeNode leftSibling ) {
        if ( tree.isLeaf( v ) ) {
            // No need to set prelim(v) to 0 as the getter takes care of this.

            TreeNode w = leftSibling;
            if ( w != null ) {
                // v has left sibling

                setPrelim( v,
                           getPrelim( w ) + getDistance( v,
                                                         w ) );
            }

        } else {
            // v is not a leaf

            TreeNode defaultAncestor = tree.getFirstChild( v );
            TreeNode previousChild = null;
            for ( TreeNode w : tree.getChildren( v ) ) {
                firstWalk( w, previousChild );
                defaultAncestor = apportion( w,
                                             defaultAncestor,
                                             previousChild,
                                             v );
                previousChild = w;
            }
            executeShifts( v );
            double midpoint = ( getPrelim( tree.getFirstChild( v ) ) + getPrelim( tree.getLastChild( v ) ) ) / 2.0;
            TreeNode w = leftSibling;
            if ( w != null ) {
                // v has left sibling

                setPrelim( v,
                           getPrelim( w ) + getDistance( v,
                                                         w ) );
                setMod( v,
                        getPrelim( v ) - midpoint );

            } else {
                // v has no left sibling

                setPrelim( v,
                           midpoint );
            }
        }
    }

    /**
     * In difference to the original algorithm we also pass in extra level
     * information.
     * @param v
     * @param m
     * @param level
     * @param levelStart
     */
    private void secondWalk( TreeNode v,
                             double m,
                             int level,
                             double levelStart ) {
        // construct the position from the prelim and the level information

        // The rootLocation affects the way how x and y are changed and in what
        // direction.
        double levelChangeSign = getLevelChangeSign();
        boolean levelChangeOnYAxis = isLevelChangeInYAxis();
        double levelSize = getSizeOfLevel( level );

        double x = getPrelim( v ) + m;

        double y;
        Configuration.AlignmentInLevel alignment = configuration.getAlignmentInLevel();
        if ( alignment == Configuration.AlignmentInLevel.Center ) {
            y = levelStart + levelChangeSign * ( levelSize / 2 );
        } else if ( alignment == Configuration.AlignmentInLevel.TowardsRoot ) {
            y = levelStart + levelChangeSign * ( getNodeThickness( v ) / 2 );
        } else {
            y = levelStart + levelSize - levelChangeSign * ( getNodeThickness( v ) / 2 );
        }

        if ( !levelChangeOnYAxis ) {
            double t = x;
            x = y;
            y = t;
        }

        positions.put( v,
                       new NormalizedPosition( x,
                                               y ) );

        // update the bounds
        updateBounds( v,
                      x,
                      y );

        // recurse
        if ( !tree.isLeaf( v ) ) {
            double nextLevelStart = levelStart
                    + ( levelSize + configuration.getGapBetweenLevels( level + 1 ) )
                    * levelChangeSign;
            for ( TreeNode w : tree.getChildren( v ) ) {
                secondWalk( w,
                            m + getMod( v ),
                            level + 1,
                            nextLevelStart );
            }
        }
    }

    // ------------------------------------------------------------------------
    // nodeBounds

    private Map<TreeNode, Rectangle2D> nodeBounds;

    /**
     * Returns the layout of the tree nodes by mapping each node of the tree to
     * its bounds (position and size).
     *

     * For each rectangle x and y will be >= 0. At least one rectangle will have
     * an x == 0 and at least one rectangle will have an y == 0.
     * @return maps each node of the tree to its bounds (position and size).
     */
    public Map<TreeNode, Rectangle2D> getNodeBounds() {
        if ( nodeBounds == null ) {
            nodeBounds = this.useIdentity ? new IdentityHashMap<TreeNode, Rectangle2D>()
                    : new HashMap<TreeNode, Rectangle2D>();
            for ( Map.Entry<TreeNode, Point2D> entry : positions.entrySet() ) {
                TreeNode node = entry.getKey();
                Point2D pos = entry.getValue();
                double w = getNodeWidth( node );
                double h = getNodeHeight( node );
                double x = pos.getX() - w / 2;
                double y = pos.getY() - h / 2;
                nodeBounds.put( node, new Rectangle2D( x,
                                                       y,
                                                       w,
                                                       h ) );
            }
        }
        return nodeBounds;
    }

    // ------------------------------------------------------------------------
    // constructor

    /**
     * Creates a TreeLayout for a given tree.
     *

     * In addition to the tree the {@link NodeExtentProvider} and the
     * {@link Configuration} must be given.
     * @param useIdentity [default: false] when true, identity ("==") is used instead of
     * equality ("equals(...)") when checking nodes. Within a tree
     * each node must only be once (using this check).
     */
    public TreeLayout( TreeForTreeLayout<TreeNode> tree,
                       NodeExtentProvider<TreeNode> nodeExtentProvider,
                       Configuration<TreeNode> configuration,
                       boolean useIdentity ) {
        this.tree = tree;
        this.nodeExtentProvider = nodeExtentProvider;
        this.configuration = configuration;
        this.useIdentity = useIdentity;

        if ( this.useIdentity ) {
            this.mod = new IdentityHashMap<TreeNode, Double>();
            this.thread = new IdentityHashMap<TreeNode, TreeNode>();
            this.prelim = new IdentityHashMap<TreeNode, Double>();
            this.change = new IdentityHashMap<TreeNode, Double>();
            this.shift = new IdentityHashMap<TreeNode, Double>();
            this.ancestor = new IdentityHashMap<TreeNode, TreeNode>();
            this.number = new IdentityHashMap<TreeNode, Integer>();
            this.positions = new IdentityHashMap<TreeNode, Point2D>();
        } else {
            this.mod = new HashMap<TreeNode, Double>();
            this.thread = new HashMap<TreeNode, TreeNode>();
            this.prelim = new HashMap<TreeNode, Double>();
            this.change = new HashMap<TreeNode, Double>();
            this.shift = new HashMap<TreeNode, Double>();
            this.ancestor = new HashMap<TreeNode, TreeNode>();
            this.number = new HashMap<TreeNode, Integer>();
            this.positions = new HashMap<TreeNode, Point2D>();
        }

        // No need to explicitly set mod, thread and ancestor as their getters
        // are taking care of the initial values. This avoids a full tree walk
        // through and saves some memory as no entries are added for
        // "initial values".

        TreeNode r = tree.getRoot();
        firstWalk( r,
                   null );
        calcSizeOfLevels( r,
                          0 );
        secondWalk( r,
                    -getPrelim( r ),
                    0,
                    0 );
    }

    public TreeLayout( TreeForTreeLayout<TreeNode> tree,
                       NodeExtentProvider<TreeNode> nodeExtentProvider,
                       Configuration<TreeNode> configuration ) {
        this( tree, nodeExtentProvider, configuration, false );
    }

    // ------------------------------------------------------------------------
    // checkTree

    private void addUniqueNodes( Map<TreeNode, TreeNode> nodes,
                                 TreeNode newNode ) {
        if ( nodes.put( newNode,
                        newNode ) != null ) {
            throw new RuntimeException( "Node used more than once in tree: " + newNode );
        }
        for ( TreeNode n : tree.getChildren( newNode ) ) {
            addUniqueNodes( nodes,
                            n );
        }
    }

    /**
     * Check if the tree is a "valid" tree.
     *

     * Typically you will use this method during development when you get an
     * unexpected layout from your trees.
     *

     * The following checks are performed:
     *

     *
Each node must only occur once in the tree.

     *

     */
    public void checkTree() {
        Map<TreeNode, TreeNode> nodes = this.useIdentity ? new IdentityHashMap<TreeNode, TreeNode>()
                : new HashMap<TreeNode, TreeNode>();

        // Traverse the tree and check if each node is only used once.
        addUniqueNodes( nodes,
                        tree.getRoot() );
    }

}


text:
package io.airlift.slice;

import javax.annotation.Nullable;

import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * An OutputStream that counts the number of bytes written.
 *
 * @author Chris Nokleberg
 */
final class CountingOutputStream
        extends FilterOutputStream
{
    private long count;

    /**
     * Wraps another output stream, counting the number of bytes written.
     *
     * @param out the output stream to be wrapped
     */
    public CountingOutputStream(@Nullable OutputStream out)
    {
        super(out);
    }

    /**
     * Returns the number of bytes written.
     */
    public long getCount()
    {
        return count;
    }

    @Override
    public void write(byte[] b, int off, int len)
            throws IOException
    {
        out.write(b, off, len);
        count += len;
    }

    @Override
    public void write(int b)
            throws IOException
    {
        out.write(b);
        count++;
    }
}


text:
namespace gecko
{
	namespace core
	{
		namespace exceptions
		{
			class format_exception : public virtual exception
			{
			public:
				format_exception()
				{
				}

				format_exception(const char* message) : exception(message)
				{
				}

				format_exception(const std::string message) : exception(message)
				{
				}

				virtual const char* what() const noexcept override
				{
					return "gecko::core::exceptions::format_exception";
				}
			};
		} //namespace exceptions
	} //namespace core
} //namespace gecko

#endif //__core_exceptions_format_exception_h__


text:
package org.knowm.xchange.bibox.dto.account;

import com.fasterxml.jackson.annotation.JsonProperty;
import java.math.BigDecimal;
import java.util.Date;
import org.knowm.xchange.bibox.dto.BiboxAdapters;

public class BiboxWithdrawal {

  public final long userId;
  public final long coinId;
  public final String toAddress;
  public final String coinSymbol;
  public final BigDecimal amountReal;
  public final BigDecimal amount;
  private final Date updatedAt;
  private final Date createdAt;
  public final String url;
  public final String iconUrl;
  public final int status;

  public BiboxWithdrawal(
      @JsonProperty("user_id") long userId,
      @JsonProperty("coin_id") long coinId,
      @JsonProperty("to_address") String toAddress,
      @JsonProperty("coin_symbol") String coinSymbol,
      @JsonProperty("amount_real") BigDecimal amountReal,
      @JsonProperty("amount") BigDecimal amount,
      @JsonProperty("updatedAt") String updatedAt,
      @JsonProperty("createdAt") String createdAt,
      @JsonProperty("url") String url,
      @JsonProperty("icon_url") String iconUrl,
      @JsonProperty("status") int status) {
    this.userId = userId;
    this.coinId = coinId;
    this.toAddress = toAddress;
    this.coinSymbol = coinSymbol;
    this.amountReal = amountReal;
    this.amount = amount;
    this.updatedAt = BiboxAdapters.convert(updatedAt);
    this.createdAt = BiboxAdapters.convert(createdAt);
    this.url = url;
    this.iconUrl = iconUrl;
    this.status = status;
  }

  public Date getUpdatedAt() {
    return new Date(updatedAt.getTime());
  }

  public Date getCreatedAt() {
    return new Date(createdAt.getTime());
  }
}


text: module.exports = 'a sub';


text:
package org.usfirst.frc.team4915.stronghold.commands;

import org.usfirst.frc.team4915.stronghold.Robot;
import org.usfirst.frc.team4915.stronghold.subsystems.Portcullis;

import edu.wpi.first.wpilibj.command.Command;

/**
 *
 */
public class PortcullisMoveDownRight extends Command {

    public PortcullisMoveDownRight() {
        // Use requires() here to declare subsystem dependencies
        // eg. requires(chassis);
   //     requires(Robot.portcullis);
    }

    // Called just before this Command runs the first time
    protected void initialize() {
    }

    // Called repeatedly when this Command is scheduled to run
    protected void execute() {
        Robot.portcullis.PortcullisMoveDown(true); //right is true and left is false
    }

    // Make this return true when this Command no longer needs to run execute()
    protected boolean isFinished() {
        return Robot.portcullis.isRightPortcullisAtBottom();
    }

    // Called once after isFinished returns true
    protected void end() {
        Robot.portcullis.stopRightMotor();
    }

    // Called when another command which requires one or more of the same
    // subsystems is scheduled to run
    protected void interrupted() {
        System.out.println("PortcullisMoveDownRight interrupted");
        end();
    }
}


text:
package net.dougqh.jak.jvm.operations;

import java.lang.reflect.Type;

import net.dougqh.jak.jvm.JvmOperationProcessor;
import net.dougqh.jak.jvm.JvmOperationProcessor.Jump;
import net.dougqh.jak.types.Reference;

public final class if_acmpne extends IfComparisonOperation {
	public static final String ID = "if_acmpne";
	public static final byte CODE = IF_ACMPNE;

	public static final if_acmpne prototype() {
		return new if_acmpne( new JumpPrototype() );
	}

	public if_acmpne( final Jump jump ) {
		super(jump);
	}

	@Override
	public final String getId() {
		return ID;
	}

	@Override
	public final int getCode() {
		return CODE;
	}

	@Override
	public final Type lhsType() {
		return Reference.class;
	}

	@Override
	public final Type rhsType() {
		return Reference.class;
	}

	@Override
	public final void process( final JvmOperationProcessor processor ) {
		processor.if_acmpne(this.jump());
	}
}


text:
namespace Engin
{
	namespace Renderer
	{
		// Represents a single vertex of a triangle.

		struct Vertex
		{
			glm::vec3 position;
			glm::vec4 color;

			Vertex() : position(0.0f), color(0.0f) {}
			Vertex(const glm::vec3& position, const glm::vec4& color) : position(position), color(color) {}
			Vertex(Vertex&& other)
			{
				position = std::move(other.position); color = std::move(other.color);
			}
		};

		// Simple batch renderer for triangles.

		class Batch
		{
		public:
			Batch();
			~Batch();

			void init(Resources::ShaderProgram* shader, size_t maxVertices = defaultBatchSize);

			void draw(const std::vector<Vertex>& vertices);
			void drawTriangle(GLfloat x1, GLfloat y1, GLfloat x2, GLfloat y2, GLfloat x3, GLfloat y3, const Color& color, GLfloat opacity = 1.0f, GLfloat depth = 0.0f);
			void drawQuad(GLfloat x, GLfloat y, GLfloat width, GLfloat height, const Color& color, GLfloat opacity = 1.0f, GLfloat depth = 0.0f);
			void flush(const Camera& camera);

			void clear()
			{
				currentVertex = 0;
			}

		private:
			std::vector<Vertex> vertices;

			static const size_t defaultBatchSize = 2048;

			GLuint VBO;
			GLuint currentVertex;

			Resources::ShaderProgram* shader;
		};
	}
}


text:
using SignalR.Dynamic.API.Common;
using System;
using System.CodeDom;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace SignalR.Dynamic.API.Interfaces
{
    public interface IHubCodeGenerator
    {
        CodeCompileUnit GenerateCodeDOM(string hubName, params string[] authorizationRoles);
    }
}


text:
package junior.contactlist;

import junior.contactlist.controller.ConsoleController;
import junior.contactlist.controller.ContactListController;

public class App {

    public static void main(String[] args) {
        ContactListController controller = new ConsoleController();
        controller.run();
    }

}


text:
package tomy.list;

import org.testng.log4testng.Logger;

public class ListPrint {
  private static final Logger LOGGER = Logger.getLogger(ListPrint.class);
  public static final String VALUE_FORMAT = "%d";

  public static void print(SList<?> list) {
    LOGGER.debug(toString(list));
  }

  public static String toString(SList<?> list) {
    StringBuilder result = new StringBuilder();
    boolean first = false;
    for (;list != null; list = list.n) {
      if (!first) {
        result.append(" ");
      }
      result.append(list.toString());
      first = true;
    }

    return result.toString();
  }

  public static String toString(DList<?> list) {
    StringBuilder result = new StringBuilder();
    boolean first = true;
    DList head = null;
    for (;list != null && list != head; list = list.n) {
      if (first) {
        head = list;
        first = false;
      } else {
        result.append(" ");
      }
      result.append(list.toString());
    }

    return result.toString();
  }
}


text:
layout: page
title: "Dummy"
quote: 'Let Alexa ask Jeopardy questions.'
---

Something here

Stay tuned for more content.

Contact Us


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>
  Class: OmgValidator::Validators::EmailValidator

    — Documentation by YARD 0.8.2.1

</title>

  <link rel="stylesheet" href="../../css/style.css" type="text/css" media="screen" charset="utf-8" />

  <link rel="stylesheet" href="../../css/common.css" type="text/css" media="screen" charset="utf-8" />

    Index (E) »
    OmgValidator » Validators
     »
    EmailValidator

(no frames)

      Class List

      Method List

      File List

Class: OmgValidator::Validators::EmailValidator

Inherits:

      ActiveModel::EachValidator

Object

ActiveModel::EachValidator

OmgValidator::Validators::EmailValidator

        show all

Defined in:

lib/omg_validator/validators/email_validator.rb

Overview

Checks whether input is a valid email address

Matches:

email@domain.com, my_user@domain.edu.org, sub.domain@ohyeah.com

Does not match:

mail@you@rock.com, domain.com

Examples:

validates :email, email: true

      Instance Method Summary
      (collapse)

      - (Object) validate_each(record, attribute, value)

Instance Method Details

    - (<tt>Object</tt>) validate_each(record, attribute, value)

14
15
16
17
18
19
20

# File 'lib/omg_validator/validators/email_validator.rb', line 14

def validate_each(record, attribute, value)
  return nil if value.blank?
  reg = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]+$/
  unless reg.match(value)
    record.errors[attribute] = "must be a valid email address"
  end
end

  Generated on Sun Sep 23 13:47:01 2012 by
  yard
  0.8.2.1 (ruby-1.9.3).


text:
function CaseCallbacks() {
};

module.exports = CaseCallbacks;


text:
<?php

class Ess_M2ePro_Model_Ebay_Connector_OrderItem_Add_Dispute
    extends Ess_M2ePro_Model_Ebay_Connector_Command_RealTime
{
    // M2ePro_TRANSLATIONS
    // Dispute cannot be opened. Reason: Dispute explanation is not defined.
    // Dispute cannot be opened. Reason: Dispute reason is not defined.
    // Unpaid Item Process was not open for Item #%id%. Reason: %msg%
    // Unpaid Item Process was not open for Item #%id%. Reason: eBay failure. Please try again later.
    // Unpaid Item Process for Item #%id% has been initiated.

    const DISPUTE_EXPLANATION_BUYER_HAS_NOT_PAID = 'BuyerNotPaid';

    /** @var $_orderItem Ess_M2ePro_Model_Order_Item */
    protected $_orderItem;

    // ########################################

    public function setOrderItem(Ess_M2ePro_Model_Order_Item $orderItem)
    {
        $this->_orderItem = $orderItem;
        $this->_account   = $orderItem->getOrder()->getAccount();

        return $this;
    }

    // ########################################

    protected function getCommand()
    {
        return array('dispute', 'add', 'entity');
    }

    protected function isNeedSendRequest()
    {
        if (empty($this->_params['explanation'])) {
            $this->_orderItem->getOrder()->addErrorLog(
                'Dispute cannot be opened. Reason: Dispute explanation is not defined.'
            );

            return false;
        }

        if (empty($this->_params['reason'])) {
            $this->_orderItem->getOrder()->addErrorLog(
                'Dispute cannot be opened. Reason: Dispute reason is not defined.'
            );

            return false;
        }

        return true;
    }

    public function getRequestData()
    {
        $requestData = array(
            'item_id'        => $this->_orderItem->getChildObject()->getItemId(),
            'transaction_id' => $this->_orderItem->getChildObject()->getTransactionId(),
            'explanation'    => $this->_params['explanation'],
            'reason'         => $this->_params['reason']
        );

        return $requestData;
    }

    protected function validateResponse()
    {
        return true;
    }

    public function process()
    {
        if (!$this->isNeedSendRequest()) {
            return;
        }

        parent::process();

        foreach ($this->getResponse()->getMessages()->getEntities() as $message) {
            if (!$message->isError()) {
                continue;
            }

            $this->_orderItem->getOrder()->addErrorLog(
                'Unpaid Item Process was not open for Item #%id%. Reason: %msg%', array(
                    '!id' => $this->_orderItem->getChildObject()->getItemId(),
                    'msg' => $message->getText()
                )
            );

            if ((in_array($message->getCode(), array(16207, 16212)))) {
                $this->_orderItem->setData(
                    'unpaid_item_process_state', Ess_M2ePro_Model_Ebay_Order_Item::UNPAID_ITEM_PROCESS_OPENED
                );
                $this->_orderItem->save();
            }
        }

        return;
    }

    protected function prepareResponseData()
    {
        if ($this->getResponse()->isResultError()) {
            return;
        }

        $responseData = $this->getResponse()->getData();

        if (empty($responseData['dispute_id'])) {
            $log = 'Unpaid Item Process was not open for Item #%id%. Reason: eBay failure. Please try again later.';
            $this->_orderItem->getOrder()->addErrorLog(
                $log, array(
                '!id' => $this->_orderItem->getChildObject()->getItemId()
                )
            );
            return;
        }

        $this->_orderItem->setData(
            'unpaid_item_process_state', Ess_M2ePro_Model_Ebay_Order_Item::UNPAID_ITEM_PROCESS_OPENED
        );
        $this->_orderItem->save();

        $this->_orderItem->getOrder()->addSuccessLog(
            'Unpaid Item Process for Item #%id% has been initiated.', array(
            '!id' => $this->_orderItem->getChildObject()->getItemId()
            )
        );
    }

    // ########################################
}


text:
import os
from setuptools import find_packages
from setuptools import setup

setup(
    name='AoikI18n',

    version='0.1.0',

    description="""A simple I18n solution featuring fallback locale, YAML locale file, synonym locale file, and flexible locale file path.""",

    long_description="""`Documentation on Github
<https://github.com/AoiKuiyuyou/AoikI18n>`_""",

    url='https://github.com/AoiKuiyuyou/AoikI18n',

    author='Aoi.Kuiyuyou',

    author_email='aoi.kuiyuyou@google.com',

    license='MIT',

    classifiers=[
        'Development Status :: 3 - Alpha',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Operating System :: OS Independent',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.6',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.1',
        'Programming Language :: Python :: 3.2',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4',
    ],

    keywords='i18n locale fallback yaml synonym flexible file path',

    install_requires=[
        'pyyaml',
    ],

    package_dir={'':'src'},

    packages=find_packages('src'),
)


text:
package account

import (
	"github.com/smolgu/lib/models"
	"github.com/smolgu/lib/modules/middleware"
)

func Dashboard(ctx *middleware.Context) {
	if ctx.Req.Method == "POST" {
		// shortcut
		g := func(name string) string {
			return ctx.Req.FormValue(name)
		}

		u := ctx.User

		u.FirstName = g("first_name")
		u.LastName = g("last_name")
		u.Patronymic = g("patronymic")

		u.Email = g("email")

		/*data*/
		u.Data["Faculty"] = g("fac")
		u.Data["TrainingDirection"] = g("train")

		pass := g("password")
		if pass != "" {
			e := u.SetPassword(pass)
			if e != nil {
				ctx.Flash.Error(e.Error())
				ctx.Redirect(ctx.Req.RequestURI)
				return
			}
		}

		e := models.SaveUser(u)
		if e != nil {
			ctx.Flash.Error(e.Error())
			ctx.Redirect(ctx.Req.RequestURI)
			return
		}

		ctx.Flash.Success("Данные сохранены")
		ctx.Redirect(ctx.Req.RequestURI)
	}
	ctx.HTML(200, "dashboard")
}