text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

#include <stdlib.h>
#ifdef _CRTDBG_MAP_ALLOC
#include <crtdbg.h>
#endif
#include <string.h>
#include "azure_c_shared_utility/gballoc.h"
#include "azure_c_shared_utility/string_tokenizer.h"
#include "azure_c_shared_utility/doublylinkedlist.h"
#include "azure_c_shared_utility/iot_logging.h"
#include "azure_c_shared_utility/tickcounter.h"

#include "iothub_client_ll.h"
#include "iothub_client_private.h"
#include "iothub_client_version.h"
#include "iothub_transport_ll.h"

#define LOG_ERROR LogError("result = %s\r\n", ENUM_TO_STRING(IOTHUB_CLIENT_RESULT, result));
#define INDEFINITE_TIME ((time_t)(-1))

DEFINE_ENUM_STRINGS(IOTHUB_CLIENT_RESULT, IOTHUB_CLIENT_RESULT_VALUES);

typedef struct IOTHUB_CLIENT_LL_HANDLE_DATA_TAG
{
    DLIST_ENTRY waitingToSend;
    TRANSPORT_LL_HANDLE transportHandle;
	bool isSharedTransport;
	IOTHUB_DEVICE_HANDLE deviceHandle;
    TRANSPORT_PROVIDER_FIELDS;
    IOTHUB_CLIENT_MESSAGE_CALLBACK_ASYNC messageCallback;
    void* messageUserContextCallback;
    time_t lastMessageReceiveTime;
    TICK_COUNTER_HANDLE tickCounter; /*shared tickcounter used to track message timeouts in waitingToSend list*/
    uint64_t currentMessageTimeout;
}IOTHUB_CLIENT_LL_HANDLE_DATA;

static const char HOSTNAME_TOKEN[] = "HostName";
static const char DEVICEID_TOKEN[] = "DeviceId";
static const char DEVICEKEY_TOKEN[] = "SharedAccessKey";
static const char PROTOCOL_GATEWAY_HOST[] = "GatewayHostName";

IOTHUB_CLIENT_LL_HANDLE IoTHubClient_LL_CreateFromConnectionString(const char* connectionString, IOTHUB_CLIENT_TRANSPORT_PROVIDER protocol)
{
    IOTHUB_CLIENT_LL_HANDLE result = NULL;

    /*Codes_SRS_IOTHUBCLIENT_LL_05_001: [IoTHubClient_LL_CreateFromConnectionString shall obtain the version string by a call to IoTHubClient_GetVersionString.]*/
    /*Codes_SRS_IOTHUBCLIENT_LL_05_002: [IoTHubClient_LL_CreateFromConnectionString shall print the version string to standard output.]*/
    LogInfo("IoT Hub SDK for C, version %s\r\n", IoTHubClient_GetVersionString());

    /* SRS_IOTHUBCLIENT_LL_12_003: [IoTHubClient_LL_CreateFromConnectionString shall verify the input parameter and if it is NULL then return NULL] */
    if (connectionString == NULL)
    {
        LogError("Input parameter is NULL: connectionString\r\n");
    }
    else if (protocol == NULL)
    {
        LogError("Input parameter is NULL: protocol\r\n");
    }
    else
    {
        /* SRS_IOTHUBCLIENT_LL_12_004: [IoTHubClient_LL_CreateFromConnectionString shall allocate IOTHUB_CLIENT_CONFIG structure] */
        IOTHUB_CLIENT_CONFIG* config = malloc(sizeof(IOTHUB_CLIENT_CONFIG));
        if (config == NULL)
        {
            /* SRS_IOTHUBCLIENT_LL_12_012: [If the allocation failed IoTHubClient_LL_CreateFromConnectionString  returns NULL]  */
            LogError("Malloc failed\r\n");
            return NULL;
        }
        else
        {
            STRING_TOKENIZER_HANDLE tokenizer1 = NULL;
            STRING_HANDLE connString = NULL;
            STRING_HANDLE tokenString = NULL;
            STRING_HANDLE valueString = NULL;
            STRING_HANDLE hostNameString = NULL;
            STRING_HANDLE hostSuffixString = NULL;
            STRING_HANDLE deviceIdString = NULL;
            STRING_HANDLE deviceKeyString = NULL;
            STRING_HANDLE protocolGateway = NULL;

            config->protocol = protocol;

            config->iotHubName = NULL;
            config->iotHubSuffix = NULL;
            config->deviceId = NULL;
            config->deviceKey = NULL;
            /* Codes_SRS_IOTHUBCLIENT_LL_04_002: [If it does not, it shall pass the protocolGatewayHostName NULL.] */
            config->protocolGatewayHostName = NULL;

            if ((connString = STRING_construct(connectionString)) == NULL)
            {
                LogError("Error constructing connectiong String\r\n");
            }
            else if ((tokenizer1 = STRING_TOKENIZER_create(connString)) == NULL)
            {
                LogError("Error creating Tokenizer\r\n");
            }
            else if ((tokenString = STRING_new()) == NULL)
            {
                LogError("Error creating Token String\r\n");
            }
            else if ((valueString = STRING_new()) == NULL)
            {
                LogError("Error creating Value String\r\n");
            }
            else if ((hostNameString = STRING_new()) == NULL)
            {
                LogError("Error creating HostName String\r\n");
            }
            else if ((hostSuffixString = STRING_new()) == NULL)
            {
                LogError("Error creating HostSuffix String\r\n");
            }
            /* SRS_IOTHUBCLIENT_LL_12_005: [IoTHubClient_LL_CreateFromConnectionString shall try to parse the connectionString input parameter for the following structure: "Key1=value1;key2=value2;key3=value3..."] */
            /* SRS_IOTHUBCLIENT_LL_12_006: [IoTHubClient_LL_CreateFromConnectionString shall verify the existence of the following Key/Value pairs in the connection string: HostName, DeviceId, SharedAccessKey.]  */
            else
            {
                while ((STRING_TOKENIZER_get_next_token(tokenizer1, tokenString, "=") == 0))
                {
                    if (STRING_TOKENIZER_get_next_token(tokenizer1, valueString, ";") != 0)
                    {
                        LogError("Tokenizer error\r\n");
                        break;
                    }
                    else
                    {
                        if (tokenString != NULL)
                        {
                            /* SRS_IOTHUBCLIENT_LL_12_010: [IoTHubClient_LL_CreateFromConnectionString shall fill up the IOTHUB_CLIENT_CONFIG structure using the following mapping: iotHubName = Name, iotHubSuffix = Suffix, deviceId = DeviceId, deviceKey = SharedAccessKey] */
                            const char* s_token = STRING_c_str(tokenString);
                            if (strcmp(s_token, HOSTNAME_TOKEN) == 0)
                            {
                                /* SRS_IOTHUBCLIENT_LL_12_009: [IoTHubClient_LL_CreateFromConnectionString shall split the value of HostName to Name and Suffix using the first "." as a separator] */
                                STRING_TOKENIZER_HANDLE tokenizer2 = NULL;
                                if ((tokenizer2 = STRING_TOKENIZER_create(valueString)) == NULL)
                                {
                                    LogError("Error creating Tokenizer\r\n");
                                    break;
                                }
                                else
                                {
                                    /* SRS_IOTHUBCLIENT_LL_12_015: [If the string split failed, IoTHubClient_LL_CreateFromConnectionString returns NULL ] */
                                    if (STRING_TOKENIZER_get_next_token(tokenizer2, hostNameString, ".") != 0)
                                    {
                                        LogError("Tokenizer error\r\n");
                                        STRING_TOKENIZER_destroy(tokenizer2);
                                        break;
                                    }
                                    else
                                    {
                                        config->iotHubName = STRING_c_str(hostNameString);
                                        if (STRING_TOKENIZER_get_next_token(tokenizer2, hostSuffixString, ";") != 0)
                                        {
                                            LogError("Tokenizer error\r\n");
                                            STRING_TOKENIZER_destroy(tokenizer2);
                                            break;
                                        }
                                        else
                                        {
                                            config->iotHubSuffix = STRING_c_str(hostSuffixString);
                                        }
                                    }
                                    STRING_TOKENIZER_destroy(tokenizer2);
                                }
                            }
                            else if (strcmp(s_token, DEVICEID_TOKEN) == 0)
                            {
                                deviceIdString = STRING_clone(valueString);
                                if (deviceIdString != NULL)
                                {
                                    config->deviceId = STRING_c_str(deviceIdString);
                                }
                            }
                            else if (strcmp(s_token, DEVICEKEY_TOKEN) == 0)
                            {
                                deviceKeyString = STRING_clone(valueString);
                                if (deviceKeyString != NULL)
                                {
                                    config->deviceKey = STRING_c_str(deviceKeyString);
                                }
                            }
                            /* Codes_SRS_IOTHUBCLIENT_LL_04_001: [IoTHubClient_LL_CreateFromConnectionString shall verify the existence of key/value pair GatewayHostName. If it does exist it shall pass the value to IoTHubClient_LL_Create API.] */
                            else if (strcmp(s_token, PROTOCOL_GATEWAY_HOST) == 0)
                            {
                                protocolGateway = STRING_clone(valueString);
                                if (protocolGateway != NULL)
                                {
                                    config->protocolGatewayHostName = STRING_c_str(protocolGateway);
                                }
                            }
                        }
                    }
                }
                /* parsing is done - check the result */
                if (config->iotHubName == NULL)
                {
                    LogError("iotHubName is not found\r\n");
                }
                else if (config->iotHubSuffix == NULL)
                {
                    LogError("iotHubSuffix is not found\r\n");
                }
                else if (config->deviceId == NULL)
                {
                    LogError("deviceId is not found\r\n");
                }
                else if (config->deviceKey == NULL)
                {
                    LogError("deviceId is not found\r\n");
                }
                else
                {
                    /* SRS_IOTHUBCLIENT_LL_12_011: [IoTHubClient_LL_CreateFromConnectionString shall call into the IoTHubClient_LL_Create API with the current structure and returns with the return value of it] */
                    result = IoTHubClient_LL_Create(config);
                    if (result == NULL)
                    {
                        LogError("IoTHubClient_LL_Create failed\r\n");
                    }
                }
            }
            if (deviceKeyString != NULL)
                STRING_delete(deviceKeyString);
            if (deviceIdString != NULL)
                STRING_delete(deviceIdString);
            if (hostSuffixString != NULL)
                STRING_delete(hostSuffixString);
            if (hostNameString != NULL)
                STRING_delete(hostNameString);
            if (valueString != NULL)
                STRING_delete(valueString);
            if (tokenString != NULL)
                STRING_delete(tokenString);
            if (connString != NULL)
                STRING_delete(connString);
            if (protocolGateway != NULL)
                STRING_delete(protocolGateway);

            if (tokenizer1 != NULL)
                STRING_TOKENIZER_destroy(tokenizer1);

            free(config);
        }
    }
    return result;
}

static void setTransportProtocol(IOTHUB_CLIENT_LL_HANDLE_DATA* handleData, TRANSPORT_PROVIDER* protocol)
{
	handleData->IoTHubTransport_SetOption = protocol->IoTHubTransport_SetOption;
	handleData->IoTHubTransport_Create = protocol->IoTHubTransport_Create;
	handleData->IoTHubTransport_Destroy = protocol->IoTHubTransport_Destroy;
	handleData->IoTHubTransport_Register = protocol->IoTHubTransport_Register;
	handleData->IoTHubTransport_Unregister = protocol->IoTHubTransport_Unregister;
	handleData->IoTHubTransport_Subscribe = protocol->IoTHubTransport_Subscribe;
	handleData->IoTHubTransport_Unsubscribe = protocol->IoTHubTransport_Unsubscribe;
	handleData->IoTHubTransport_DoWork = protocol->IoTHubTransport_DoWork;
	handleData->IoTHubTransport_GetSendStatus = protocol->IoTHubTransport_GetSendStatus;

}

IOTHUB_CLIENT_LL_HANDLE IoTHubClient_LL_Create(const IOTHUB_CLIENT_CONFIG* config)
{
    IOTHUB_CLIENT_LL_HANDLE result;
    /*Codes_SRS_IOTHUBCLIENT_LL_02_001: [IoTHubClient_LL_Create shall return NULL if config parameter is NULL or protocol field is NULL.]*/
    if (
        (config == NULL) ||
        (config->protocol == NULL)
        )
    {
        result = NULL;
        LogError("invalid configuration (NULL detected)\r\n");
    }
    else
    {
        IOTHUB_CLIENT_LL_HANDLE_DATA* handleData = (IOTHUB_CLIENT_LL_HANDLE_DATA*)malloc(sizeof(IOTHUB_CLIENT_LL_HANDLE_DATA));
        if (handleData == NULL)
        {
            LogError("malloc failed\r\n");
            result = NULL;
        }
        else
        {
            if ((handleData->tickCounter = tickcounter_create()) == NULL)
            {
                LogError("unable to get a tickcounter");
                free(handleData);
                result = NULL;
            }
            else
            {
            /*Codes_SRS_IOTHUBCLIENT_LL_02_004: [Otherwise IoTHubClient_LL_Create shall initialize a new DLIST (further called "waitingToSend") containing records with fields of the following types: IOTHUB_MESSAGE_HANDLE, IOTHUB_CLIENT_EVENT_CONFIRMATION_CALLBACK, void*.]*/
            IOTHUBTRANSPORT_CONFIG lowerLayerConfig;
            DList_InitializeListHead(&(handleData->waitingToSend));
			setTransportProtocol(handleData, (TRANSPORT_PROVIDER*)config->protocol());
            handleData->messageCallback = NULL;
            handleData->messageUserContextCallback = NULL;
            handleData->lastMessageReceiveTime = INDEFINITE_TIME;
            /*Codes_SRS_IOTHUBCLIENT_LL_02_006: [IoTHubClient_LL_Create shall populate a structure of type IOTHUBTRANSPORT_CONFIG with the information from config parameter and the previous DLIST and shall pass that to the underlying layer _Create function.]*/
            lowerLayerConfig.upperConfig = config;
            lowerLayerConfig.waitingToSend = &(handleData->waitingToSend);
            /*Codes_SRS_IOTHUBCLIENT_LL_02_007: [If the underlaying layer _Create function fails them IoTHubClient_LL_Create shall fail and return NULL.] */
            if ((handleData->transportHandle = handleData->IoTHubTransport_Create(&lowerLayerConfig)) == NULL)
            {
                LogError("underlying transport failed\r\n");
                    tickcounter_destroy(handleData->tickCounter);
                free(handleData);
                result = NULL;
            }
            else
            {
				/*Codes_SRS_IOTHUBCLIENT_LL_17_008: [IoTHubClient_LL_Create shall call the transport _Register function with the deviceId, DeviceKey and waitingToSend list.] */
				if ((handleData->deviceHandle = handleData->IoTHubTransport_Register(handleData->transportHandle, config->deviceId, config->deviceKey, handleData, &(handleData->waitingToSend))) == NULL)
				{
					/*Codes_SRS_IOTHUBCLIENT_LL_17_009: [If the _Register function fails, this function shall fail and return NULL.]*/
					LogError("Registering device in transport failed");
					handleData->IoTHubTransport_Destroy(handleData->transportHandle);
                        tickcounter_destroy(handleData->tickCounter);
					free(handleData);
					result = NULL;
				}
				else
				{
					/*Codes_SRS_IOTHUBCLIENT_LL_02_008: [Otherwise, IoTHubClient_LL_Create shall succeed and return a non-NULL handle.] */
					handleData->isSharedTransport = false;
                        /*Codes_SRS_IOTHUBCLIENT_LL_02_042: [ By default, messages shall not timeout. ]*/
                        handleData->currentMessageTimeout = 0;
					result = handleData;
				}
            }
        }
    }
    }

    return result;
}

IOTHUB_CLIENT_LL_HANDLE IoTHubClient_LL_CreateWithTransport(const IOTHUB_CLIENT_DEVICE_CONFIG * config)
{
	IOTHUB_CLIENT_LL_HANDLE result;
	/*Codes_SRS_IOTHUBCLIENT_LL_17_001: [IoTHubClient_LL_CreateWithTransport shall return NULL if config parameter is NULL, or protocol field is NULL or transportHandle is NULL.]*/
	if (
		(config == NULL) ||
		(config->protocol == NULL) ||
		(config->transportHandle == NULL)
		)
	{
		result = NULL;
		LogError("invalid configuration (NULL detected)\r\n");
	}
	else
	{
		/*Codes_SRS_IOTHUBCLIENT_LL_17_002: [IoTHubClient_LL_CreateWithTransport shall allocate data for the IOTHUB_CLIENT_LL_HANDLE.]*/
		IOTHUB_CLIENT_LL_HANDLE_DATA* handleData = (IOTHUB_CLIENT_LL_HANDLE_DATA*)malloc(sizeof(IOTHUB_CLIENT_LL_HANDLE_DATA));
		if (handleData == NULL)
		{
			/*Codes_SRS_IOTHUBCLIENT_LL_17_003: [If allocation fails, the function shall fail and return NULL.] */
			LogError("malloc failed\r\n");
			result = NULL;
		}
		else
		{
            if ((handleData->tickCounter = tickcounter_create()) == NULL)
            {
                LogError("unable to get a tickcounter");
                free(handleData);
                result = NULL;
            }
            else
            {
			/*Codes_SRS_IOTHUBCLIENT_LL_17_004: [IoTHubClient_LL_CreateWithTransport shall initialize a new DLIST (further called "waitingToSend") containing records with fields of the following types: IOTHUB_MESSAGE_HANDLE, IOTHUB_CLIENT_EVENT_CONFIRMATION_CALLBACK, void*.]*/
			DList_InitializeListHead(&(handleData->waitingToSend));
			setTransportProtocol(handleData, (TRANSPORT_PROVIDER*)config->protocol());
			handleData->messageCallback = NULL;
			handleData->messageUserContextCallback = NULL;
			handleData->lastMessageReceiveTime = INDEFINITE_TIME;
			handleData->transportHandle = config->transportHandle;
			/*Codes_SRS_IOTHUBCLIENT_LL_17_006: [IoTHubClient_LL_CreateWithTransport shall call the transport _Register function with the deviceId, DeviceKey and waitingToSend list.]*/
			if ((handleData->deviceHandle = handleData->IoTHubTransport_Register(config->transportHandle, config->deviceId, config->deviceKey, handleData, &(handleData->waitingToSend))) == NULL)
			{
				/*Codes_SRS_IOTHUBCLIENT_LL_17_007: [If the _Register function fails, this function shall fail and return NULL.]*/
				LogError("Registering device in transport failed");
                    tickcounter_destroy(handleData->tickCounter);
				free(handleData);
				result = NULL;
			}
			else
			{
				/*Codes_SRS_IOTHUBCLIENT_LL_17_005: [IoTHubClient_LL_CreateWithTransport shall save the transport handle and mark this transport as shared.]*/
				handleData->isSharedTransport = true;
                    /*Codes_SRS_IOTHUBCLIENT_LL_02_042: [ By default, messages shall not timeout. ]*/
                    handleData->currentMessageTimeout = 0;
				result = handleData;
			}
		}
	}
	}

	return result;
}

void IoTHubClient_LL_Destroy(IOTHUB_CLIENT_LL_HANDLE iotHubClientHandle)
{
    /*Codes_SRS_IOTHUBCLIENT_LL_02_009: [IoTHubClient_LL_Destroy shall do nothing if parameter iotHubClientHandle is NULL.]*/
    if (iotHubClientHandle != NULL)
    {
        PDLIST_ENTRY unsend;
		/*Codes_SRS_IOTHUBCLIENT_LL_17_010: [IoTHubClient_LL_Destroy  shall call the underlaying layer's _Unregister function] */
        IOTHUB_CLIENT_LL_HANDLE_DATA* handleData = (IOTHUB_CLIENT_LL_HANDLE_DATA*)iotHubClientHandle;
		handleData->IoTHubTransport_Unregister(handleData->deviceHandle);
		if (handleData->isSharedTransport == false)
		{
			/*Codes_SRS_IOTHUBCLIENT_LL_02_010: [If iotHubClientHandle was not created by IoTHubClient_LL_CreateWithTransport, IoTHubClient_LL_Destroy  shall call the underlaying layer's _Destroy function.] */
			handleData->IoTHubTransport_Destroy(handleData->transportHandle);
		}
        /*if any, remove the items currently not send*/
        while ((unsend = DList_RemoveHeadList(&(handleData->waitingToSend))) != &(handleData->waitingToSend))
        {
            IOTHUB_MESSAGE_LIST* temp = containingRecord(unsend, IOTHUB_MESSAGE_LIST, entry);
            /*Codes_SRS_IOTHUBCLIENT_LL_02_033: [Otherwise, IoTHubClient_LL_Destroy shall complete all the event message callbacks that are in the waitingToSend list with the result IOTHUB_CLIENT_CONFIRMATION_BECAUSE_DESTROY.] */
            if (temp->callback != NULL)
            {
                temp->callback(IOTHUB_CLIENT_CONFIRMATION_BECAUSE_DESTROY, temp->context);
            }
            IoTHubMessage_Destroy(temp->messageHandle);
            free(temp);
        }
		/*Codes_SRS_IOTHUBCLIENT_LL_17_011: [IoTHubClient_LL_Destroy  shall free the resources allocated by IoTHubClient (if any).] */
        tickcounter_destroy(handleData->tickCounter);
        free(handleData);
    }
}

/*Codes_SRS_IOTHUBCLIENT_LL_02_044: [ Messages already delivered to IoTHubClient_LL shall not have their timeouts modified by a new call to IoTHubClient_LL_SetOption. ]*/
/*returns 0 on success, any other value is error*/
static int attach_ms_timesOutAfter(IOTHUB_CLIENT_LL_HANDLE_DATA* handleData, IOTHUB_MESSAGE_LIST *newEntry)
{
    int result;
    /*Codes_SRS_IOTHUBCLIENT_LL_02_043: [ Calling IoTHubClient_LL_SetOption with value set to "0" shall disable the timeout mechanism for all new messages. ]*/
    if (handleData->currentMessageTimeout == 0)
    {
        newEntry->ms_timesOutAfter = 0; /*do not timeout*/
        result = 0;
    }
    else
    {
        /*Codes_SRS_IOTHUBCLIENT_LL_02_039: [ "messageTimeout" - once IoTHubClient_LL_SendEventAsync is called the message shall timeout after value miliseconds. Value is a pointer to a uint64. ]*/
        if (tickcounter_get_current_ms(handleData->tickCounter, &newEntry->ms_timesOutAfter) != 0)
        {
            result = __LINE__;
            LogError("unable to get the current relative tickcount");
        }
        else
        {
            newEntry->ms_timesOutAfter += handleData->currentMessageTimeout;
            result = 0;
        }
    }
    return result;
}

IOTHUB_CLIENT_RESULT IoTHubClient_LL_SendEventAsync(IOTHUB_CLIENT_LL_HANDLE iotHubClientHandle, IOTHUB_MESSAGE_HANDLE eventMessageHandle, IOTHUB_CLIENT_EVENT_CONFIRMATION_CALLBACK eventConfirmationCallback, void* userContextCallback)
{
    IOTHUB_CLIENT_RESULT result;
    /*Codes_SRS_IOTHUBCLIENT_LL_02_011: [IoTHubClient_LL_SendEventAsync shall fail and return IOTHUB_CLIENT_INVALID_ARG if parameter iotHubClientHandle or eventMessageHandle is NULL.]*/
    if (
        (iotHubClientHandle == NULL) ||
        (eventMessageHandle == NULL) ||
        /*Codes_SRS_IOTHUBCLIENT_LL_02_012: [IoTHubClient_LL_SendEventAsync shall fail and return IOTHUB_CLIENT_INVALID_ARG if parameter eventConfirmationCallback is NULL and userContextCallback is not NULL.] */
        ((eventConfirmationCallback == NULL) && (userContextCallback != NULL))
        )
    {
        result = IOTHUB_CLIENT_INVALID_ARG;
        LOG_ERROR;
    }
    else
    {
        IOTHUB_MESSAGE_LIST *newEntry = (IOTHUB_MESSAGE_LIST*)malloc(sizeof(IOTHUB_MESSAGE_LIST));
        if (newEntry == NULL)
        {
            result = IOTHUB_CLIENT_ERROR;
            LOG_ERROR;
        }
        else
        {
            IOTHUB_CLIENT_LL_HANDLE_DATA* handleData = (IOTHUB_CLIENT_LL_HANDLE_DATA*)iotHubClientHandle;

            if (attach_ms_timesOutAfter(handleData, newEntry) != 0)
            {
                result = IOTHUB_CLIENT_ERROR;
                LOG_ERROR;
                free(newEntry);
            }
            else
            {
            /*Codes_SRS_IOTHUBCLIENT_LL_02_013: [IoTHubClient_SendEventAsync shall add the DLIST waitingToSend a new record cloning the information from eventMessageHandle, eventConfirmationCallback, userContextCallback.]*/
            if ((newEntry->messageHandle = IoTHubMessage_Clone(eventMessageHandle)) == NULL)
            {
                /*Codes_SRS_IOTHUBCLIENT_LL_02_014: [If cloning and/or adding the information fails for any reason, IoTHubClient_LL_SendEventAsync shall fail and return IOTHUB_CLIENT_ERROR.] */
                result = IOTHUB_CLIENT_ERROR;
                free(newEntry);
                LOG_ERROR;
            }
            else
            {
                IOTHUB_CLIENT_LL_HANDLE_DATA* handleData = (IOTHUB_CLIENT_LL_HANDLE_DATA*)iotHubClientHandle;
                /*Codes_SRS_IOTHUBCLIENT_LL_02_013: [IoTHubClient_SendEventAsync shall add the DLIST waitingToSend a new record cloning the information from eventMessageHandle, eventConfirmationCallback, userContextCallback.]*/
                newEntry->callback = eventConfirmationCallback;
                newEntry->context = userContextCallback;
                DList_InsertTailList(&(handleData->waitingToSend), &(newEntry->entry));
                /*Codes_SRS_IOTHUBCLIENT_LL_02_015: [Otherwise IoTHubClient_LL_SendEventAsync shall succeed and return IOTHUB_CLIENT_OK.] */
                result = IOTHUB_CLIENT_OK;
            }
        }
    }
    }
    return result;
}

IOTHUB_CLIENT_RESULT IoTHubClient_LL_SetMessageCallback(IOTHUB_CLIENT_LL_HANDLE iotHubClientHandle, IOTHUB_CLIENT_MESSAGE_CALLBACK_ASYNC messageCallback, void* userContextCallback)
{
    IOTHUB_CLIENT_RESULT result;
    /*Codes_SRS_IOTHUBCLIENT_LL_02_016: [IoTHubClient_LL_SetMessageCallback shall fail and return IOTHUB_CLIENT_INVALID_ARG if parameter iotHubClientHandle is NULL.] */
    if (iotHubClientHandle == NULL)
    {
        result = IOTHUB_CLIENT_INVALID_ARG;
        LOG_ERROR;
    }
    else
    {
        IOTHUB_CLIENT_LL_HANDLE_DATA* handleData = (IOTHUB_CLIENT_LL_HANDLE_DATA*)iotHubClientHandle;
        if (messageCallback == NULL)
        {
            /*Codes_SRS_IOTHUBCLIENT_LL_02_019: [If parameter messageCallback is NULL then IoTHubClient_LL_SetMessageCallback shall call the underlying layer's _Unsubscribe function and return IOTHUB_CLIENT_OK.] */
            handleData->IoTHubTransport_Unsubscribe(handleData->deviceHandle);
            handleData->messageCallback = NULL;
            handleData->messageUserContextCallback = NULL;
            result = IOTHUB_CLIENT_OK;
        }
        else
        {
            /*Codes_SRS_IOTHUBCLIENT_LL_02_017: [If parameter messageCallback is non-NULL then IoTHubClient_LL_SetMessageCallback shall call the underlying layer's _Subscribe function.]*/
            if (handleData->IoTHubTransport_Subscribe(handleData->deviceHandle) == 0)
            {
                handleData->messageCallback = messageCallback;
                handleData->messageUserContextCallback = userContextCallback;
                result = IOTHUB_CLIENT_OK;
            }
            else
            {
                handleData->messageCallback = NULL;
                handleData->messageUserContextCallback = NULL;
                /*Codes_SRS_IOTHUBCLIENT_LL_02_018: [If the underlying layer's _Subscribe function fails, then IoTHubClient_LL_SetMessageCallback shall fail and return IOTHUB_CLIENT_ERROR. Otherwise IoTHubClient_LL_SetMessageCallback shall succeed and return IOTHUB_CLIENT_OK.]*/
                result = IOTHUB_CLIENT_ERROR;
            }
        }
    }

    return result;
}

static void DoTimeouts(IOTHUB_CLIENT_LL_HANDLE_DATA* handleData)
{
    uint64_t nowTick;
    if (tickcounter_get_current_ms(handleData->tickCounter, &nowTick) != 0)
    {
        LogError("unable to get the current ms, timeouts will not be processed");
    }
    else
    {
        DLIST_ENTRY* currentItemInWaitingToSend = handleData->waitingToSend.Flink;
        while (currentItemInWaitingToSend != &(handleData->waitingToSend)) /*while we are not at the end of the list*/
        {
            IOTHUB_MESSAGE_LIST* fullEntry = containingRecord(currentItemInWaitingToSend, IOTHUB_MESSAGE_LIST, entry);
            /*Codes_SRS_IOTHUBCLIENT_LL_02_041: [ If more than value miliseconds have passed since the call to IoTHubClient_LL_SendEventAsync then the message callback shall be called with a status code of IOTHUB_CLIENT_CONFIRMATION_TIMEOUT. ]*/
            if ((fullEntry->ms_timesOutAfter!=0) && (fullEntry->ms_timesOutAfter < nowTick))
            {
                PDLIST_ENTRY theNext = currentItemInWaitingToSend->Flink; /*need to save the next item, because the below operations are destructive*/
                DList_RemoveEntryList(currentItemInWaitingToSend);
                if (fullEntry->callback != NULL)
                {
                    fullEntry->callback(IOTHUB_CLIENT_CONFIRMATION_MESSAGE_TIMEOUT, fullEntry->context);
                }
                IoTHubMessage_Destroy(fullEntry->messageHandle); /*because it has been cloned*/
                free(fullEntry);
                currentItemInWaitingToSend = theNext;
            }
            else
            {
                currentItemInWaitingToSend = currentItemInWaitingToSend->Flink;
            }
        }
    }
}

void IoTHubClient_LL_DoWork(IOTHUB_CLIENT_LL_HANDLE iotHubClientHandle)
{
    /*Codes_SRS_IOTHUBCLIENT_LL_02_020: [If parameter iotHubClientHandle is NULL then IoTHubClient_LL_DoWork shall not perform any action.] */
    if (iotHubClientHandle != NULL)
    {
        IOTHUB_CLIENT_LL_HANDLE_DATA* handleData = (IOTHUB_CLIENT_LL_HANDLE_DATA*)iotHubClientHandle;
        DoTimeouts(handleData);
        handleData->IoTHubTransport_DoWork(handleData->transportHandle, iotHubClientHandle);
    }
}

IOTHUB_CLIENT_RESULT IoTHubClient_LL_GetSendStatus(IOTHUB_CLIENT_LL_HANDLE iotHubClientHandle, IOTHUB_CLIENT_STATUS *iotHubClientStatus)
{
    IOTHUB_CLIENT_RESULT result;

    /* Codes_SRS_IOTHUBCLIENT_09_007: [IoTHubClient_GetSendStatus shall return IOTHUB_CLIENT_INVALID_ARG if called with NULL parameter] */
    if (iotHubClientHandle == NULL || iotHubClientStatus == NULL)
    {
        result = IOTHUB_CLIENT_INVALID_ARG;
        LOG_ERROR;
    }
    else
    {
        IOTHUB_CLIENT_LL_HANDLE_DATA* handleData = (IOTHUB_CLIENT_LL_HANDLE_DATA*)iotHubClientHandle;

        /* Codes_SRS_IOTHUBCLIENT_09_008: [IoTHubClient_GetSendStatus shall return IOTHUB_CLIENT_OK and status IOTHUB_CLIENT_SEND_STATUS_IDLE if there is currently no items to be sent] */
        /* Codes_SRS_IOTHUBCLIENT_09_009: [IoTHubClient_GetSendStatus shall return IOTHUB_CLIENT_OK and status IOTHUB_CLIENT_SEND_STATUS_BUSY if there are currently items to be sent] */
        result = handleData->IoTHubTransport_GetSendStatus(handleData->deviceHandle, iotHubClientStatus);
    }

    return result;
}

void IoTHubClient_LL_SendComplete(IOTHUB_CLIENT_LL_HANDLE handle, PDLIST_ENTRY completed, IOTHUB_BATCHSTATE_RESULT result)
{
    /*Codes_SRS_IOTHUBCLIENT_LL_02_022: [If parameter completed is NULL, or parameter handle is NULL then IoTHubClient_LL_SendBatch shall return.]*/
    if (
        (handle == NULL) ||
        (completed == NULL)
        )
    {
        /*"shall return"*/
        LogError("invalid arg\r\n");
    }
    else
    {
        /*Codes_SRS_IOTHUBCLIENT_LL_02_027: [If parameter result is IOTHUB_BACTHSTATE_FAILED then IoTHubClient_LL_SendComplete shall call all the non-NULL callbacks with the result parameter set to IOTHUB_CLIENT_CONFIRMATION_ERROR and the context set to the context passed originally in the SendEventAsync call.] */
        /*Codes_SRS_IOTHUBCLIENT_LL_02_025: [If parameter result is IOTHUB_BATCHSTATE_SUCCESS then IoTHubClient_LL_SendComplete shall call all the non-NULL callbacks with the result parameter set to IOTHUB_CLIENT_CONFIRMATION_OK and the context set to the context passed originally in the SendEventAsync call.]*/
        IOTHUB_CLIENT_CONFIRMATION_RESULT resultToBeCalled = (result == IOTHUB_BATCHSTATE_SUCCESS) ? IOTHUB_CLIENT_CONFIRMATION_OK : IOTHUB_CLIENT_CONFIRMATION_ERROR;
        PDLIST_ENTRY oldest;
        while((oldest= DList_RemoveHeadList(completed))!=completed)
        {
            IOTHUB_MESSAGE_LIST* messageList = (IOTHUB_MESSAGE_LIST*)containingRecord(oldest, IOTHUB_MESSAGE_LIST, entry);
            if (messageList->callback != NULL)
            {
                messageList->callback(resultToBeCalled, messageList->context);
            }
            IoTHubMessage_Destroy(messageList->messageHandle);
            free(messageList);
        }
    }
}

IOTHUBMESSAGE_DISPOSITION_RESULT IoTHubClient_LL_MessageCallback(IOTHUB_CLIENT_LL_HANDLE handle, IOTHUB_MESSAGE_HANDLE message)
{
    int result;
    /*Codes_SRS_IOTHUBCLIENT_LL_02_029: [If parameter handle is NULL then IoTHubClient_LL_MessageCallback shall return IOTHUBMESSAGE_ABANDONED.] */
    if (handle == NULL)
    {
        LogError("invalid argument\r\n");
        result = IOTHUBMESSAGE_ABANDONED;
    }
    else
    {
        IOTHUB_CLIENT_LL_HANDLE_DATA* handleData = (IOTHUB_CLIENT_LL_HANDLE_DATA*)handle;

        /* Codes_SRS_IOTHUBCLIENT_LL_09_004: [IoTHubClient_LL_GetLastMessageReceiveTime shall return lastMessageReceiveTime in localtime] */
        handleData->lastMessageReceiveTime = get_time(NULL);

        /*Codes_SRS_IOTHUBCLIENT_LL_02_030: [IoTHubClient_LL_MessageCallback shall invoke the last callback function (the parameter messageCallback to IoTHubClient_LL_SetMessageCallback) passing the message and the passed userContextCallback.]*/
        if (handleData->messageCallback != NULL)
        {
            result = handleData->messageCallback(message, handleData->messageUserContextCallback);
        }
        else
        {
            /*Codes_SRS_IOTHUBCLIENT_LL_02_032: [If the last callback function was NULL, then IoTHubClient_LL_MessageCallback  shall return IOTHUBMESSAGE_ABANDONED.] */
            LogError("user callback was NULL\r\n");
            result = IOTHUBMESSAGE_ABANDONED;
        }
    }
    /*Codes_SRS_IOTHUBCLIENT_LL_02_031: [Then IoTHubClient_LL_MessageCallback shall return what the user function returns.]*/
    return result;
}

IOTHUB_CLIENT_RESULT IoTHubClient_LL_GetLastMessageReceiveTime(IOTHUB_CLIENT_LL_HANDLE iotHubClientHandle, time_t* lastMessageReceiveTime)
{
    IOTHUB_CLIENT_RESULT result;
    IOTHUB_CLIENT_LL_HANDLE_DATA* handleData = (IOTHUB_CLIENT_LL_HANDLE_DATA*)iotHubClientHandle;

    /* Codes_SRS_IOTHUBCLIENT_LL_09_001: [IoTHubClient_LL_GetLastMessageReceiveTime shall return IOTHUB_CLIENT_INVALID_ARG if any of the arguments is NULL] */
    if (handleData == NULL || lastMessageReceiveTime == NULL)
    {
        result = IOTHUB_CLIENT_INVALID_ARG;
        LOG_ERROR;
    }
    else
    {
        /* Codes_SRS_IOTHUBCLIENT_LL_09_002: [IoTHubClient_LL_GetLastMessageReceiveTime shall return IOTHUB_CLIENT_INDEFINITE_TIME - and not set 'lastMessageReceiveTime' - if it is unable to provide the time for the last commands] */
        if (handleData->lastMessageReceiveTime == INDEFINITE_TIME)
        {
            result = IOTHUB_CLIENT_INDEFINITE_TIME;
            LOG_ERROR;
        }
        else
        {
            /* Codes_SRS_IOTHUBCLIENT_LL_09_003: [IoTHubClient_LL_GetLastMessageReceiveTime shall return IOTHUB_CLIENT_OK if it wrote in the lastMessageReceiveTime the time when the last command was received] */
            /* Codes_SRS_IOTHUBCLIENT_LL_09_004: [IoTHubClient_LL_GetLastMessageReceiveTime shall return lastMessageReceiveTime in localtime] */
            *lastMessageReceiveTime = handleData->lastMessageReceiveTime;
            result = IOTHUB_CLIENT_OK;
        }
    }

    return result;
}

IOTHUB_CLIENT_RESULT IoTHubClient_LL_SetOption(IOTHUB_CLIENT_LL_HANDLE iotHubClientHandle, const char* optionName, const void* value)
{

    IOTHUB_CLIENT_RESULT result;
    /*Codes_SRS_IOTHUBCLIENT_LL_02_034: [If iotHubClientHandle is NULL then IoTHubClient_LL_SetOption shall return IOTHUB_CLIENT_INVALID_ARG.]*/
    /*Codes_SRS_IOTHUBCLIENT_LL_02_035: [If optionName is NULL then IoTHubClient_LL_SetOption shall return IOTHUB_CLIENT_INVALID_ARG.] */
    /*Codes_SRS_IOTHUBCLIENT_LL_02_036: [If value is NULL then IoTHubClient_LL_SetOption shall return IOTHUB_CLIENT_INVALID_ARG.] */
    if (
        (iotHubClientHandle == NULL) ||
        (optionName == NULL) ||
        (value == NULL)
        )
    {
        result = IOTHUB_CLIENT_INVALID_ARG;
        LogError("invalid argument (NULL)\r\n");
    }
    else
    {
        IOTHUB_CLIENT_LL_HANDLE_DATA* handleData = (IOTHUB_CLIENT_LL_HANDLE_DATA*)iotHubClientHandle;

        /*Codes_SRS_IOTHUBCLIENT_LL_02_039: [ "messageTimeout" - once IoTHubClient_LL_SendEventAsync is called the message shall timeout after value miliseconds. Value is a pointer to a uint64. ]*/
        if (strcmp(optionName, "messageTimeout") == 0)
        {
            /*this is an option handled by IoTHubClient_LL*/
            /*Codes_SRS_IOTHUBCLIENT_LL_02_043: [ Calling IoTHubClient_LL_SetOption with value set to "0" shall disable the timeout mechanism for all new messages. ]*/
            handleData->currentMessageTimeout = *(const uint64_t*)value;
            result = IOTHUB_CLIENT_OK;
        }
        else
        {
        /*Codes_SRS_IOTHUBCLIENT_LL_02_038: [Otherwise, IoTHubClient_LL shall call the function _SetOption of the underlying transport and return what that function is returning.] */
        result = handleData->IoTHubTransport_SetOption(handleData->transportHandle, optionName, value);

        if (result != IOTHUB_CLIENT_OK)
        {
            LogError("underlying transport failed, returned = %s\r\n", ENUM_TO_STRING(IOTHUB_CLIENT_RESULT, result));
        }
        }
    }
    return result;
}


text:
/* modified 05 Jan 2000 by Paul B. McBride (pmcbride@tiac.net) */
/*=============================================================
 * gedcom.h -- Main header file of LifeLines system
 * Copyright(c) 1992-96 by T.T. Wetmore IV; all rights reserved
 * pre-SourceForge version information:
 *   2.3.4 - 24 Jun 93    2.3.5 - 02 Sep 93
 *   3.0.0 - 23 Sep 94    3.0.2 - 09 Dec 94
 *   3.0.3 - 17 Jan 96
 *===========================================================*/

#ifndef _GEDCOM_H
#define _GEDCOM_H

#include "table.h"
#include "translat.h"

#ifndef INCLUDED_UIPROMPTS_H
#include "uiprompts.h"
#endif

#define NAMESEP '/'
#define MAXGEDNAMELEN 512
/* keys run up to 9,999,999, eg I9999999 */
/* These are GEDCOM identifier numbers, eg, for @I510@,
 the key is 510 */
/* btree databases use this as part of the database key */
#define MAXKEYWIDTH 8
#define MAXKEYNUMBER 9999999

#define OKAY  1
#define ERROR 0
#define DONE -1

/*=====================================
 * NODE -- Internal form of GEDCOM line
 *===================================*/
/*
 A NODE is a struct ntag which holds the in-memory
 representation of one line of a GEDCOM record.
 For example, a NODE may hold the in-memory representation
 of the GEDCOM line "2 DATE ABT 1900". The NODE actually contains
 the "DATE" part of the string in its n_tag field, and
 the "ABT 1900" portion of the string in its n_val field.
 The level is not explicitly given, but is implicit in the
 NODEs location in the NODE tree in which it lives (it has
 fields n_parent, n_child, n_sibling which connect it into
 its NODE tree). (E.g., its parent might be a NODE representing
 "1 BIRT".)
*/
typedef struct tag_cacheel *CACHEEL;
typedef struct tag_node *NODE;
struct tag_node {
	/* a NODE is an OBJECT */
	struct tag_vtable * vtable; /* generic object table (see vtable.h) */
	int    n_refcnt;    /* refcount for temp nodes */
	STRING n_xref;      /* cross ref */
	STRING n_tag;       /* tag */
	STRING n_val;       /* value */
	NODE   n_parent;    /* parent */
	NODE   n_child;     /* first child */
	NODE   n_sibling;   /* sibling */
	INT    n_flag;      /* eg, ND_TEMP */
	CACHEEL n_cel;      /* pointer to cacheel, if node is inside cache */
};
#define nxref(n)    ((n)->n_xref)
#define ntag(n)     ((n)->n_tag)
#define nval(n)     ((n)->n_val)
#define nparent(n)  ((n)->n_parent)
#define nchild(n)   ((n)->n_child)
#define nsibling(n) ((n)->n_sibling)
#define nflag(n)    ((n)->n_flag)
#define nrefcnt(n)  ((n)->n_refcnt)
#define ncel(n)     ((n)->n_cel)
enum { ND_TEMP=1 };

struct tag_nkey { char ntype; INT keynum; char key[MAXKEYWIDTH+1]; };
typedef struct tag_nkey NKEY;

/*=====================================
 * RECORD -- Internal form of GEDCOM record
 *===================================*/
/*
 A RECORD is a struct record_s which holds the in-memory representation
 of an entire GEDCOM record, such as an INDI. It has a pointer to the
 root NODE of the INDI (which is of course a NODE representing a line
 such as "0 @I43@ INDI"), and it also contains some additional data.
 A RECORD will in the future contain a pointer to its cache element.
 LifeLines is very RECORD-oriented.
*/

typedef struct tag_record *RECORD;

NODE nztop(RECORD rec); /* handles NULL, also reloads from cache */
CNSTRING nzkey(RECORD rec);
INT nzkeynum(RECORD rec);
char nztype(RECORD rec);
CACHEEL nzcel(RECORD rec);

/*============================================
 * Traversal function pointer typedefs
 *==========================================*/
typedef BOOLEAN(*TRAV_RAWRECORDS_FUNC)(CNSTRING key, STRING data, INT len, void *param);
#define TRAV_RAWRECORDS_FUNC_ARGS(zkey,zdata,zlen,zparam) CNSTRING zkey, STRING zdata, INT zlen, void *zparam

typedef BOOLEAN(*TRAV_RECORDS_FUNC)(CNSTRING key, RECORD rec, void *param);
#define TRAV_RECORDS_FUNC_ARGS(zkey,zrec,zparam) CNSTRING zkey, RECORD zrec, HINT_PARAM_UNUSED void *zparam

typedef BOOLEAN(*TRAV_NAMES_FUNC)(CNSTRING key, CNSTRING name, BOOLEAN newset, void *param);
#define TRAV_NAMES_FUNC_ARGS(zkey,zname,znewset,zparam) CNSTRING zkey, CNSTRING zname, BOOLEAN znewset, HINT_PARAM_UNUSED void *zparam

typedef BOOLEAN(*TRAV_REFNS_FUNC)(CNSTRING key, CNSTRING refn, BOOLEAN newset, void *param);
#define TRAV_REFNS_FUNC_ARGS(zkey,zrefn,znewset,zparam) CNSTRING zkey, CNSTRING zrefn, BOOLEAN znewset, HINT_PARAM_UNUSED void *zparam

/*=====================================
 * LLDATABASE types -- LifeLines database
 *===================================*/

typedef struct tag_lldatabase *LLDATABASE;

/*
 reformating functions - format date or place for display
 callbacks to GUI client to tailor display as desired
 either or both may be null, meaning use date or place exactly as
 occurs in data
*/
struct tag_rfmt {
	STRING (*rfmt_date)(STRING); /* returns static buffer */
	STRING (*rfmt_plac)(STRING); /* returns static buffer */
	STRING combopic; /* stdalloc'd buffer, eg, "%1, %2" */
};
typedef struct tag_rfmt *RFMT;

/*==============================================
 * Option type enumerations (but we use defines)
 *============================================*/

#define SEX_MALE    1
#define SEX_FEMALE  2
#define SEX_UNKNOWN 3

/* custom translation tables */
	/* MEDIN: translate editor characters to internal */
#define MEDIN 0
	/* MINED: translate internal characters to editor */
#define MINED 1
	/* MGDIN: translate gedcom file characters to internal */
#define MGDIN 2
	/* MGDIN: translate internal characters to gedcom file */
#define MINGD 3
	/* MDSIN: translate display characters to internal */
#define MDSIN 4
	/* MINDS: translate internal characters to display */
#define MINDS 5
	/* MRPIN: translate report to internal characters */
#define MRPIN 6
	/* MINRP: translate internal characters to report */
#define MINRP 7
	/* MSORT: custom sort table, characters to numeric order */
#define MSORT 8
	/* MCHAR: character table (translation result unused) */
#define MCHAR 9
	/* MLCAS: translate character to lower-case (UNIMPLEMENTED) */
#define MLCAS 10
	/* MUCAS: translate character to upper-case (UNIMPLEMENTED) */
#define MUCAS 11
	/* MPREF: prefix to skip for sorting (UNIMPLEMENTED) */
#define MPREF 12
	/* number of maps listed above */
#define NUM_TT_MAPS 13

/*========
 * Globals
 *======*/

extern INT flineno;
extern BOOLEAN keyflag;
extern BOOLEAN readonly;
extern BOOLEAN immutable;
extern STRING editstr;
extern STRING editfile;
/* tabtable & placabbvs should be moved into LLDATABASE */
extern TABLE tagtable;		/* table for GEDCOM tags */
extern TABLE placabbvs;		/* table for place abbrvs */
extern LLDATABASE def_lldb;        /* default database */

/*=====================
 * enums for functions
 *===================*/
typedef enum { DOSURCAP, NOSURCAP } SURCAPTYPE;
typedef enum { SURFIRST, REGORDER } SURORDER;

/*=====================
 * Function definitions
 *===================*/

STRING addat(STRING);
void addixref(INT key);
void addexref(INT key);
void addfxref(INT key);
void addref_record(RECORD rec);
void addsxref(INT key);
void addxref(CNSTRING key);
void addxxref(INT key);
BOOLEAN add_refn(CNSTRING refn, CNSTRING key);
BOOLEAN are_locales_supported(void);
void change_node_tag(NODE node, STRING newtag);
RECORD choose_child(RECORD irec, RECORD frec, STRING msg0, STRING msgn, ASK1Q ask1);
void choose_and_remove_family(void);
RECORD choose_father(RECORD irec, RECORD frec, STRING msg0, STRING msgn, ASK1Q ask1);
RECORD choose_family(RECORD irec, STRING msg0, STRING msgn, BOOLEAN fams);
RECORD choose_mother(RECORD indi, RECORD fam, STRING msg0, STRING msgn, ASK1Q ask1);
RECORD choose_note(RECORD current, STRING msg0, STRING msgn);
RECORD choose_pointer(RECORD current, STRING msg0, STRING msgn);
RECORD choose_source(RECORD current, STRING msg0, STRING msgn);
RECORD choose_spouse(RECORD irec, STRING msg0, STRING msgn);
void classify_nodes(NODE*, NODE*, NODE*);
void closexref(void);
void close_lifelines(void);
NODE convert_first_fp_to_node(FILE*, BOOLEAN, XLAT, STRING*, BOOLEAN*);
NODE copy_node(NODE);
NODE copy_node_subtree(NODE node);
NODE copy_nodes(NODE node, BOOLEAN kids, BOOLEAN sibs);
BOOLEAN create_database(STRING dbused, INT *lldberr);
NODE create_node(STRING, STRING, STRING, NODE);
NODE create_temp_node(STRING, STRING, STRING, NODE);
void delete_metarec(STRING key);
void dumpxrefs(void);
BOOLEAN edit_mapping(INT);
BOOLEAN edit_valtab_from_db(STRING, TABLE*, INT sep, STRING, STRING (*validator)(TABLE tab, void * param), void *param);
BOOLEAN equal_tree(NODE, NODE);
BOOLEAN equal_node(NODE, NODE);
BOOLEAN equal_nodes(NODE, NODE, BOOLEAN, BOOLEAN);
void even_to_cache(NODE);
void even_to_dbase(NODE);
STRING even_to_list_string(NODE even, INT len, STRING delim);
STRING event_to_date(NODE, BOOLEAN);
void event_to_date_place(NODE node, STRING * date, STRING * plac);
STRING event_to_plac(NODE, BOOLEAN);
STRING event_to_string(NODE, RFMT rfmt);
void fam_to_cache(NODE);
void fam_to_dbase(NODE);
STRING fam_to_event(NODE, STRING tag, STRING head, INT len, RFMT);
NODE fam_to_first_chil(NODE);
NODE fam_to_last_chil(NODE);
STRING fam_to_list_string(NODE fam, INT len, STRING delim);
NODE fam_to_spouse(NODE, NODE);
int next_spouse(NODE *node, RECORD *spouse);
RECORD file_to_record(STRING fname, XLAT ttm, STRING *pmsg, BOOLEAN *pemp);
NODE file_to_node(STRING, XLAT, STRING*, BOOLEAN*);
INT file_to_line(FILE*, XLAT, INT*, STRING*, STRING*, STRING*, STRING*);
NODE find_node(NODE, STRING, STRING, NODE*);
NODE find_tag(NODE, CNSTRING);
void free_node(NODE);
void free_nodes(NODE);
void free_temp_node_tree(NODE);
STRING full_value(NODE, STRING sep);
ZSTR get_cache_stats_fam(void);
ZSTR get_cache_stats_indi(void);
STRING get_current_locale_collate(void);
STRING get_current_locale_msgs(void);
INT get_decimal(STRING);
INT get_hexidecimal(STRING);
STRING get_lifelines_version(INT maxlen);
STRING get_original_locale_collate(void);
STRING get_original_locale_msgs(void);
STRING get_property(STRING opt);
void get_refns(STRING, INT*, STRING**, INT);
STRING getexref(void);
STRING getfxref(void);
INT32 getixrefnum(void);
STRING getsxref(void);
STRING getxxref(void);
BOOLEAN getrefnrec(CNSTRING refn);
void growexrefs(void);
void growfxrefs(void);
void growixrefs(void);
void growsxrefs(void);
void growxxrefs(void);
INT hexvalue(INT);
void index_by_refn(NODE, STRING);
void indi_to_dbase(NODE);
STRING indi_to_event(NODE, STRING tag, STRING head, INT len, RFMT);
NODE indi_to_famc(NODE);
NODE indi_to_fath(NODE);
NODE indi_to_moth(NODE);
STRING indi_to_name(NODE, INT);
RECORD indi_to_next_sib(RECORD);
NODE indi_to_next_sib_old(NODE);
STRING indi_to_ped_fix(NODE indi, INT len);
RECORD indi_to_prev_sib(RECORD);
NODE indi_to_prev_sib_old(NODE);
STRING indi_to_title(NODE, INT);
void initxref(void);
void init_browse_lists(void);
void init_caches(void);
void free_caches(void);
void init_disp_reformat(void);
BOOLEAN init_lifelines_postdb(void);
BOOLEAN init_lifelines_global(STRING configfile, STRING * pmsg, void (*notify)(STRING db, BOOLEAN opening));
CNSTRING init_get_config_file(void);
void init_new_record(RECORD rec, CNSTRING key);
BOOLEAN init_valtab_from_file(STRING, TABLE, XLAT, INT sep, STRING*);
BOOLEAN init_valtab_from_rec(CNSTRING, TABLE, INT sep, STRING*);
BOOLEAN init_valtab_from_string(CNSTRING, TABLE, INT sep, STRING*);
BOOLEAN is_codeset_utf8(CNSTRING codeset);
BOOLEAN is_iconv_supported(void);
BOOLEAN is_nls_supported(void);
BOOLEAN is_record_missing_data_entry(CNSTRING key);
BOOLEAN is_temp_node(NODE);
BOOLEAN iso_list(NODE, NODE);
BOOLEAN iso_nodes(NODE, NODE, BOOLEAN, BOOLEAN);
void join_fam(NODE, NODE, NODE, NODE, NODE, NODE);
void join_indi(NODE, NODE, NODE, NODE, NODE, NODE, NODE);
void join_othr(NODE root, NODE refn, NODE rest);
STRING key_of_record(NODE);
RECORD key_possible_to_record(STRING, INT let);
NODE key_to_even(CNSTRING);
RECORD key_to_erecord(CNSTRING);
NODE key_to_fam(CNSTRING);
RECORD key_to_frecord(CNSTRING);
NODE key_to_indi(CNSTRING);
RECORD key_to_irecord(CNSTRING);
RECORD key_to_orecord(CNSTRING);
NODE key_to_othr(CNSTRING);
RECORD key_to_record(CNSTRING key);
NODE key_to_sour(CNSTRING);
RECORD key_to_srecord(CNSTRING);
NODE key_to_type(CNSTRING key, INT reportmode);
NODE keynum_to_fam(int keynum);
RECORD keynum_to_erecord(int keynum);
RECORD keynum_to_frecord(int keynum);
NODE keynum_to_indi(int keynum);
RECORD keynum_to_irecord(int keynum);
NODE keynum_to_node(char ntype, int keynum);
RECORD keynum_to_orecord(int keynum);
RECORD keynum_to_record(char ntype, int keynum);
RECORD keynum_to_srecord(int keynum);
NODE keynum_to_sour(int keynum);
NODE keynum_to_even(int keynum);
NODE keynum_to_othr(int keynum);
INT length_nodes(NODE);
STRING ll_langinfo(void);
char * llsetlocale(int category, char * locale);
void load_char_mappings(void);
BOOLEAN load_new_tt(CNSTRING filepath, INT ttnum);
void locales_notify_language_change(void);
void locales_notify_uicodeset_changes(void);
STRING newexref(STRING, BOOLEAN);
STRING newfxref(STRING, BOOLEAN);
STRING newixref(STRING, BOOLEAN);
STRING newsxref(STRING, BOOLEAN);
STRING newxxref(STRING, BOOLEAN);
void new_name_browse_list(STRING, STRING);
RECORD next_fp_to_record(FILE*, BOOLEAN, XLAT, STRING*, BOOLEAN*);
NODE next_fp_to_node(FILE*, BOOLEAN, XLAT, STRING*, BOOLEAN*);
void nkey_copy(NKEY * src, NKEY * dest);
BOOLEAN nkey_eq(NKEY * nkey1, NKEY * nkey2);
void nkey_clear(NKEY * nkey);
void nkey_load_key(NKEY * nkey);
BOOLEAN nkey_to_node(NKEY * nkey, NODE * node);
BOOLEAN nkey_to_record(NKEY * nkey, RECORD * prec);
NKEY nkey_zero(void);
void node_to_dbase(NODE, STRING);
BOOLEAN node_to_file(INT, NODE, STRING, BOOLEAN, TRANTABLE);
INT node_to_keynum(char ntype, NODE nod);
NODE node_to_next_event(NODE node, CNSTRING tag);
BOOLEAN node_to_nkey(NODE node, NKEY * nkey);
NODE node_to_node(NODE, INT*);
RECORD node_to_record(NODE node);
STRING node_to_tag(NODE node, STRING tag, INT len);
void normalize_fam(NODE fam);
void normalize_irec(RECORD irec);
void normalize_indi(NODE indi);
void normalize_rec(RECORD rec);
INT num_evens(void);
INT num_fam_xrefs(NODE fam);
INT num_fams(void);
INT num_indis(void);
INT num_spouses_of_indi(NODE);
INT num_sours(void);
INT num_othrs(void);
BOOLEAN open_database(INT alteration, STRING dbused, INT *lldberr);
BOOLEAN openxref(BOOLEAN readonly);
STRING other_to_list_string(NODE node, INT len, STRING delim);
void othr_to_cache(NODE);
void othr_to_dbase(NODE);
BOOLEAN pointer_value(STRING);
NODE qkey_to_even(CNSTRING key);
RECORD qkey_to_erecord(CNSTRING key);
NODE qkey_to_fam(CNSTRING key);
RECORD qkey_to_frecord(CNSTRING key);
NODE qkey_to_indi(CNSTRING key);
RECORD qkey_to_irecord(CNSTRING key);
RECORD qkey_to_orecord(CNSTRING key);
NODE qkey_to_othr(CNSTRING key);
RECORD qkey_to_record(CNSTRING key);
NODE qkey_to_sour(CNSTRING key);
RECORD qkey_to_srecord(CNSTRING key);
NODE qkey_to_type(CNSTRING key);
RECORD qkeynum_to_frecord(int keynum);
NODE qkeynum_to_indi(int keynum);
INT record_letter(CNSTRING);
void record_to_date_place(RECORD record, STRING tag, STRING * date, STRING * plac, INT * count);
NODE record_to_first_event(RECORD record, CNSTRING tag);
NODE refn_to_record(STRING, INT);
void register_uicodeset_callback(CALLBACK_FNC fncptr, VPTR uparm);
void register_uilang_callback(CALLBACK_FNC fncptr, VPTR uparm);
void release_record(RECORD rec);
BOOLEAN remove_child(NODE indi, NODE fam);
BOOLEAN remove_empty_fam(NODE);
BOOLEAN remove_any_record(RECORD record);
void remove_indi_by_root(NODE);
void remove_indi_cache(STRING key);
void remove_fam_cache(STRING key);
void remove_from_cache_by_key(CNSTRING key);
BOOLEAN remove_fam_record(RECORD frec);
void remove_from_browse_lists(STRING);
BOOLEAN remove_refn(CNSTRING refn, CNSTRING key);
void rename_from_browse_lists(STRING);
BOOLEAN remove_spouse(NODE indi, NODE fam);
void replace_fam(NODE fam1, NODE fam2);
void replace_indi(NODE indi1, NODE indi2);
INT resolve_refn_links(NODE);
RECORD_STATUS retrieve_to_file(STRING key, STRING file);
RECORD_STATUS retrieve_to_textfile(STRING key, STRING file, TRANSLFNC);
STRING retrieve_raw_record(CNSTRING, INT*);
STRING rmvat(CNSTRING);
STRING rmvbrackets(CNSTRING str);
STRING rpt_setlocale(STRING str);
void rptlocale(void);
void save_original_locales(void);
BOOLEAN save_tt_to_file(INT ttnum, STRING filename);
void set_displaykeys(BOOLEAN);
void set_temp_node(NODE, BOOLEAN temp);
STRING shorten_plac(STRING);
void show_node(NODE node);
void show_node_rec(INT, NODE);
void sour_to_cache(NODE);
void sour_to_dbase(NODE);
STRING sour_to_list_string(NODE sour, INT len, STRING delim);
void split_fam(NODE, NODE*, NODE*, NODE*, NODE*, NODE*);
void split_indi_old(NODE, NODE*, NODE*, NODE*, NODE*, NODE*, NODE*);
void split_othr(NODE node, NODE *prefn, NODE *prest);
BOOLEAN store_file_to_db(STRING key, STRING file);
BOOLEAN store_record(CNSTRING key, STRING rec, INT len);
RECORD string_to_record(STRING str, CNSTRING key, INT len);
void termlocale(void);
void term_browse_lists(void);
void term_namerec(void);
void term_refnrec(void);
BOOLEAN traverse_nodes(NODE node, BOOLEAN (*func)(NODE, VPTR), VPTR param);
void traverse_refns(TRAV_REFNS_FUNC func, void *param);
INT tree_strlen(INT, NODE);
void uilocale(void);
NODE union_nodes(NODE, NODE, BOOLEAN, BOOLEAN);
NODE unique_nodes(NODE, BOOLEAN);
void unknown_node_to_dbase(NODE node);
void unregister_uilang_callback(CALLBACK_FNC fncptr, VPTR uparm);
void unregister_uicodeset_callback(CALLBACK_FNC fncptr, VPTR uparm);
void update_useropts(VPTR uparm);
BOOLEAN valid_indi_tree(NODE, STRING*, NODE);
BOOLEAN valid_fam_tree(NODE, STRING*, NODE);
BOOLEAN valid_name(STRING);
BOOLEAN valid_node_type(NODE node, char ntype, STRING *pmsg, NODE node0);
BOOLEAN valid_sour_tree(NODE, STRING*, NODE);
BOOLEAN valid_to_list(STRING, LIST, INT*, STRING);
BOOLEAN valid_even_tree(NODE, STRING*, NODE);
BOOLEAN valid_othr_tree(NODE, STRING*, NODE);
INT val_to_sex(NODE);
STRING value_to_xref(STRING);
BOOLEAN writexrefs(void);
void write_node_to_editfile(NODE); /* used by Ethel */

/* dblist.c */
INT get_dblist(STRING path, LIST * dblist, LIST * dbdesclist);
void release_dblist(LIST dblist);

/* interface.c */
void del_in_dbase(CNSTRING key);
void delete_record_missing_data_entry(CNSTRING key);
BOOLEAN mark_deleted_record_as_deleted(CNSTRING key);
BOOLEAN mark_live_record_as_live(CNSTRING key);
BOOLEAN store_text_file_to_db(STRING key, CNSTRING file, TRANSLFNC);
void traverse_db_key_recs(TRAV_RECORDS_FUNC, void *param);
void traverse_db_rec_keys(CNSTRING lo, CNSTRING hi, TRAV_RAWRECORDS_FUNC func, void *param);

/* keytonod.c */
void add_new_indi_to_cache(RECORD rec);
RECORD get_record_for_cel(CACHEEL cel);

/* gstrings.c */
STRING generic_to_list_string(NODE node, STRING key, INT len, STRING delim, RFMT rfmt, BOOLEAN appkey);
STRING *get_child_strings(NODE, RFMT, INT*, STRING**);
STRING indi_to_list_string(NODE indi, NODE fam, INT len, RFMT rfmt, BOOLEAN appkey);

/* init.c */
void print_version(CNSTRING program);

/* lldatabase.c */
LLDATABASE lldb_alloc(void);
void lldb_close(LLDATABASE *plldb);
void lldb_set_btree(LLDATABASE lldb, void * btree);

/* llgettext.c */
CNSTRING get_gettext_codeset(void);
void ll_bindtextdomain(CNSTRING domain, CNSTRING localeDir);
void llgettext_set_default_localedir(CNSTRING defLocaleDir);
void set_gettext_codeset(CNSTRING domain, CNSTRING codeset);

/* misc.c */
INT xrefval(char ntype, STRING str);

/* names.c */
void add_name(CNSTRING name, CNSTRING key);
LIST find_indis_by_name(CNSTRING name);
CNSTRING getasurname(CNSTRING);
CNSTRING getsxsurname(CNSTRING);
CNSTRING givens(CNSTRING);
STRING manip_name(STRING name, SURCAPTYPE captype, SURORDER surorder, INT len);
LIST name_to_list(CNSTRING name, INT *plen, INT *psind);
STRING name_string(STRING);
int namecmp(STRING, STRING);
void remove_name(STRING name, CNSTRING key);
void traverse_names(TRAV_NAMES_FUNC func, void *param);
STRING trim_name(STRING, INT);

/* node.c */
/* node tree iterator */
struct tag_node_iter {
	NODE start;
	NODE next;
};
typedef struct tag_node_iter * NODE_ITER;
void begin_node_it(NODE node, NODE_ITER nodeit);
INT fam_to_husb(RECORD frec, RECORD * prec);
NODE fam_to_husb_node(NODE);
INT fam_to_wife(RECORD frec, RECORD * prec);
NODE fam_to_wife_node(NODE);
NODE next_node_it_ptr(NODE_ITER nodeit);

/* nodechk.c */
void nodechk(NODE node, CNSTRING scope);
void nodechk_enable(BOOLEAN enable);

/* nodeio.c */
void prefix_file_for_edit(FILE *fp);
void prefix_file_for_gedcom(FILE *fp);
void prefix_file_for_report(FILE *fp);
STRING node_to_string(NODE);
NODE string_to_node(STRING);
void write_indi_to_file_for_edit(NODE indi, CNSTRING file, RFMT rfmt);
void write_fam_to_file_for_edit(NODE fam, CNSTRING file, RFMT rfmt);
void write_nodes(INT, FILE*, XLAT, NODE, BOOLEAN, BOOLEAN, BOOLEAN);

/* place.c */
LIST place_to_list(STRING, INT*);
LIST value_to_list (STRING str, INT *plen, STRING dlm);

/* refns.c */
void annotate_with_supplemental(NODE node, RFMT rfmt);

/* soundex.c */
CNSTRING trad_soundex(CNSTRING);
INT soundex_count(void);
CNSTRING soundex_get(INT i, CNSTRING name);

/* xreffile.c */
BOOLEAN addxref_if_missing (CNSTRING key);
BOOLEAN delete_xref_if_present(CNSTRING key);
BOOLEAN is_key_in_use(CNSTRING key);
INT xref_firste(void);
INT xref_firstf(void);
INT xref_firsti(void);
INT xref_firsts(void);
INT xref_firstx(void);
INT xref_laste(void);
INT xref_lastf(void);
INT xref_lasti(void);
INT xref_lasts(void);
INT xref_lastx(void);
INT32 xref_max_any(void);
INT32 xref_max_indis(void);
INT32 xref_max_evens (void);
INT32 xref_max_fams (void);
INT32 xref_max_othrs (void);
INT32 xref_max_sours (void);
INT xref_next(char ntype, INT i);
INT xref_nexte(INT);
INT xref_nextf(INT);
INT xref_nexti(INT);
INT xref_nexts(INT);
INT xref_nextx(INT);
INT xref_prev(char ntype, INT i);
INT xref_preve(INT);
INT xref_prevf(INT);
INT xref_previ(INT);
INT xref_prevs(INT);
INT xref_prevx(INT);

#ifndef GEDCOM_MACROS_INCLUDED
#include "gedcom_macros.h"
#endif

#endif /* _GEDCOM_H */

redpajama_set_name: RedPajamaGithub


text:
package main

import (
	"flag"
	"fmt"
	"log"
	"net/http"
	"os"
	"strconv"
	"time"

	kube_client "github.com/GoogleCloudPlatform/kubernetes/pkg/client"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/cloudcfg"
)

const APP_VERSION = "0.1"

// The flag package provides a default help printer via -h switch
var (
	versionFlag  = flag.Bool("v", false, "Print the version number.")
	httpServer   = flag.String("h", "", "The host to connect to.")
	config       = flag.String("c", "", "Path to the config file.")
	labelQuery   = flag.String("l", "", "Label query to use for listing")
	updatePeriod = flag.Duration("u", 60*time.Second, "Update interarrival in seconds")
	portSpec     = flag.String("p", "", "The port spec, comma-separated list of <external>:<internal>,...")
	servicePort  = flag.Int("s", -1, "If positive, create and run a corresponding service on this port, only used with 'run'")
	authConfig   = flag.String("auth", os.Getenv("HOME")+"/.kubernetes_auth", "Path to the auth info file.  If missing, prompt the user")
	json         = flag.Bool("json", false, "If true, print raw JSON for responses")
	yaml         = flag.Bool("yaml", false, "If true, print raw YAML for responses")
)

func usage() {
	log.Fatal("Usage: cloudcfg -h <host> [-c config/file.json] [-p <hostPort>:<containerPort>,..., <hostPort-n>:<containerPort-n> <method> <path>")
}

// CloudCfg command line tool.
func main() {
	flag.Parse() // Scan the arguments list

	if *versionFlag {
		fmt.Println("Version:", APP_VERSION)
		os.Exit(0)
	}

	if len(flag.Args()) < 2 {
		usage()
	}
	method := flag.Arg(0)
	url := *httpServer + "/api/v1beta1" + flag.Arg(1)
	var request *http.Request
	var err error

	var printer cloudcfg.ResourcePrinter
	if *json {
		printer = &cloudcfg.IdentityPrinter{}
	} else if *yaml {
		printer = &cloudcfg.YAMLPrinter{}
	} else {
		printer = &cloudcfg.HumanReadablePrinter{}
	}

	auth, err := cloudcfg.LoadAuthInfo(*authConfig)
	if err != nil {
		log.Fatalf("Error loading auth: %#v", err)
	}

	switch method {
	case "get", "list":
		if len(*labelQuery) > 0 && method == "list" {
			url = url + "?labels=" + *labelQuery
		}
		request, err = http.NewRequest("GET", url, nil)
	case "delete":
		request, err = http.NewRequest("DELETE", url, nil)
	case "create":
		request, err = cloudcfg.RequestWithBody(*config, url, "POST")
	case "update":
		request, err = cloudcfg.RequestWithBody(*config, url, "PUT")
	case "rollingupdate":
		client := &kube_client.Client{
			Host: *httpServer,
			Auth: &auth,
		}
		cloudcfg.Update(flag.Arg(1), client, *updatePeriod)
	case "run":
		args := flag.Args()
		if len(args) < 4 {
			log.Fatal("usage: cloudcfg -h <host> run <image> <replicas> <name>")
		}
		image := args[1]
		replicas, err := strconv.Atoi(args[2])
		name := args[3]
		if err != nil {
			log.Fatalf("Error parsing replicas: %#v", err)
		}
		err = cloudcfg.RunController(image, name, replicas, kube_client.Client{Host: *httpServer, Auth: &auth}, *portSpec, *servicePort)
		if err != nil {
			log.Fatalf("Error: %#v", err)
		}
		return
	case "stop":
		err = cloudcfg.StopController(flag.Arg(1), kube_client.Client{Host: *httpServer, Auth: &auth})
		if err != nil {
			log.Fatalf("Error: %#v", err)
		}
		return
	case "rm":
		err = cloudcfg.DeleteController(flag.Arg(1), kube_client.Client{Host: *httpServer, Auth: &auth})
		if err != nil {
			log.Fatalf("Error: %#v", err)
		}
		return
	default:
		log.Fatalf("Unknown command: %s", method)
	}
	if err != nil {
		log.Fatalf("Error: %#v", err)
	}
	var body string
	body, err = cloudcfg.DoRequest(request, auth.User, auth.Password)
	if err != nil {
		log.Fatalf("Error: %#v", err)
	}
	err = printer.Print(body, os.Stdout)
	if err != nil {
		log.Fatalf("Failed to print: %#v", err)
	}
	fmt.Print("\n")
}


text:
Ext.define('User.Form',{
	extend: 'Ext.form.Panel',
	alias: 'widget.userform',

	/**
	 * Хранилище компаний для поля выбора
	 * @private
	 */
	storeCompany: null,

	initComponent: function() {

		var me = this;

		me.storeCompany = Ext.create('Ext.data.Store',{
			model: 'Organization',
			proxy: {
				type: 'ajax',
				api: {
					read: Routing.generate('directoryOrganizationIndex')
				},
				reader: {
					type: 'json',
					root: 'items'
				}
			},
			autoLoad: true
		});

		Ext.apply(this,{
			bodyPadding: 10,
			activeRecord: null,
			defaultType: 'textfield',
			border: false,
			submitEmptyText: false,
			items: [{
				fieldLabel: 'Ф.И.О.',
				name: 'name',
				labelStyle: 'font-weight: bold;',
				allowBlank: false,
				blankText: 'Поле не может быть пустым'
			},{
				fieldLabel: 'Логин',
				name: 'username',
                itemId: 'user_login',
				labelStyle: 'font-weight: bold;',
				allowBlank: false,
				blankText: 'Поле не может быть пустым, а значит, должно быть уникальным, так как это идентификатор при авторизации.'
			},{
				fieldLabel: 'Пароль',
				itemId: 'user-password',
				name: 'password',
				labelStyle: 'font-weight: bold;',
				inputType: 'password',
                blankText: 'Поле не может быть пустым'
			},{
				xtype: 'fieldcontainer',
                allowBlank: false,
				defaultType: 'radiofield',
				itemId: 'user_role',
				fieldLabel: 'Роль',
				name: 'role_id',
				labelStyle: 'font-weight: bold;'
			},{
				xtype: 'combo',
				fieldLabel: 'Организация',
				name: 'organization_id',
				itemId: 'user-organization',
				store: me.storeCompany,
				displayField: 'name',
				valueField: 'id',
				allowBlank: false,
				blankText: 'Поле не может быть пустым',
				labelStyle: 'font-weight: bold;',
				emptyText: 'Выберите организацию',
				queryMode: 'local',
                triggerAction: 'all',
                enableKeyEvents: true,
                forceSelection:true,
                listeners: {
                    keyup: function() {
                        this.store.filter('name', this.getRawValue(), true, false);
                    }
                }
			},{
				fieldLabel: 'Должность',
				name: 'post',
				labelStyle: 'font-weight: bold;'
			},{
				fieldLabel: 'Email',
				name: 'email',
				labelStyle: 'font-weight: bold;',
				vtype: 'email',
				vtypeText: 'Не верный формат email. Пример верного: user@example.com'
			},{
				fieldLabel: 'Телефон',
				name: 'phone',
				labelStyle: 'font-weight: bold;',
				vtype: 'Phone'
			},{
				fieldLabel: 'Собственный телефон',
				name: 'own_phone',
				labelStyle: 'font-weight: bold;',
				vtype: 'Phone'
			},{
				xtype: 'htmleditor',
				fieldLabel: 'Примечание',
				name: 'note',
				labelStyle: 'font-weight: bold;',
				enableFont: false,
				enableFontSize: false,
				enableColors: false,
				enableAlignments: false,
				enableSourceEdit: false,
				width: 300,
				enableLists: false
			}]
		});

		this.callParent(arguments);
	},

	setAllowBlankField: function(field, allowBlank) {
		Ext.apply(this.down('#' + field),{
			allowBlank: allowBlank
		});
	},

	setActiveRecord: function(record) {
		var me = this;

		me.activeRecord = record;

		if(record) {

			var comboStore = this.down('#user-organization').getStore();

			comboStore.on("load",function() {
				me.getForm().loadRecord(record);
			});

			comboStore.load();
		}
	}
});


text:
#ifndef __SPRITE_CCSPRITE_FRAME_CACHE_H__
#define __SPRITE_CCSPRITE_FRAME_CACHE_H__

/*
 * To create sprite frames and texture atlas, use this tool:
 * http://zwoptex.zwopple.com/
 */

#include "sprite_nodes/CCSpriteFrame.h"
#include "textures/CCTexture2D.h"
#include "cocoa/CCObject.h"
#include <set>
#include <string>

NS_CC_BEGIN

class CCDictionary;
class CCArray;
class CCSprite;

/**
 * @addtogroup sprite_nodes
 * @{
 */

/** @brief Singleton that handles the loading of the sprite frames.
 It saves in a cache the sprite frames.
 @since v0.9
 */
class CC_DLL CCSpriteFrameCache : public CCObject
{
public:
    bool init(void);
    ~CCSpriteFrameCache(void);

private:
    /*Adds multiple Sprite Frames with a dictionary. The texture will be associated with the created sprite frames.
     */
    void addSpriteFramesWithDictionary(CCDictionary* pobDictionary, CCTexture2D *pobTexture);
public:
    /** Adds multiple Sprite Frames from a plist file.
     * A texture will be loaded automatically. The texture name will composed by replacing the .plist suffix with .png
     * If you want to use another texture, you should use the addSpriteFramesWithFile:texture method.
     */
    void addSpriteFramesWithFile(const char *pszPlist);

    /** Adds multiple Sprite Frames from a plist file. The texture will be associated with the created sprite frames.
    @since v0.99.5
    */
    void addSpriteFramesWithFile(const char* plist, const char* textureFileName);

    /** Adds multiple Sprite Frames from a plist file. The texture will be associated with the created sprite frames. */
    void addSpriteFramesWithFile(const char *pszPlist, CCTexture2D *pobTexture);

    /** Adds an sprite frame with a given name.
     If the name already exists, then the contents of the old name will be replaced with the new one.
     */
    void addSpriteFrame(CCSpriteFrame *pobFrame, const char *pszFrameName);

    /** Purges the dictionary of loaded sprite frames.
     * Call this method if you receive the "Memory Warning".
     * In the short term: it will free some resources preventing your app from being killed.
     * In the medium term: it will allocate more resources.
     * In the long term: it will be the same.
     */
    void removeSpriteFrames(void);

    /** Removes unused sprite frames.
     * Sprite Frames that have a retain count of 1 will be deleted.
     * It is convenient to call this method after when starting a new Scene.
     */
    void removeUnusedSpriteFrames(void);

    /** Deletes an sprite frame from the sprite frame cache. */
    void removeSpriteFrameByName(const char *pszName);

    /** Removes multiple Sprite Frames from a plist file.
    * Sprite Frames stored in this file will be removed.
    * It is convenient to call this method when a specific texture needs to be removed.
    * @since v0.99.5
    */
    void removeSpriteFramesFromFile(const char* plist);

private:
    /** Removes multiple Sprite Frames from CCDictionary.
    * @since v0.99.5
    */
    void removeSpriteFramesFromDictionary(CCDictionary* dictionary);
public:
    /** Removes all Sprite Frames associated with the specified textures.
    * It is convenient to call this method when a specific texture needs to be removed.
    * @since v0.995.
    */
    void removeSpriteFramesFromTexture(CCTexture2D* texture);

    /** Returns an Sprite Frame that was previously added.
     If the name is not found it will return nil.
     You should retain the returned copy if you are going to use it.
     */
    CCSpriteFrame* spriteFrameByName(const char *pszName);

public:
    /** Returns the shared instance of the Sprite Frame cache */
    static CCSpriteFrameCache* sharedSpriteFrameCache(void);

    /** Purges the cache. It releases all the Sprite Frames and the retained instance. */
    static void purgeSharedSpriteFrameCache(void);

private:
    CCSpriteFrameCache(void) : m_pSpriteFrames(NULL), m_pSpriteFramesAliases(NULL){}
protected:
    CCDictionary* m_pSpriteFrames;
    CCDictionary* m_pSpriteFramesAliases;
    std::set<std::string>*  m_pLoadedFileNames;
};

// end of sprite_nodes group
/// @}

NS_CC_END

#endif // __SPRITE_CCSPRITE_FRAME_CACHE_H__


text:
<?php

use Phinx\Migration\AbstractMigration;

class AddGithubUsername extends AbstractMigration
{
    /**
     * Change Method.
     *
     * More information on this method is available here:
     * http://docs.phinx.org/en/latest/migrations.html#the-change-method
     *
     * Uncomment this method if you would like to use it.
     *
    public function change()
    {
    }
    */

    /**
     * Migrate Up.
     */
    public function up()
    {
        $users = $this->table('users');

        $users->addColumn('githubName', 'text', ['null' => true])->update();
    }

    /**
     * Migrate Down.
     */
    public function down()
    {
        $users = $this->table('users');

        $users->removeColumn('githubName');

    }
}


text:
import {findLastIndex} from 'rambda'

const list = [1, 2, 3]

describe('R.findLastIndex', () => {
  it('happy', () => {
    const predicate = (x: number) => x > 2
    const result = findLastIndex(predicate, list)
    result // $ExpectType number
  })
  it('curried', () => {
    const predicate = (x: number) => x > 2
    const result = findLastIndex(predicate)(list)
    result // $ExpectType number
  })
})


text:
import React, { Component } from "react";
import ItemMenu from "../firstLevelComponent/ItemMenu";

export default class Menu extends Component {

	render(){

		let menuItems = [];
		let menu = this.props.menu;
		let name, url;

		Object.keys(menu).forEach(function(index) {
			name = menu[index]["name"];
			url = menu[index]["url"];

			menuItems.push(<ItemMenu key={index} text={name} url={url} />);
		});

		return (

				        {menuItems}

		);
	}
}


text:
package session

import (
	"time"

	"errors"

	impact "github.com/impactasaurus/server"
	"github.com/impactasaurus/server/auth"
	"github.com/impactasaurus/server/data"
	"github.com/impactasaurus/server/log"
	"github.com/satori/go.uuid"
	"gopkg.in/mgo.v2"
)

type export struct {
	ID      string `bson:"_id"`
	Data    *impact.Export
	TTL     time.Duration
	Created time.Time
	User    string
}

func (s *S) SaveExport(e *impact.Export, ttl time.Duration, u auth.User) (string, error) {
	id := uuid.NewV4().String()
	if err := s.collection(exports).Insert(export{
		ID:      id,
		Data:    e,
		TTL:     ttl,
		Created: time.Now(),
		User:    u.UserID(),
	}); err != nil {
		return "", err
	}

	return id, nil
}

func (s *S) removeExport(id string) {
	if err := s.collection(exports).RemoveId(id); err != nil {
		log.Error(errors.New("failed to delete export"), map[string]string{
			"id":  id,
			"err": err.Error(),
		})
	}
}

func (s *S) GetExport(id string) (*impact.Export, error) {
	e := export{}
	err := s.collection(exports).FindId(id).One(&e)
	if err != nil {
		if mgo.ErrNotFound == err {
			return nil, data.NewNotFoundError("export")
		}
		return nil, err
	}

	if time.Now().After(e.Created.Add(e.TTL)) {
		return nil, data.NewExpiredError("export")
	}

	s.removeExport(id)

	return e.Data, nil
}


text:
namespace image
{
namespace sse3
{
void assign_value( scanline &dest, float v );
void add_planeplane(
    scanline &dest, const scanline &srcA, const scanline &srcB );
void add_planenumber( scanline &dest, const scanline &srcA, float v );

void sub_planeplane(
    scanline &dest, const scanline &srcA, const scanline &srcB );

void mul_planeplane(
    scanline &dest, const scanline &srcA, const scanline &srcB );
void mul_planenumber( scanline &dest, const scanline &srcA, float v );

void div_planeplane(
    scanline &dest, const scanline &srcA, const scanline &srcB );

void div_numberplane( scanline &dest, float v, const scanline &src );

void muladd_planeplaneplane(
    scanline &      dest,
    const scanline &srcA,
    const scanline &srcB,
    const scanline &srcC );

void muladd_planenumbernumber(
    scanline &dest, const scanline &src, float a, float b );

} // namespace sse3

} // namespace image


text:
/**
 * www.TheAIGames.com
 * Heads Up Omaha pokerbot
 *
 * Last update: May 07, 2014
 *
 * @author Jim van Eeden, Starapple
 * @version 1.0
 * @License MIT License (http://opensource.org/Licenses/MIT)
 */

package poker;

/**
 * Class that represents the action of a bot.
 */
public class PokerMove {

	String player = null;
	String action = null;
	int amount;

	public PokerMove(String botName, String act, int amt)
	{
		player = botName;
		action = act;
		amount = amt;
	}

	public String getPlayer()
	{
		return player;
	}

	public String getAction()
	{
		return action;
	}

	public int getAmount()
	{
		return amount;
	}

	/**
	 * Returns a string representation of the move as a sentence of two words, being the action
	 * string and the action amount. Returning the player name to the engine is not needed
	 */
	public String toString() {
		return String.format("%s %d", action, amount);
	}

}


text:
/**
 * Swaggy Jenkins
 * Jenkins API clients generated from Swagger / Open API specification
 *
 * OpenAPI spec version: 1.5.1-pre.0
 * Contact: blah@cliffano.com
 *
 * NOTE: This class is auto generated by OpenAPI Generator
 * https://github.com/OpenAPITools/openapi-generator
 * Do not edit the class manually.
 */

#include "OpenAPIFreeStyleProject.h"

#include "OpenAPIModule.h"
#include "OpenAPIHelpers.h"

#include "Templates/SharedPointer.h"

namespace OpenAPI
{

void OpenAPIFreeStyleProject::WriteJson(JsonWriter& Writer) const
{
	Writer->WriteObjectStart();
	if (_Class.IsSet())
	{
		Writer->WriteIdentifierPrefix(TEXT("_class")); WriteJsonValue(Writer, _Class.GetValue());
	}
	if (Name.IsSet())
	{
		Writer->WriteIdentifierPrefix(TEXT("name")); WriteJsonValue(Writer, Name.GetValue());
	}
	if (Url.IsSet())
	{
		Writer->WriteIdentifierPrefix(TEXT("url")); WriteJsonValue(Writer, Url.GetValue());
	}
	if (Color.IsSet())
	{
		Writer->WriteIdentifierPrefix(TEXT("color")); WriteJsonValue(Writer, Color.GetValue());
	}
	if (Actions.IsSet())
	{
		Writer->WriteIdentifierPrefix(TEXT("actions")); WriteJsonValue(Writer, Actions.GetValue());
	}
	if (Description.IsSet())
	{
		Writer->WriteIdentifierPrefix(TEXT("description")); WriteJsonValue(Writer, Description.GetValue());
	}
	if (DisplayName.IsSet())
	{
		Writer->WriteIdentifierPrefix(TEXT("displayName")); WriteJsonValue(Writer, DisplayName.GetValue());
	}
	if (DisplayNameOrNull.IsSet())
	{
		Writer->WriteIdentifierPrefix(TEXT("displayNameOrNull")); WriteJsonValue(Writer, DisplayNameOrNull.GetValue());
	}
	if (FullDisplayName.IsSet())
	{
		Writer->WriteIdentifierPrefix(TEXT("fullDisplayName")); WriteJsonValue(Writer, FullDisplayName.GetValue());
	}
	if (FullName.IsSet())
	{
		Writer->WriteIdentifierPrefix(TEXT("fullName")); WriteJsonValue(Writer, FullName.GetValue());
	}
	if (Buildable.IsSet())
	{
		Writer->WriteIdentifierPrefix(TEXT("buildable")); WriteJsonValue(Writer, Buildable.GetValue());
	}
	if (Builds.IsSet())
	{
		Writer->WriteIdentifierPrefix(TEXT("builds")); WriteJsonValue(Writer, Builds.GetValue());
	}
	if (FirstBuild.IsSet())
	{
		Writer->WriteIdentifierPrefix(TEXT("firstBuild")); WriteJsonValue(Writer, FirstBuild.GetValue());
	}
	if (HealthReport.IsSet())
	{
		Writer->WriteIdentifierPrefix(TEXT("healthReport")); WriteJsonValue(Writer, HealthReport.GetValue());
	}
	if (InQueue.IsSet())
	{
		Writer->WriteIdentifierPrefix(TEXT("inQueue")); WriteJsonValue(Writer, InQueue.GetValue());
	}
	if (KeepDependencies.IsSet())
	{
		Writer->WriteIdentifierPrefix(TEXT("keepDependencies")); WriteJsonValue(Writer, KeepDependencies.GetValue());
	}
	if (LastBuild.IsSet())
	{
		Writer->WriteIdentifierPrefix(TEXT("lastBuild")); WriteJsonValue(Writer, LastBuild.GetValue());
	}
	if (LastCompletedBuild.IsSet())
	{
		Writer->WriteIdentifierPrefix(TEXT("lastCompletedBuild")); WriteJsonValue(Writer, LastCompletedBuild.GetValue());
	}
	if (LastFailedBuild.IsSet())
	{
		Writer->WriteIdentifierPrefix(TEXT("lastFailedBuild")); WriteJsonValue(Writer, LastFailedBuild.GetValue());
	}
	if (LastStableBuild.IsSet())
	{
		Writer->WriteIdentifierPrefix(TEXT("lastStableBuild")); WriteJsonValue(Writer, LastStableBuild.GetValue());
	}
	if (LastSuccessfulBuild.IsSet())
	{
		Writer->WriteIdentifierPrefix(TEXT("lastSuccessfulBuild")); WriteJsonValue(Writer, LastSuccessfulBuild.GetValue());
	}
	if (LastUnstableBuild.IsSet())
	{
		Writer->WriteIdentifierPrefix(TEXT("lastUnstableBuild")); WriteJsonValue(Writer, LastUnstableBuild.GetValue());
	}
	if (LastUnsuccessfulBuild.IsSet())
	{
		Writer->WriteIdentifierPrefix(TEXT("lastUnsuccessfulBuild")); WriteJsonValue(Writer, LastUnsuccessfulBuild.GetValue());
	}
	if (NextBuildNumber.IsSet())
	{
		Writer->WriteIdentifierPrefix(TEXT("nextBuildNumber")); WriteJsonValue(Writer, NextBuildNumber.GetValue());
	}
	if (QueueItem.IsSet())
	{
		Writer->WriteIdentifierPrefix(TEXT("queueItem")); WriteJsonValue(Writer, QueueItem.GetValue());
	}
	if (ConcurrentBuild.IsSet())
	{
		Writer->WriteIdentifierPrefix(TEXT("concurrentBuild")); WriteJsonValue(Writer, ConcurrentBuild.GetValue());
	}
	if (Scm.IsSet())
	{
		Writer->WriteIdentifierPrefix(TEXT("scm")); WriteJsonValue(Writer, Scm.GetValue());
	}
	Writer->WriteObjectEnd();
}

bool OpenAPIFreeStyleProject::FromJson(const TSharedPtr<FJsonValue>& JsonValue)
{
	const TSharedPtr<FJsonObject>* Object;
	if (!JsonValue->TryGetObject(Object))
		return false;

	bool ParseSuccess = true;

	ParseSuccess &= TryGetJsonValue(*Object, TEXT("_class"), _Class);
	ParseSuccess &= TryGetJsonValue(*Object, TEXT("name"), Name);
	ParseSuccess &= TryGetJsonValue(*Object, TEXT("url"), Url);
	ParseSuccess &= TryGetJsonValue(*Object, TEXT("color"), Color);
	ParseSuccess &= TryGetJsonValue(*Object, TEXT("actions"), Actions);
	ParseSuccess &= TryGetJsonValue(*Object, TEXT("description"), Description);
	ParseSuccess &= TryGetJsonValue(*Object, TEXT("displayName"), DisplayName);
	ParseSuccess &= TryGetJsonValue(*Object, TEXT("displayNameOrNull"), DisplayNameOrNull);
	ParseSuccess &= TryGetJsonValue(*Object, TEXT("fullDisplayName"), FullDisplayName);
	ParseSuccess &= TryGetJsonValue(*Object, TEXT("fullName"), FullName);
	ParseSuccess &= TryGetJsonValue(*Object, TEXT("buildable"), Buildable);
	ParseSuccess &= TryGetJsonValue(*Object, TEXT("builds"), Builds);
	ParseSuccess &= TryGetJsonValue(*Object, TEXT("firstBuild"), FirstBuild);
	ParseSuccess &= TryGetJsonValue(*Object, TEXT("healthReport"), HealthReport);
	ParseSuccess &= TryGetJsonValue(*Object, TEXT("inQueue"), InQueue);
	ParseSuccess &= TryGetJsonValue(*Object, TEXT("keepDependencies"), KeepDependencies);
	ParseSuccess &= TryGetJsonValue(*Object, TEXT("lastBuild"), LastBuild);
	ParseSuccess &= TryGetJsonValue(*Object, TEXT("lastCompletedBuild"), LastCompletedBuild);
	ParseSuccess &= TryGetJsonValue(*Object, TEXT("lastFailedBuild"), LastFailedBuild);
	ParseSuccess &= TryGetJsonValue(*Object, TEXT("lastStableBuild"), LastStableBuild);
	ParseSuccess &= TryGetJsonValue(*Object, TEXT("lastSuccessfulBuild"), LastSuccessfulBuild);
	ParseSuccess &= TryGetJsonValue(*Object, TEXT("lastUnstableBuild"), LastUnstableBuild);
	ParseSuccess &= TryGetJsonValue(*Object, TEXT("lastUnsuccessfulBuild"), LastUnsuccessfulBuild);
	ParseSuccess &= TryGetJsonValue(*Object, TEXT("nextBuildNumber"), NextBuildNumber);
	ParseSuccess &= TryGetJsonValue(*Object, TEXT("queueItem"), QueueItem);
	ParseSuccess &= TryGetJsonValue(*Object, TEXT("concurrentBuild"), ConcurrentBuild);
	ParseSuccess &= TryGetJsonValue(*Object, TEXT("scm"), Scm);

	return ParseSuccess;
}

}


text:
from setuptools import setup, find_packages

from Raitonoberu import (
    __version__ as version,
    __author__ as author,
    __license__ as license,
    __title__ as title
)

setup(
    name=title,
    version=version,
    packages=find_packages(),
    url='https://github.com/GetRektByMe/Raitonoberu',
    license=license,
    author=author,
    author_email='',
    description='Python 3 asynchronous novelupdates scraper',
    long_description="Raitonoberu is a Python 3 Asyncio NovelUpdates Website scraper that is capable of getting useful information for use in applications.",
    classifiers=[
        'Development Status :: 4 - Beta',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Programming Language :: Python :: 3.5',
        'Programming Language :: Python :: 3 :: Only',
        'Topic :: Software Development :: Libraries'
    ],
    keywords=["NovelUpdates", "asyncio", "aiohttp", "scraping"],
    install_requires=['aiohttp', 'bs4', 'lxml'],
)


text:
<?php

/** ensure this file is being included by a parent file */
defined( '_JEXEC' ) or die( 'Restricted access' );

JFactory::getApplication()->input->set('hidemainmenu', 1);

/** @var $gantry Gantry */
		global $gantry;

JHtml::_('behavior.keepalive');
$user = JFactory::getUser();
$canDo = $this->getActions();
$isNew = ($this->item->id == 0);

require_once(JPATH_LIBRARIES."/gantry/gantry.php");

gantry_import('core.config.gantryform');
gantry_import('core.config.gantryformnaminghelper');

$gantryForm = $this->gantryForm;
$fieldSets = $gantryForm->getFieldsets();

//$gantry->addStyle($gantry->gantryUrl."/admin/widgets/gantry-administrator.css");
$this->compileLess();
define('GANTRY_CSS', 1);

$gantry->addScript($gantry->gantryUrl."/admin/widgets/moofx.js");
$gantry->addScript($gantry->gantryUrl."/admin/widgets/Twipsy.js");
$gantry->addScript($gantry->gantryUrl."/admin/widgets/gantry.js");
$gantry->addScript($gantry->gantryUrl."/admin/widgets/gantry.popupbuttons.js");
$gantry->addScript($gantry->gantryUrl . '/admin/widgets/ajaxbutton/js/ajaxbutton.js');
$gantry->addScript($gantry->gantryUrl."/admin/widgets/growl.js");
if ($this->override) $gantry->addScript($gantry->gantryUrl."/admin/widgets/assignments/js/assignments.js");
$gantry->addInlineScript("var GantryIsMaster = ".(($this->override) ? 'false' : 'true').";");

function gantry_admin_render_menu($view, $item)
{
	$user = JFactory::getUser();
	$canDo = $view->getActions();
	$isNew = ($item->id == 0);
	ob_start();
	?>

Save</div

Save & Close

						<?php if (!$isNew && $canDo->get('core.create')):?>

Save as Copy

						<?php endif; ?>

Save Preset

Presets

Clear Cache

Close

	<?php
	$buffer = ob_get_clean();
	return $buffer;
}

function gantry_admin_render_edit_item($element)
{
	if ($element->type == 'tips' && (isset($element->element['tab']) && (string) $element->element['tab'] != 'overview')) return $element->getInput();

	$buffer = '';
	$buffer .= "
type . "-field g4-row\">\n";
	$label = '';
	if ($element->show_label) $label = $element->getLabel() . "\n";
	$buffer .= "
\n";
	$buffer .= $label;
	$buffer .= "
";
	$buffer .= "

\n";
	$buffer .= "";
	$buffer .= $element->getInput() . "\n";
	$buffer .= "

\n";
	$buffer .= "
\n";
	return $buffer;
}

function  gantry_admin_render_edit_override_item($element)
{
	if ($element->type == 'tips' && (isset($element->element['tab']) && (string) $element->element['tab'] != 'overview')) return $element->getInput();

	$buffer = "";
	$buffer .= "
type . "-field g4-row\">\n";
	$label = '';
	$checked = ($element->variance) ? ' checked="checked"' : '';
	if ($element->show_label){
		if (!$element->setinoverride) $label = $element->getLabel() . "\n";
		else $label = '
<input  name="overridden-' . $element->name . '" type="checkbox"' . $checked . '/>' . $element->getLabel() . '
';
	}
	$buffer .= "
\n";
	$buffer .= $label;
	$buffer .= "
";
	$buffer .= "

\n";
	$buffer .= "";
	$buffer .= $element->getInput() . "\n";
	$buffer .= "

\n";
	$buffer .= "
\n";
	return $buffer;
}

function get_badges_layout($name, $override=0, $involved=0, $assignments=0) {
	if ($name == 'assignment'){
		return ''.$assignments.'';
	} else {
		if ($override) {
			return '
				'."\n".'
				 0 '."\n".'
				 '.$involved.''."\n".'
			';
		} else {
			return '0';
		}
	}
}

function get_version_update_info(){

	$buffer = '';
	gantry_import('core.gantryupdates');
	$gantry_updates = GantryUpdates::getInstance();
	$currentVersion =  $gantry_updates->getCurrentVersion();
	$latest_version = $gantry_updates->getLatestVersion();

	if (version_compare($latest_version,$currentVersion,'>')){
		$klass="update";
		$upd = JText::sprintf('COM_GANTRY_VERSION_UPDATE_OUTOFDATE',$latest_version,'index.php?option=com_installer&view=update');
	} else {
		$klass = "noupdate";
		jimport('joomla.utilities.date');
		$nextupdate = new JDate($gantry_updates->getLastUpdated()+(24*60*60));

		$upd = JText::sprintf('COM_GANTRY_VERSION_UPDATE_CURRENT');
	}

	$buffer .= "

Gantry v".$currentVersion."

".$upd."

";

	return $buffer;
}

$this->gantryForm->initialize();
?>

<div class="g4-wrap <?php echo (!$this->override) ? 'defaults-wrap' : 'override-wrap'; ?>">
	<?php if(!$this->override):?>

<?php endif;?>

Templates Manager / Edit Style

		<?php echo gantry_admin_render_menu($this, $this->item); ?>

	<form action="<?php echo JRoute::_('index.php?option=com_gantry&layout=edit&id='.(int) $this->item->id); ?>" method="post" name="adminForm" id="adminForm" class="form-validate">
		<?php echo $this->form->getInput('client_id'); ?>

			<?php if ($this->item->id) : ?>
				<?php echo $this->form->getInput('id'); ?>
			<?php endif; ?>

		<?php
			$status = JFactory::getApplication()->input->cookie->getString('gantry-'.$gantry->templateName.'-adminpresets','hide');
			$presetsShowing = ($status == 'hide') ? "" : ' class="presets-showing"';

			if ($this->override) {
				$flag = "g4-flag-override";
				$flag_text = "Override";
			} else {
				$flag = "g4-flag-master";
				$flag_text = "✭ Master";
			}
		?>

			<div id="g4-master" class="<?php echo $flag; ?> g4-size-13">

					<?php echo $flag_text; ?>

			<div id="g4-details"<?php echo $presetsShowing; ?>>

				<fieldset class="adminform g4-horizontal-form">

						<?php echo $this->form->getLabel('title'); ?>

							<?php echo $this->form->getInput('title'); ?>

						<?php echo $this->form->getLabel('template'); ?>

							<?php echo $this->form->getInput('template'); ?>

						<?php echo $this->form->getLabel('home'); ?>

							<?php echo $this->form->getInput('home'); ?>

				</fieldset>

			<?php echo $this->loadTemplate('presets'); ?>

			<?php //settings_fields('theme-options-array'); ?>

								<?php
									$panels = array();
									$positions = array(
										'hiddens' => array(),
										'top' => array(),
										'left' => array(),
										'right' => array(),
										'bottom' => array()
									);

									$involvedCounts = array();
									foreach ($fieldSets as $name => $fieldSet) {
										if ($name == 'toolbar-panel') continue;
										$fields = $gantryForm->getFullFieldset($name);
										$involved = 0;
										if ($name == 'assignment' && (!$user->authorise('core.edit', 'com_menu') || !$canDo->get('core.edit.state'))) continue;
										array_push($panels, array("name" => $name, "height" => (isset($fieldSet->height))?$fieldSet->height:null));
										foreach($fields as $fname => $field) {
											$position = $field->panel_position;

											if ($field->type != 'hidden' && $field->setinoverride && $field->variance) $involved++;
											if ($field->type == 'hidden') $position = 'hiddens';
											if (!isset($positions[$position][$name])) $positions[$position][$name] = array();
											array_push(
												$positions[$position][$name],
												$field
												//array("name" => $field->name, "label" => $field->label, "input" => $field->input, "show_label" => $field->show_label, 'type' => $field->type)
											);
										}
										$involvedCounts[$name] = $involved;
									}

									foreach ($fieldSets as $name => $fieldSet):
										if ($name == 'toolbar-panel') continue;
										if ($name == 'assignment' && (!$user->authorise('core.edit', 'com_menu') || !$canDo->get('core.edit.state'))) continue;
										?>
										<li class="<?php echo $this->tabs[$name];?>">
											<?php echo get_badges_layout($name, $this->override, $involvedCounts[$name], $this->assignmentCount);?>
											<?php echo JText::_($fieldSet->label);?>

									<?php endforeach;?>

					<?php
						$output = "";
						$output .= "
\n";
						if (count($panels) > 0)
						{
							for($i = 0; $i < count($panels); $i++) {
								$panel = $panels[$i]['name'];
								if ($panel == 'assignment' && (!$user->authorise('core.edit', 'com_menu') || !$canDo->get('core.edit.state'))) continue;
								$width = '';
								if ((@count($positions['left'][$panels[$i]['name']]) && !@count($positions['right'][$panels[$i]['name']])) || (!@count($positions['left'][$panels[$i]['name']]) && @count($positions['right'][$panels[$i]['name']]))) {
									$width = 'width-100pc';
								}

								$activePanel = "";
								if ($i == $this->activeTab - 1) $activePanel = " active-panel";
								else $activePanel = "";

								$output .= "
\n";

								$buffer = "";
								foreach($positions as $name => $position) {

									if (isset($positions[$name][$panel])) {
										// hide right panels in Gantry4 for all but overview tab
										if (!($name == "right" && $panel != "overview")) {
											$buffer .= "
\n";
											$panel_name = $name == 'left' ? 'panelform' : 'paneldesc';

											$buffer .= "
\n";

											if ($panel_name == 'paneldesc' && $panel == 'overview') {
												$buffer .= get_version_update_info();

											}
											foreach($positions[$name][$panel] as $element) {
												if (!$this->override){
													$buffer .= $element->render('gantry_admin_render_edit_item');
												}
												else{
													$buffer .= $element->render('gantry_admin_render_edit_override_item');
												}
											}

											$buffer .= "
\n";
											$buffer .= "
\n";
										}

										if ($panel != 'overview' && $name == 'right'){
											foreach($positions[$name][$panel] as $element) {
												if (get_class($element) != 'GantryFormFieldTips') continue;

												if (!$this->override){
													$buffer .= $element->render('gantry_admin_render_edit_item');
												}
												else{
													$buffer .= $element->render('gantry_admin_render_edit_override_item');
												}
											}
										}
									}
								}
								$output .= $buffer;

								$output .= "
";
							}
						}
						$output .= "
\n";
						echo $output;
						?>

				<input type="hidden" name="task" value="" />
				<?php echo JHtml::_('form.token'); ?>

		</form>

<?php
 // css overrides
	if ($gantry->browser->name == 'ie' && file_exists($gantry->gantryPath . '/' . 'admin' . '/' . 'widgets' . '/' . 'gantry-ie.css')) {
		$gantry->addStyle($gantry->gantryUrl . '/admin/widgets/gantry-ie.css');
	}
	if ($gantry->browser->name == 'ie' && $gantry->browser->version == '7' && file_exists($gantry->gantryPath . '/' . 'admin' . '/' . 'widgets' . '/' . 'gantry-ie7.css')) {
		$gantry->addStyle($gantry->gantryUrl . '/admin/widgets/gantry-ie7.css');
	}

	if (($gantry->browser->name == 'firefox' && $gantry->browser->version < '3.7') || ($gantry->browser->name == 'ie' && $gantry->browser->version > '6')) {
		$css = ".text-short, .text-medium, .text-long, .text-color {padding-top: 4px;height:19px;}";
		$gantry->addInlineStyle($css);
	}

	if ($gantry->browser->name == 'ie' && $gantry->browser->shortversion == '7') {
		$css = "
			.g-surround, .g-inner, .g-surround > div {zoom: 1;position: relative;}
			.text-short, .text-medium, .text-long, .text-color {border:0 !important;}
			.selectbox {z-index:500;position:relative;}
			.group-fusionmenu, .group-splitmenu {position:relative;margin-top:0 !important;zoom:1;}
			.scroller .inner {position:relative;}
			.moor-hexLabel {display:inline-block;zoom:1;float:left;}
			.moor-hexLabel input {float:left;}
		";
		$gantry->addInlineStyle($css);
	}
	if ($gantry->browser->name == 'opera' && file_exists($gantry->gantryPath . '/' . 'admin' . '/' . 'widgets' . '/' . 'gantry-opera.css')) {
		$gantry->addStyle($gantry->gantryUrl . '/admin/widgets/gantry-opera.css');
	}

	$this->gantryForm->finalize();
	$gantry->finalize();


text:
package io.machinecode.chainlink.core.transport;

import io.machinecode.chainlink.core.management.JobOperatorImpl;
import io.machinecode.chainlink.core.registry.UUIDId;
import io.machinecode.chainlink.core.repository.RepositoryTest;
import io.machinecode.chainlink.core.transport.artifacts.TestTransport;
import io.machinecode.chainlink.spi.configuration.Dependencies;
import io.machinecode.chainlink.spi.configuration.JobOperatorModel;
import io.machinecode.chainlink.spi.configuration.factory.TransportFactory;
import io.machinecode.chainlink.spi.property.PropertyLookup;
import io.machinecode.chainlink.spi.registry.RepositoryId;
import io.machinecode.chainlink.spi.repository.Repository;
import io.machinecode.chainlink.spi.transport.Transport;
import org.junit.Before;

import java.util.Collections;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * @author Brent Douglas
 * @since 1.0
 */
public class DistributedRepositoryTest extends RepositoryTest {

    private static final ConcurrentMap<String, TestTransport> transports = new ConcurrentHashMap<>();

    private Repository repo;

    @Override
    protected void visitJobOperatorModel(final JobOperatorModel model) throws Exception {
        model.getTransport().setFactory(new TransportFactory() {
            @Override
            public Transport produce(final Dependencies dependencies, final PropertyLookup properties) throws Exception {
                final TestTransport transport = new TestTransport(transports, "first", Collections.<String>emptyList(), dependencies, properties);
                transports.put("first", transport);
                return transport;
            }
        });
    }

    @Before
    public void before() throws Exception {
        final JobOperatorImpl operator = new JobOperatorImpl(configuration());
        operator.open(configuration());
    }

    public Repository repository() throws Exception {
        if (repo == null) {
            final Transport transport = configuration().getTransport();
            final RepositoryId id = new UUIDId(transport);
            _registry.registerRepository(id, _repository);
            repo = transport.getRepository(id);
        }
        return repo;
    }
}