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>
#include <limits.h>
#include "azure_c_shared_utility/optimize_size.h"
#include "azure_c_shared_utility/gballoc.h"
#include "azure_c_shared_utility/buffer_.h"
#include "azure_c_shared_utility/strings.h"
#include "azure_c_shared_utility/macro_utils.h"
#include "azure_c_shared_utility/xlogging.h"
#include "azure_umqtt_c/mqtt_codec.h"
#include <inttypes.h>

#define PAYLOAD_OFFSET                      5
#define PACKET_TYPE_BYTE(p)                 (CONTROL_PACKET_TYPE)((uint8_t)(((uint8_t)(p)) & 0xf0))
#define FLAG_VALUE_BYTE(p)                  ((uint8_t)(((uint8_t)(p)) & 0xf))

#define USERNAME_FLAG                       0x80
#define PASSWORD_FLAG                       0x40
#define WILL_RETAIN_FLAG                    0x20
#define WILL_QOS_FLAG_                      0x18
#define WILL_FLAG_FLAG                      0x04
#define CLEAN_SESSION_FLAG                  0x02

#define NEXT_128_CHUNK                      0x80
#define PUBLISH_DUP_FLAG                    0x8
#define PUBLISH_QOS_EXACTLY_ONCE            0x4
#define PUBLISH_QOS_AT_LEAST_ONCE           0x2
#define PUBLISH_QOS_RETAIN                  0x1

#define PROTOCOL_NUMBER                     4
#define CONN_FLAG_BYTE_OFFSET               7

#define CONNECT_FIXED_HEADER_SIZE           2
#define CONNECT_VARIABLE_HEADER_SIZE        10
#define SUBSCRIBE_FIXED_HEADER_FLAG         0x2
#define UNSUBSCRIBE_FIXED_HEADER_FLAG       0x2

#define MAX_SEND_SIZE                       0xFFFFFF7F

#define CODEC_STATE_VALUES      \
    CODEC_STATE_FIXED_HEADER,   \
    CODEC_STATE_VAR_HEADER,     \
    CODEC_STATE_PAYLOAD

static const char* const TRUE_CONST = "true";
static const char* const FALSE_CONST = "false";

DEFINE_ENUM(CODEC_STATE_RESULT, CODEC_STATE_VALUES);

typedef struct MQTTCODEC_INSTANCE_TAG
{
    CONTROL_PACKET_TYPE currPacket;
    CODEC_STATE_RESULT codecState;
    size_t bufferOffset;
    int headerFlags;
    BUFFER_HANDLE headerData;
    ON_PACKET_COMPLETE_CALLBACK packetComplete;
    void* callContext;
    uint8_t storeRemainLen[4];
    size_t remainLenIndex;
} MQTTCODEC_INSTANCE;

typedef struct PUBLISH_HEADER_INFO_TAG
{
    const char* topicName;
    uint16_t packetId;
    const char* msgBuffer;
    QOS_VALUE qualityOfServiceValue;
} PUBLISH_HEADER_INFO;

static const char* retrieve_qos_value(QOS_VALUE value)
{
    switch (value)
    {
        case DELIVER_AT_MOST_ONCE:
            return "DELIVER_AT_MOST_ONCE";
        case DELIVER_AT_LEAST_ONCE:
            return "DELIVER_AT_LEAST_ONCE";
        case DELIVER_EXACTLY_ONCE:
        default:
            return "DELIVER_EXACTLY_ONCE";
    }
}

static void byteutil_writeByte(uint8_t** buffer, uint8_t value)
{
    if (buffer != NULL)
    {
        **buffer = value;
        (*buffer)++;
    }
}

static void byteutil_writeInt(uint8_t** buffer, uint16_t value)
{
    if (buffer != NULL)
    {
        **buffer = (char)(value / 256);
        (*buffer)++;
        **buffer = (char)(value % 256);
        (*buffer)++;
    }
}

static void byteutil_writeUTF(uint8_t** buffer, const char* stringData, uint16_t len)
{
    if (buffer != NULL)
    {
        byteutil_writeInt(buffer, len);
        (void)memcpy(*buffer, stringData, len);
        *buffer += len;
    }
}

static CONTROL_PACKET_TYPE processControlPacketType(uint8_t pktByte, int* flags)
{
    CONTROL_PACKET_TYPE result;
    result = PACKET_TYPE_BYTE(pktByte);
    if (flags != NULL)
    {
        *flags = FLAG_VALUE_BYTE(pktByte);
    }
    return result;
}

static int addListItemsToUnsubscribePacket(BUFFER_HANDLE ctrlPacket, const char** payloadList, size_t payloadCount, STRING_HANDLE trace_log)
{
    int result = 0;
    if (payloadList == NULL || ctrlPacket == NULL)
    {
        result = __FAILURE__;
    }
    else
    {
        size_t index = 0;
        for (index = 0; index < payloadCount && result == 0; index++)
        {
            // Add the Payload
            size_t offsetLen = BUFFER_length(ctrlPacket);
            size_t topicLen = strlen(payloadList[index]);
            if (topicLen > USHRT_MAX)
            {
                result = __FAILURE__;
            }
            else if (BUFFER_enlarge(ctrlPacket, topicLen + 2) != 0)
            {
                result = __FAILURE__;
            }
            else
            {
                uint8_t* iterator = BUFFER_u_char(ctrlPacket);
                iterator += offsetLen;
                byteutil_writeUTF(&iterator, payloadList[index], (uint16_t)topicLen);
            }
            if (trace_log != NULL)
            {
                STRING_sprintf(trace_log, " | TOPIC_NAME: %s", payloadList[index]);
            }
        }
    }
    return result;
}

static int addListItemsToSubscribePacket(BUFFER_HANDLE ctrlPacket, SUBSCRIBE_PAYLOAD* payloadList, size_t payloadCount, STRING_HANDLE trace_log)
{
    int result = 0;
    if (payloadList == NULL || ctrlPacket == NULL)
    {
        result = __FAILURE__;
    }
    else
    {
        size_t index = 0;
        for (index = 0; index < payloadCount && result == 0; index++)
        {
            // Add the Payload
            size_t offsetLen = BUFFER_length(ctrlPacket);
            size_t topicLen = strlen(payloadList[index].subscribeTopic);
            if (topicLen > USHRT_MAX)
            {
                result = __FAILURE__;
            }
            else if (BUFFER_enlarge(ctrlPacket, topicLen + 2 + 1) != 0)
            {
                result = __FAILURE__;
            }
            else
            {
                uint8_t* iterator = BUFFER_u_char(ctrlPacket);
                iterator += offsetLen;
                byteutil_writeUTF(&iterator, payloadList[index].subscribeTopic, (uint16_t)topicLen);
                *iterator = payloadList[index].qosReturn;

                if (trace_log != NULL)
                {
                    STRING_sprintf(trace_log, " | TOPIC_NAME: %s | QOS: %d", payloadList[index].subscribeTopic, (int)payloadList[index].qosReturn);
                }
            }
        }
    }
    return result;
}

static int constructConnectVariableHeader(BUFFER_HANDLE ctrlPacket, const MQTT_CLIENT_OPTIONS* mqttOptions, STRING_HANDLE trace_log)
{
    int result = 0;
    if (BUFFER_enlarge(ctrlPacket, CONNECT_VARIABLE_HEADER_SIZE) != 0)
    {
        result = __FAILURE__;
    }
    else
    {
        uint8_t* iterator = BUFFER_u_char(ctrlPacket);
        if (iterator == NULL)
        {
            result = __FAILURE__;
        }
        else
        {
            if (trace_log != NULL)
            {
                STRING_sprintf(trace_log, " | VER: %d | KEEPALIVE: %d | FLAGS:", PROTOCOL_NUMBER, mqttOptions->keepAliveInterval);
            }
            byteutil_writeUTF(&iterator, "MQTT", 4);
            byteutil_writeByte(&iterator, PROTOCOL_NUMBER);
            byteutil_writeByte(&iterator, 0); // Flags will be entered later
            byteutil_writeInt(&iterator, mqttOptions->keepAliveInterval);
            result = 0;
        }
    }
    return result;
}

static int constructPublishVariableHeader(BUFFER_HANDLE ctrlPacket, const PUBLISH_HEADER_INFO* publishHeader, STRING_HANDLE trace_log)
{
    int result = 0;
    size_t topicLen = 0;
    size_t spaceLen = 0;
    size_t idLen = 0;

    size_t currLen = BUFFER_length(ctrlPacket);

    topicLen = strlen(publishHeader->topicName);
    spaceLen += 2;

    if (publishHeader->qualityOfServiceValue != DELIVER_AT_MOST_ONCE)
    {
        // Packet Id is only set if the QOS is not 0
        idLen = 2;
    }

    if (topicLen > USHRT_MAX)
    {
        result = __FAILURE__;
    }
    else if (BUFFER_enlarge(ctrlPacket, topicLen + idLen + spaceLen) != 0)
    {
        result = __FAILURE__;
    }
    else
    {
        uint8_t* iterator = BUFFER_u_char(ctrlPacket);
        if (iterator == NULL)
        {
            result = __FAILURE__;
        }
        else
        {
            iterator += currLen;
            /* The Topic Name MUST be present as the first field in the PUBLISH Packet Variable header.It MUST be 792 a UTF-8 encoded string [MQTT-3.3.2-1] as defined in section 1.5.3.*/
            byteutil_writeUTF(&iterator, publishHeader->topicName, (uint16_t)topicLen);
            if (trace_log != NULL)
            {
                STRING_sprintf(trace_log, " | TOPIC_NAME: %s", publishHeader->topicName);
            }
            if (idLen > 0)
            {
                if (trace_log != NULL)
                {
                    STRING_sprintf(trace_log, " | PACKET_ID: %"PRIu16, publishHeader->packetId);
                }
                byteutil_writeInt(&iterator, publishHeader->packetId);
            }
            result = 0;
        }
    }
    return result;
}

static int constructSubscibeTypeVariableHeader(BUFFER_HANDLE ctrlPacket, uint16_t packetId)
{
    int result = 0;
    if (BUFFER_enlarge(ctrlPacket, 2) != 0)
    {
        result = __FAILURE__;
    }
    else
    {
        uint8_t* iterator = BUFFER_u_char(ctrlPacket);
        if (iterator == NULL)
        {
            result = __FAILURE__;
        }
        else
        {
            byteutil_writeInt(&iterator, packetId);
            result = 0;
        }
    }
    return result;
}

static BUFFER_HANDLE constructPublishReply(CONTROL_PACKET_TYPE type, uint8_t flags, uint16_t packetId)
{
    BUFFER_HANDLE result = BUFFER_new();
    if (result != NULL)
    {
        if (BUFFER_pre_build(result, 4) != 0)
        {
            BUFFER_delete(result);
            result = NULL;
        }
        else
        {
            uint8_t* iterator = BUFFER_u_char(result);
            if (iterator == NULL)
            {
                BUFFER_delete(result);
                result = NULL;
            }
            else
            {
                *iterator = (uint8_t)type | flags;
                iterator++;
                *iterator = 0x2;
                iterator++;
                byteutil_writeInt(&iterator, packetId);
            }
        }
    }
    return result;
}

static int constructFixedHeader(BUFFER_HANDLE ctrlPacket, CONTROL_PACKET_TYPE packetType, uint8_t flags)
{
    int result;
    if (ctrlPacket == NULL)
    {
        return __FAILURE__;
    }
    else
    {
        size_t packetLen = BUFFER_length(ctrlPacket);
        uint8_t remainSize[4] ={ 0 };
        size_t index = 0;

        // Calculate the length of packet
        do
        {
            uint8_t encode = packetLen % 128;
            packetLen /= 128;
            // if there are more data to encode, set the top bit of this byte
            if (packetLen > 0)
            {
                encode |= NEXT_128_CHUNK;
            }
            remainSize[index++] = encode;
        } while (packetLen > 0);

        BUFFER_HANDLE fixedHeader = BUFFER_new();
        if (fixedHeader == NULL)
        {
            result = __FAILURE__;
        }
        else if (BUFFER_pre_build(fixedHeader, index + 1) != 0)
        {
            BUFFER_delete(fixedHeader);
            result = __FAILURE__;
        }
        else
        {
            uint8_t* iterator = BUFFER_u_char(fixedHeader);
            *iterator = (uint8_t)packetType | flags;
            iterator++;
            (void)memcpy(iterator, remainSize, index);

            result = BUFFER_prepend(ctrlPacket, fixedHeader);
            BUFFER_delete(fixedHeader);
        }
    }
    return result;
}

static int constructConnPayload(BUFFER_HANDLE ctrlPacket, const MQTT_CLIENT_OPTIONS* mqttOptions, STRING_HANDLE trace_log)
{
    int result = 0;
    if (mqttOptions == NULL || ctrlPacket == NULL)
    {
        result = __FAILURE__;
    }
    else
    {
        size_t clientLen = 0;
        size_t usernameLen = 0;
        size_t passwordLen = 0;
        size_t willMessageLen = 0;
        size_t willTopicLen = 0;
        size_t spaceLen = 0;

        if (mqttOptions->clientId != NULL)
        {
            spaceLen += 2;
            clientLen = strlen(mqttOptions->clientId);
        }
        if (mqttOptions->username != NULL)
        {
            spaceLen += 2;
            usernameLen = strlen(mqttOptions->username);
        }
        if (mqttOptions->password != NULL)
        {
            spaceLen += 2;
            passwordLen = strlen(mqttOptions->password);
        }
        if (mqttOptions->willMessage != NULL)
        {
            spaceLen += 2;
            willMessageLen = strlen(mqttOptions->willMessage);
        }
        if (mqttOptions->willTopic != NULL)
        {
            spaceLen += 2;
            willTopicLen = strlen(mqttOptions->willTopic);
        }

        size_t currLen = BUFFER_length(ctrlPacket);
        size_t totalLen = clientLen + usernameLen + passwordLen + willMessageLen + willTopicLen + spaceLen;

        // Validate the Username & Password
        if (clientLen > USHRT_MAX)
        {
            result = __FAILURE__;
        }
        else if (usernameLen == 0 && passwordLen > 0)
        {
            result = __FAILURE__;
        }
        else if ((willMessageLen > 0 && willTopicLen == 0) || (willTopicLen > 0 && willMessageLen == 0))
        {
            result = __FAILURE__;
        }
        else if (BUFFER_enlarge(ctrlPacket, totalLen) != 0)
        {
            result = __FAILURE__;
        }
        else
        {
            uint8_t* packet = BUFFER_u_char(ctrlPacket);
            uint8_t* iterator = packet;

            iterator += currLen;
            byteutil_writeUTF(&iterator, mqttOptions->clientId, (uint16_t)clientLen);

            // TODO: Read on the Will Topic
            if (willMessageLen > USHRT_MAX || willTopicLen > USHRT_MAX || usernameLen > USHRT_MAX || passwordLen > USHRT_MAX)
            {
                result = __FAILURE__;
            }
            else
            {
                STRING_HANDLE connect_payload_trace = NULL;
                if (trace_log != NULL)
                {
                    connect_payload_trace = STRING_new();
                }
                if (willMessageLen > 0 && willTopicLen > 0)
                {
                    if (trace_log != NULL)
                    {
                        (void)STRING_sprintf(connect_payload_trace, " | WILL_TOPIC: %s", mqttOptions->willTopic);
                    }
                    packet[CONN_FLAG_BYTE_OFFSET] |= WILL_FLAG_FLAG;
                    byteutil_writeUTF(&iterator, mqttOptions->willTopic, (uint16_t)willTopicLen);
                    packet[CONN_FLAG_BYTE_OFFSET] |= (mqttOptions->qualityOfServiceValue << 3);
                    if (mqttOptions->messageRetain)
                    {
                        packet[CONN_FLAG_BYTE_OFFSET] |= WILL_RETAIN_FLAG;
                    }
                    byteutil_writeUTF(&iterator, mqttOptions->willMessage, (uint16_t)willMessageLen);
                }
                if (usernameLen > 0)
                {
                    packet[CONN_FLAG_BYTE_OFFSET] |= USERNAME_FLAG;
                    byteutil_writeUTF(&iterator, mqttOptions->username, (uint16_t)usernameLen);
                    if (trace_log != NULL)
                    {
                        (void)STRING_sprintf(connect_payload_trace, " | USERNAME: %s", mqttOptions->username);
                    }
                }
                if (passwordLen > 0)
                {
                    packet[CONN_FLAG_BYTE_OFFSET] |= PASSWORD_FLAG;
                    byteutil_writeUTF(&iterator, mqttOptions->password, (uint16_t)passwordLen);
                    if (trace_log != NULL)
                    {
                        (void)STRING_sprintf(connect_payload_trace, " | PWD: XXXX");
                    }
                }
                // TODO: Get the rest of the flags
                if (trace_log != NULL)
                {
                    (void)STRING_sprintf(connect_payload_trace, " | CLEAN: %s", mqttOptions->useCleanSession ? "1" : "0");
                }
                if (mqttOptions->useCleanSession)
                {
                    packet[CONN_FLAG_BYTE_OFFSET] |= CLEAN_SESSION_FLAG;
                }
                if (trace_log != NULL)
                {
                    (void)STRING_sprintf(trace_log, " %zu", packet[CONN_FLAG_BYTE_OFFSET]);
                    (void)STRING_concat_with_STRING(trace_log, connect_payload_trace);
                    STRING_delete(connect_payload_trace);
                }
                result = 0;
            }
        }
    }
    return result;
}

static int prepareheaderDataInfo(MQTTCODEC_INSTANCE* codecData, uint8_t remainLen)
{
    int result;
    if (codecData == NULL)
    {
        result = __FAILURE__;
    }
    else
    {
        result = 0;
        codecData->storeRemainLen[codecData->remainLenIndex++] = remainLen;
        if (remainLen <= 0x7f)
        {
            int multiplier = 1;
            int totalLen = 0;
            size_t index = 0;
            uint8_t encodeByte = 0;
            do
            {
                encodeByte = codecData->storeRemainLen[index++];
                totalLen += (encodeByte & 127) * multiplier;
                multiplier *= NEXT_128_CHUNK;

                if (multiplier > 128 * 128 * 128)
                {
                    result = __FAILURE__;
                    break;
                }
            } while ((encodeByte & NEXT_128_CHUNK) != 0);

            codecData->codecState = CODEC_STATE_VAR_HEADER;

            // Reset remainLen Index
            codecData->remainLenIndex = 0;
            memset(codecData->storeRemainLen, 0, 4 * sizeof(uint8_t));

            if (totalLen > 0)
            {
                codecData->bufferOffset = 0;
                codecData->headerData = BUFFER_new();
                if (codecData->headerData == NULL)
                {
                    /* Codes_SRS_MQTT_CODEC_07_035: [ If any error is encountered then the packet state will be marked as error and mqtt_codec_bytesReceived shall return a non-zero value. ] */
                    LogError("Failed BUFFER_new");
                    result = __FAILURE__;
                }
                else
                {
                    if (BUFFER_pre_build(codecData->headerData, totalLen) != 0)
                    {
                        /* Codes_SRS_MQTT_CODEC_07_035: [ If any error is encountered then the packet state will be marked as error and mqtt_codec_bytesReceived shall return a non-zero value. ] */
                        LogError("Failed BUFFER_pre_build");
                        result = __FAILURE__;
                    }

                }
            }
        }
    }
    return result;
}

static void completePacketData(MQTTCODEC_INSTANCE* codecData)
{
    if (codecData)
    {
        if (codecData->packetComplete != NULL)
        {
            codecData->packetComplete(codecData->callContext, codecData->currPacket, codecData->headerFlags, codecData->headerData);
        }

        // Clean up data
        codecData->currPacket = UNKNOWN_TYPE;
        codecData->codecState = CODEC_STATE_FIXED_HEADER;
        codecData->headerFlags = 0;
        BUFFER_delete(codecData->headerData);
        codecData->headerData = NULL;
    }
}

MQTTCODEC_HANDLE mqtt_codec_create(ON_PACKET_COMPLETE_CALLBACK packetComplete, void* callbackCtx)
{
    MQTTCODEC_HANDLE result;
    result = malloc(sizeof(MQTTCODEC_INSTANCE));
    /* Codes_SRS_MQTT_CODEC_07_001: [If a failure is encountered then mqtt_codec_create shall return NULL.] */
    if (result != NULL)
    {
        /* Codes_SRS_MQTT_CODEC_07_002: [On success mqtt_codec_create shall return a MQTTCODEC_HANDLE value.] */
        result->currPacket = UNKNOWN_TYPE;
        result->codecState = CODEC_STATE_FIXED_HEADER;
        result->headerFlags = 0;
        result->bufferOffset = 0;
        result->packetComplete = packetComplete;
        result->callContext = callbackCtx;
        result->headerData = NULL;
        memset(result->storeRemainLen, 0, 4 * sizeof(uint8_t));
        result->remainLenIndex = 0;
    }
    return result;
}

void mqtt_codec_destroy(MQTTCODEC_HANDLE handle)
{
    /* Codes_SRS_MQTT_CODEC_07_003: [If the handle parameter is NULL then mqtt_codec_destroy shall do nothing.] */
    if (handle != NULL)
    {
        MQTTCODEC_INSTANCE* codecData = (MQTTCODEC_INSTANCE*)handle;
        /* Codes_SRS_MQTT_CODEC_07_004: [mqtt_codec_destroy shall deallocate all memory that has been allocated by this object.] */
        BUFFER_delete(codecData->headerData);
        free(codecData);
    }
}

BUFFER_HANDLE mqtt_codec_connect(const MQTT_CLIENT_OPTIONS* mqttOptions, STRING_HANDLE trace_log)
{
    BUFFER_HANDLE result;
    /* Codes_SRS_MQTT_CODEC_07_008: [If the parameters mqttOptions is NULL then mqtt_codec_connect shall return a null value.] */
    if (mqttOptions == NULL)
    {
        result = NULL;
    }
    else
    {
        /* Codes_SRS_MQTT_CODEC_07_009: [mqtt_codec_connect shall construct a BUFFER_HANDLE that represents a MQTT CONNECT packet.] */
        result = BUFFER_new();
        if (result != NULL)
        {
            STRING_HANDLE varible_header_log = NULL;
            if (trace_log != NULL)
            {
                varible_header_log = STRING_new();
            }
            // Add Variable Header Information
            if (constructConnectVariableHeader(result, mqttOptions, varible_header_log) != 0)
            {
                /* Codes_SRS_MQTT_CODEC_07_010: [If any error is encountered then mqtt_codec_connect shall return NULL.] */
                BUFFER_delete(result);
                result = NULL;
            }
            else
            {
                if (constructConnPayload(result, mqttOptions, varible_header_log) != 0)
                {
                    /* Codes_SRS_MQTT_CODEC_07_010: [If any error is encountered then mqtt_codec_connect shall return NULL.] */
                    BUFFER_delete(result);
                    result = NULL;
                }
                else
                {
                    if (trace_log != NULL)
                    {
                        (void)STRING_copy(trace_log, "CONNECT");
                    }
                    if (constructFixedHeader(result, CONNECT_TYPE, 0) != 0)
                    {
                        /* Codes_SRS_MQTT_CODEC_07_010: [If any error is encountered then mqtt_codec_connect shall return NULL.] */
                        BUFFER_delete(result);
                        result = NULL;
                    }
                    else
                    {
                        if (trace_log != NULL)
                        {
                            (void)STRING_concat_with_STRING(trace_log, varible_header_log);
                        }
                    }
                }
                if (varible_header_log != NULL)
                {
                    STRING_delete(varible_header_log);
                }
            }
        }
    }
    return result;
}

BUFFER_HANDLE mqtt_codec_disconnect()
{
    /* Codes_SRS_MQTT_CODEC_07_011: [On success mqtt_codec_disconnect shall construct a BUFFER_HANDLE that represents a MQTT DISCONNECT packet.] */
    BUFFER_HANDLE result = BUFFER_new();
    if (result != NULL)
    {
        if (BUFFER_enlarge(result, 2) != 0)
        {
            /* Codes_SRS_MQTT_CODEC_07_012: [If any error is encountered mqtt_codec_disconnect shall return NULL.] */
            BUFFER_delete(result);
            result = NULL;
        }
        else
        {
            uint8_t* iterator = BUFFER_u_char(result);
            if (iterator == NULL)
            {
                /* Codes_SRS_MQTT_CODEC_07_012: [If any error is encountered mqtt_codec_disconnect shall return NULL.] */
                BUFFER_delete(result);
                result = NULL;
            }
            else
            {
                iterator[0] = DISCONNECT_TYPE;
                iterator[1] = 0;
            }
        }
    }
    return result;
}

BUFFER_HANDLE mqtt_codec_publish(QOS_VALUE qosValue, bool duplicateMsg, bool serverRetain, uint16_t packetId, const char* topicName, const uint8_t* msgBuffer, size_t buffLen, STRING_HANDLE trace_log)
{
    BUFFER_HANDLE result;
    /* Codes_SRS_MQTT_CODEC_07_005: [If the parameters topicName is NULL then mqtt_codec_publish shall return NULL.] */
    if (topicName == NULL)
    {
        result = NULL;
    }
    /* Codes_SRS_MQTT_CODEC_07_036: [mqtt_codec_publish shall return NULL if the buffLen variable is greater than the MAX_SEND_SIZE (0xFFFFFF7F).] */
    else if (buffLen > MAX_SEND_SIZE)
    {
        /* Codes_SRS_MQTT_CODEC_07_006: [If any error is encountered then mqtt_codec_publish shall return NULL.] */
        result = NULL;
    }
    else
    {
        PUBLISH_HEADER_INFO publishInfo ={ 0 };
        publishInfo.topicName = topicName;
        publishInfo.packetId = packetId;
        publishInfo.qualityOfServiceValue = qosValue;

        uint8_t headerFlags = 0;
        if (duplicateMsg) headerFlags |= PUBLISH_DUP_FLAG;
        if (serverRetain) headerFlags |= PUBLISH_QOS_RETAIN;
        if (qosValue != DELIVER_AT_MOST_ONCE)
        {
            if (qosValue == DELIVER_AT_LEAST_ONCE)
            {
                headerFlags |= PUBLISH_QOS_AT_LEAST_ONCE;
            }
            else
            {
                headerFlags |= PUBLISH_QOS_EXACTLY_ONCE;
            }
        }

        /* Codes_SRS_MQTT_CODEC_07_007: [mqtt_codec_publish shall return a BUFFER_HANDLE that represents a MQTT PUBLISH message.] */
        result = BUFFER_new();
        if (result != NULL)
        {
            STRING_HANDLE varible_header_log = NULL;
            if (trace_log != NULL)
            {
                varible_header_log = STRING_construct_sprintf(" | IS_DUP: %s | RETAIN: %d | QOS: %s", duplicateMsg ? TRUE_CONST : FALSE_CONST,
                    serverRetain ? 1 : 0,
                    retrieve_qos_value(publishInfo.qualityOfServiceValue) );
            }

            if (constructPublishVariableHeader(result, &publishInfo, varible_header_log) != 0)
            {
                /* Codes_SRS_MQTT_CODEC_07_006: [If any error is encountered then mqtt_codec_publish shall return NULL.] */
                BUFFER_delete(result);
                result = NULL;
            }
            else
            {
                size_t payloadOffset = BUFFER_length(result);
                if (buffLen > 0)
                {
                    if (BUFFER_enlarge(result, buffLen) != 0)
                    {
                        /* Codes_SRS_MQTT_CODEC_07_006: [If any error is encountered then mqtt_codec_publish shall return NULL.] */
                        BUFFER_delete(result);
                        result = NULL;
                    }
                    else
                    {
                        uint8_t* iterator = BUFFER_u_char(result);
                        if (iterator == NULL)
                        {
                            /* Codes_SRS_MQTT_CODEC_07_006: [If any error is encountered then mqtt_codec_publish shall return NULL.] */
                            BUFFER_delete(result);
                            result = NULL;
                        }
                        else
                        {
                            iterator += payloadOffset;
                            // Write Message
                            (void)memcpy(iterator, msgBuffer, buffLen);
                            if (trace_log)
                            {
                                STRING_sprintf(varible_header_log, " | PAYLOAD_LEN: %zu", buffLen);
                            }
                        }
                    }
                }

                if (result != NULL)
                {
                    if (trace_log != NULL)
                    {
                        (void)STRING_copy(trace_log, "PUBLISH");
                    }
                    if (constructFixedHeader(result, PUBLISH_TYPE, headerFlags) != 0)
                    {
                        /* Codes_SRS_MQTT_CODEC_07_006: [If any error is encountered then mqtt_codec_publish shall return NULL.] */
                        BUFFER_delete(result);
                        result = NULL;
                    }
                    else
                    {
                        if (trace_log != NULL)
                        {
                            (void)STRING_concat_with_STRING(trace_log, varible_header_log);
                        }
                    }
                }
            }
            if (varible_header_log != NULL)
            {
                STRING_delete(varible_header_log);
            }
        }
    }
    return result;
}

BUFFER_HANDLE mqtt_codec_publishAck(uint16_t packetId)
{
    /* Codes_SRS_MQTT_CODEC_07_013: [On success mqtt_codec_publishAck shall return a BUFFER_HANDLE representation of a MQTT PUBACK packet.] */
    /* Codes_SRS_MQTT_CODEC_07_014 : [If any error is encountered then mqtt_codec_publishAck shall return NULL.] */
    BUFFER_HANDLE result = constructPublishReply(PUBACK_TYPE, 0, packetId);
    return result;
}

BUFFER_HANDLE mqtt_codec_publishReceived(uint16_t packetId)
{
    /* Codes_SRS_MQTT_CODEC_07_015: [On success mqtt_codec_publishRecieved shall return a BUFFER_HANDLE representation of a MQTT PUBREC packet.] */
    /* Codes_SRS_MQTT_CODEC_07_016 : [If any error is encountered then mqtt_codec_publishRecieved shall return NULL.] */
    BUFFER_HANDLE result = constructPublishReply(PUBREC_TYPE, 0, packetId);
    return result;
}

BUFFER_HANDLE mqtt_codec_publishRelease(uint16_t packetId)
{
    /* Codes_SRS_MQTT_CODEC_07_017: [On success mqtt_codec_publishRelease shall return a BUFFER_HANDLE representation of a MQTT PUBREL packet.] */
    /* Codes_SRS_MQTT_CODEC_07_018 : [If any error is encountered then mqtt_codec_publishRelease shall return NULL.] */
    BUFFER_HANDLE result = constructPublishReply(PUBREL_TYPE, 2, packetId);
    return result;
}

BUFFER_HANDLE mqtt_codec_publishComplete(uint16_t packetId)
{
    /* Codes_SRS_MQTT_CODEC_07_019: [On success mqtt_codec_publishComplete shall return a BUFFER_HANDLE representation of a MQTT PUBCOMP packet.] */
    /* Codes_SRS_MQTT_CODEC_07_020 : [If any error is encountered then mqtt_codec_publishComplete shall return NULL.] */
    BUFFER_HANDLE result = constructPublishReply(PUBCOMP_TYPE, 0, packetId);
    return result;
}

BUFFER_HANDLE mqtt_codec_ping()
{
    /* Codes_SRS_MQTT_CODEC_07_021: [On success mqtt_codec_ping shall construct a BUFFER_HANDLE that represents a MQTT PINGREQ packet.] */
    BUFFER_HANDLE result = BUFFER_new();
    if (result != NULL)
    {
        if (BUFFER_enlarge(result, 2) != 0)
        {
            /* Codes_SRS_MQTT_CODEC_07_022: [If any error is encountered mqtt_codec_ping shall return NULL.] */
            BUFFER_delete(result);
            result = NULL;
        }
        else
        {
            uint8_t* iterator = BUFFER_u_char(result);
            if (iterator == NULL)
            {
                /* Codes_SRS_MQTT_CODEC_07_022: [If any error is encountered mqtt_codec_ping shall return NULL.] */
                BUFFER_delete(result);
                result = NULL;
            }
            else
            {
                iterator[0] = PINGREQ_TYPE;
                iterator[1] = 0;
            }
        }
    }
    return result;
}

BUFFER_HANDLE mqtt_codec_subscribe(uint16_t packetId, SUBSCRIBE_PAYLOAD* subscribeList, size_t count, STRING_HANDLE trace_log)
{
    BUFFER_HANDLE result;
    /* Codes_SRS_MQTT_CODEC_07_023: [If the parameters subscribeList is NULL or if count is 0 then mqtt_codec_subscribe shall return NULL.] */
    if (subscribeList == NULL || count == 0)
    {
        result = NULL;
    }
    else
    {
        /* Codes_SRS_MQTT_CODEC_07_026: [mqtt_codec_subscribe shall return a BUFFER_HANDLE that represents a MQTT SUBSCRIBE message.]*/
        result = BUFFER_new();
        if (result != NULL)
        {
            if (constructSubscibeTypeVariableHeader(result, packetId) != 0)
            {
                /* Codes_SRS_MQTT_CODEC_07_025: [If any error is encountered then mqtt_codec_subscribe shall return NULL.] */
                BUFFER_delete(result);
                result = NULL;
            }
            else
            {
                STRING_HANDLE sub_trace = NULL;
                if (trace_log != NULL)
                {
                    sub_trace = STRING_construct_sprintf(" | PACKET_ID: %"PRIu16, packetId);
                }
                /* Codes_SRS_MQTT_CODEC_07_024: [mqtt_codec_subscribe shall iterate through count items in the subscribeList.] */
                if (addListItemsToSubscribePacket(result, subscribeList, count, sub_trace) != 0)
                {
                    /* Codes_SRS_MQTT_CODEC_07_025: [If any error is encountered then mqtt_codec_subscribe shall return NULL.] */
                    BUFFER_delete(result);
                    result = NULL;
                }
                else
                {

                    if (trace_log != NULL)
                    {
                        STRING_concat(trace_log, "SUBSCRIBE");
                    }
                    if (constructFixedHeader(result, SUBSCRIBE_TYPE, SUBSCRIBE_FIXED_HEADER_FLAG) != 0)
                    {
                        /* Codes_SRS_MQTT_CODEC_07_025: [If any error is encountered then mqtt_codec_subscribe shall return NULL.] */
                        BUFFER_delete(result);
                        result = NULL;
                    }
                    else
                    {
                        if (trace_log != NULL)
                        {
                            (void)STRING_concat_with_STRING(trace_log, sub_trace);
                        }
                    }
                }
                if (sub_trace != NULL)
                {
                    STRING_delete(sub_trace);
                }
            }
        }
    }
    return result;
}

BUFFER_HANDLE mqtt_codec_unsubscribe(uint16_t packetId, const char** unsubscribeList, size_t count, STRING_HANDLE trace_log)
{
    BUFFER_HANDLE result;
    /* Codes_SRS_MQTT_CODEC_07_027: [If the parameters unsubscribeList is NULL or if count is 0 then mqtt_codec_unsubscribe shall return NULL.] */
    if (unsubscribeList == NULL || count == 0)
    {
        result = NULL;
    }
    else
    {
        /* Codes_SRS_MQTT_CODEC_07_030: [mqtt_codec_unsubscribe shall return a BUFFER_HANDLE that represents a MQTT SUBSCRIBE message.] */
        result = BUFFER_new();
        if (result != NULL)
        {
            if (constructSubscibeTypeVariableHeader(result, packetId) != 0)
            {
                /* Codes_SRS_MQTT_CODEC_07_029: [If any error is encountered then mqtt_codec_unsubscribe shall return NULL.] */
                BUFFER_delete(result);
                result = NULL;
            }
            else
            {
                STRING_HANDLE unsub_trace = NULL;
                if (trace_log != NULL)
                {
                    unsub_trace = STRING_construct_sprintf(" | PACKET_ID: %"PRIu16, packetId);
                }
                /* Codes_SRS_MQTT_CODEC_07_028: [mqtt_codec_unsubscribe shall iterate through count items in the unsubscribeList.] */
                if (addListItemsToUnsubscribePacket(result, unsubscribeList, count, unsub_trace) != 0)
                {
                    /* Codes_SRS_MQTT_CODEC_07_029: [If any error is encountered then mqtt_codec_unsubscribe shall return NULL.] */
                    BUFFER_delete(result);
                    result = NULL;
                }
                else
                {
                    if (trace_log != NULL)
                    {
                        (void)STRING_copy(trace_log, "UNSUBSCRIBE");
                    }
                    if (constructFixedHeader(result, UNSUBSCRIBE_TYPE, UNSUBSCRIBE_FIXED_HEADER_FLAG) != 0)
                    {
                        /* Codes_SRS_MQTT_CODEC_07_029: [If any error is encountered then mqtt_codec_unsubscribe shall return NULL.] */
                        BUFFER_delete(result);
                        result = NULL;
                    }
                    else
                    {
                        if (trace_log != NULL)
                        {
                            (void)STRING_concat_with_STRING(trace_log, unsub_trace);
                        }
                    }
                }
                if (unsub_trace != NULL)
                {
                    STRING_delete(unsub_trace);
                }
            }
        }
    }
    return result;
}

int mqtt_codec_bytesReceived(MQTTCODEC_HANDLE handle, const unsigned char* buffer, size_t size)
{
    int result;
    MQTTCODEC_INSTANCE* codec_Data = (MQTTCODEC_INSTANCE*)handle;
    /* Codes_SRS_MQTT_CODEC_07_031: [If the parameters handle or buffer is NULL then mqtt_codec_bytesReceived shall return a non-zero value.] */
    if (codec_Data == NULL)
    {
        result = __FAILURE__;
    }
    /* Codes_SRS_MQTT_CODEC_07_031: [If the parameters handle or buffer is NULL then mqtt_codec_bytesReceived shall return a non-zero value.] */
    /* Codes_SRS_MQTT_CODEC_07_032: [If the parameters size is zero then mqtt_codec_bytesReceived shall return a non-zero value.] */
    else if (buffer == NULL || size == 0)
    {
        codec_Data->currPacket = PACKET_TYPE_ERROR;
        result = __FAILURE__;
    }
    else
    {
        /* Codes_SRS_MQTT_CODEC_07_033: [mqtt_codec_bytesReceived constructs a sequence of bytes into the corresponding MQTT packets and on success returns zero.] */
        result = 0;
        size_t index = 0;
        for (index = 0; index < size && result == 0; index++)
        {
            uint8_t iterator = ((int8_t*)buffer)[index];
            if (codec_Data->codecState == CODEC_STATE_FIXED_HEADER)
            {
                if (codec_Data->currPacket == UNKNOWN_TYPE)
                {
                    codec_Data->currPacket = processControlPacketType(iterator, &codec_Data->headerFlags);
                }
                else
                {
                    if (prepareheaderDataInfo(codec_Data, iterator) != 0)
                    {
                        /* Codes_SRS_MQTT_CODEC_07_035: [If any error is encountered then the packet state will be marked as error and mqtt_codec_bytesReceived shall return a non-zero value.] */
                        codec_Data->currPacket = PACKET_TYPE_ERROR;
                        result = __FAILURE__;
                    }
                    if (codec_Data->currPacket == PINGRESP_TYPE)
                    {
                        /* Codes_SRS_MQTT_CODEC_07_034: [Upon a constructing a complete MQTT packet mqtt_codec_bytesReceived shall call the ON_PACKET_COMPLETE_CALLBACK function.] */
                        completePacketData(codec_Data);
                    }
                }
            }
            else if (codec_Data->codecState == CODEC_STATE_VAR_HEADER)
            {
                if (codec_Data->headerData == NULL)
                {
                    codec_Data->codecState = CODEC_STATE_PAYLOAD;
                }
                else
                {
                    uint8_t* dataBytes = BUFFER_u_char(codec_Data->headerData);
                    if (dataBytes == NULL)
                    {
                        /* Codes_SRS_MQTT_CODEC_07_035: [If any error is encountered then the packet state will be marked as error and mqtt_codec_bytesReceived shall return a non-zero value.] */
                        codec_Data->currPacket = PACKET_TYPE_ERROR;
                        result = __FAILURE__;
                    }
                    else
                    {
                        // Increment the data
                        dataBytes += codec_Data->bufferOffset++;
                        *dataBytes = iterator;

                        size_t totalLen = BUFFER_length(codec_Data->headerData);
                        if (codec_Data->bufferOffset >= totalLen)
                        {
                            /* Codes_SRS_MQTT_CODEC_07_034: [Upon a constructing a complete MQTT packet mqtt_codec_bytesReceived shall call the ON_PACKET_COMPLETE_CALLBACK function.] */
                            completePacketData(codec_Data);
                        }
                    }
                }
            }
            else
            {
                /* Codes_SRS_MQTT_CODEC_07_035: [If any error is encountered then the packet state will be marked as error and mqtt_codec_bytesReceived shall return a non-zero value.] */
                codec_Data->currPacket = PACKET_TYPE_ERROR;
                result = __FAILURE__;
            }
        }
    }
    return result;
}


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Morus hastifolia F.T.Wang & Tang ex Z.Y.Cao

### Remarks
null

redpajama_set_name: RedPajamaGithub


text:
#include <thrift/test/gen-cpp/global_types.h>

#include <tuple>

bool global_structA::operator<(const global_structA& rhs) const {
  return std::tie(a, b) < std::tie(rhs.a, rhs.b);
}

bool global_structB::operator<(const global_structB& rhs) const {
  return std::tie(c, d) < std::tie(rhs.c, rhs.d);
}


text:
<?php

namespace Auth;

abstract class Auth_Group_Driver extends \Auth_Driver
{
	/**
	 * @var	Auth_Driver
	 */
	protected static $_instance = null;

	/**
	 * @var	array	contains references if multiple were loaded
	 */
	protected static $_instances = array();

	public static function forge(array $config = array())
	{
		// default driver id to driver name when not given
		! array_key_exists('id', $config) && $config['id'] = $config['driver'];

		$class = \Inflector::get_namespace($config['driver']).'Auth_Group_'.\Str::ucwords(\Inflector::denamespace($config['driver']));
		$driver = new $class($config);
		static::$_instances[$driver->get_id()] = $driver;
		is_null(static::$_instance) and static::$_instance = $driver;

		foreach ($driver->get_config('drivers', array()) as $type => $drivers)
		{
			foreach ($drivers as $d => $custom)
			{
				$custom = is_int($d)
					? array('driver' => $custom)
					: array_merge($custom, array('driver' => $d));
				$class = 'Auth_'.\Str::ucwords($type).'_Driver';
				$class::forge($custom);
			}
		}

		return $driver;
	}

	// ------------------------------------------------------------------------

	/**
	 * Verify Acl access
	 *
	 * @param	mixed	condition to validate
	 * @param	string	acl driver id or null to check all
	 * @param	array	user identifier to check in form array(driver_id, user_id)
	 * @return	bool
	 */
	public function has_access($condition, $driver, $group = null)
	{
		// When group was given just check the group
		if (is_array($group))
		{
			if ($driver === null)
			{
				foreach (\Auth::acl(true) as $acl)
				{
					if ($acl->has_access($condition, $group))
					{
						return true;
					}
				}

				return false;
			}

			return \Auth::acl($driver)->has_access($condition, $group);
		}

		// When no group was given check all logged in users
		foreach (\Auth::verified() as $v)
		{
			// ... and check all those their groups
			$gs = $v->get_groups();
			foreach ($gs as $g_id)
			{
				// ... and try to validate if its group is this one
				if ($this->id = $g_id[0])
				{
					if ($this->has_access($condition, $driver, $g_id))
					{
						return true;
					}
				}
			}
		}

		// when nothing validated yet: it has failed to
		return false;
	}

	// ------------------------------------------------------------------------

	/**
	 * Check membership of given users
	 *
	 * @param	mixed	condition to check for access
	 * @param	array	user identifier in the form of array(driver_id, user_id), or null for logged in
	 * @return	bool
	 */
	abstract public function member($group, $user = null);

	/**
	 * Fetch the display name of the given group
	 *
	 * @param	mixed	group condition to check
	 * @return	string
	 */
	abstract public function get_name($group);
}

/* end of file driver.php */


text:
///////////////////////////////////////////////////////////////////////////
// Copyright © 2015 Esri. All Rights Reserved.
//
// Licensed under the Apache License Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
///////////////////////////////////////////////////////////////////////////
define([
  'dojo/_base/declare',
  'dojo/_base/lang',
  'dojo/_base/html',
  'dojo/topic',
  'dojo/on',
  'dojo/query',
  './FeatureActionManager',
  './utils',
  './dijit/PopupMenu'
  ], function(declare, lang, html, topic, on, query, FeatureActionManager, jimuUtils, PopupMenu) {
    var instance = null;
    var clazz = declare(null, {
      mapManager: null,
      // popupUnion = {
      //   mobile: is mobile popup of map,
      //   bigScreen: is popup of map
      // };
      popupUnion: null,

      constructor: function(options) {
        lang.mixin(this, options);

        this.popupMenu = PopupMenu.getInstance();
        this.isInited = false;

        this.featureActionManager = FeatureActionManager.getInstance();
        topic.subscribe("mapLoaded", lang.hitch(this, this.onMapLoadedOrChanged));
        topic.subscribe("mapChanged", lang.hitch(this, this.onMapLoadedOrChanged));
        topic.subscribe("appConfigChanged", lang.hitch(this, this._onAppConfigChanged));
        topic.subscribe("widgetsActionsRegistered", lang.hitch(this, this._onWidgetsActionsRegistered));
      },

      init: function() {
        this.popupUnion = this.mapManager.getMapInfoWindow();
        if(!this.popupUnion.bigScreen || !this.popupUnion.mobile ||
          !this.popupUnion.bigScreen.domNode || !this.popupUnion.mobile.domNode){
          return;
        }
        if(!this.isInited){
          this._createPopupMenuButton();
          this._bindSelectionChangeEvent();
          this.isInited = true;
        }
      },

      _createPopupMenuButton: function(){
        this.popupMenuButtonDesktop = html.create('span', {
          'class': 'popup-menu-button'
        }, query(".actionList", this.popupUnion.bigScreen.domNode)[0]);

        var mobileActionListNode = query(".esriMobilePopupInfoView .esriMobileInfoViewItem").parent()[0];
        var mobileViewItem = html.create('div', {
            'class': 'esriMobileInfoViewItem'
          }, mobileActionListNode);
        this.popupMenuButtonMobile = html.create('span', {
          'class': 'popup-menu-button'
        }, mobileViewItem);

        on(this.popupMenuButtonMobile, 'click', lang.hitch(this, this._onPopupMenuButtonClick));
        on(this.popupMenuButtonDesktop, 'click', lang.hitch(this, this._onPopupMenuButtonClick));
      },

      _onPopupMenuButtonClick: function(evt){
        var position = html.position(evt.target);
        this.popupMenu.show(position);
      },

      _bindSelectionChangeEvent: function(){
        on(this.popupUnion.bigScreen, "selection-change", lang.hitch(this, this._onSelectionChange));
        on(this.popupUnion.mobile, "selection-change", lang.hitch(this, this._onSelectionChange));
      },

      _onSelectionChange: function(evt){
        this.selectedFeature = evt.target.getSelectedFeature();
        if(!this.selectedFeature){
          html.addClass(this.popupMenuButtonDesktop, 'disabled');
          html.addClass(this.popupMenuButtonMobile, 'disabled');
          return;
        }
        this._initPopupMenu();
      },

      _initPopupMenu: function(){
        this.featureActionManager.getSupportedActions(this.selectedFeature).then(lang.hitch(this, function(actions){
          var popupActions = actions.filter(lang.hitch(this, function(action){
            return ['ZoomTo', 'ShowPopup', 'Flash'].indexOf(action.name) < 0 ;
          }));

          if(popupActions.length === 0){
            html.addClass(this.popupMenuButtonDesktop, 'disabled');
            html.addClass(this.popupMenuButtonMobile, 'disabled');
          }else{
            html.removeClass(this.popupMenuButtonDesktop, 'disabled');
            html.removeClass(this.popupMenuButtonMobile, 'disabled');
          }
          var menuActions = popupActions.map(lang.hitch(this, function(action){
            action.data = jimuUtils.toFeatureSet(this.selectedFeature);
            return action;
          }));
          this.popupMenu.setActions(menuActions);
        }));
      },

      /******************************
       * Events
       ******************************/
      onMapLoadedOrChanged: function() {
        this.isInited = false;
        this.init();
      },

      _onAppConfigChanged: function() {
        if(this.popupUnion) {
          if(this.popupUnion.bigScreen && this.popupUnion.bigScreen.hide) {
            this.popupUnion.bigScreen.hide();
            this.popupMenu.hide();
          }
          if(this.popupUnion.mobile && this.popupUnion.mobile.hide) {
            this.popupUnion.mobile.hide();
            this.popupMenu.hide();
          }
        }
      },

      _onWidgetsActionsRegistered: function(){
        //to init actions
        this.init();
      }

    });

    clazz.getInstance = function(mapManager) {
      if (instance === null) {
        instance = new clazz({
          mapManager: mapManager
        });
      }
      return instance;
    };

    return clazz;
  });


text:
package grpc

import (
	"io"

	"go.uber.org/zap"
	"google.golang.org/grpc"

	"github.com/jaegertracing/jaeger/cmd/agent/app/configmanager"
	grpcManager "github.com/jaegertracing/jaeger/cmd/agent/app/configmanager/grpc"
	"github.com/jaegertracing/jaeger/cmd/agent/app/reporter"
	"github.com/jaegertracing/jaeger/pkg/metrics"
	"github.com/jaegertracing/jaeger/pkg/multicloser"
)

// ProxyBuilder holds objects communicating with collector
type ProxyBuilder struct {
	reporter  *reporter.ClientMetricsReporter
	manager   configmanager.ClientConfigManager
	conn      *grpc.ClientConn
	tlsCloser io.Closer
}

// NewCollectorProxy creates ProxyBuilder
func NewCollectorProxy(builder *ConnBuilder, agentTags map[string]string, mFactory metrics.Factory, logger *zap.Logger) (*ProxyBuilder, error) {
	conn, err := builder.CreateConnection(logger, mFactory)
	if err != nil {
		return nil, err
	}
	grpcMetrics := mFactory.Namespace(metrics.NSOptions{Name: "", Tags: map[string]string{"protocol": "grpc"}})
	r1 := NewReporter(conn, agentTags, logger)
	r2 := reporter.WrapWithMetrics(r1, grpcMetrics)
	r3 := reporter.WrapWithClientMetrics(reporter.ClientMetricsReporterParams{
		Reporter:       r2,
		Logger:         logger,
		MetricsFactory: mFactory,
	})
	return &ProxyBuilder{
		conn:      conn,
		reporter:  r3,
		manager:   configmanager.WrapWithMetrics(grpcManager.NewConfigManager(conn), grpcMetrics),
		tlsCloser: &builder.TLS,
	}, nil
}

// GetConn returns grpc conn
func (b ProxyBuilder) GetConn() *grpc.ClientConn {
	return b.conn
}

// GetReporter returns Reporter
func (b ProxyBuilder) GetReporter() reporter.Reporter {
	return b.reporter
}

// GetManager returns manager
func (b ProxyBuilder) GetManager() configmanager.ClientConfigManager {
	return b.manager
}

// Close closes connections used by proxy.
func (b ProxyBuilder) Close() error {
	return multicloser.Wrap(b.reporter, b.tlsCloser, b.GetConn()).Close()
}


text:
package io.druid.java.util.common.parsers;

import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import junit.framework.Assert;
import org.junit.Test;

import java.util.Map;

/**
 */
public class JavaScriptParserTest
{
  @Test
  public void testParse()
  {
    final String function = "function(str) { var parts = str.split(\"-\"); return { one: parts[0], two: parts[1] } }";

    final Parser<String, Object> parser = new JavaScriptParser(
        function
    );
    String data = "foo-val1";

    final Map<String, Object> parsed = parser.parse(data);
    ImmutableMap.Builder builder = ImmutableMap.builder();
    builder.put("one", "foo");
    builder.put("two", "val1");
    Assert.assertEquals(
        "result",
        builder.build(),
        parsed
    );
  }

  @Test
  public void testParseWithMultiVal()
  {
    final String function = "function(str) { var parts = str.split(\"-\"); return { one: [parts[0], parts[1]] } }";

    final Parser<String, Object> parser = new JavaScriptParser(
        function
    );
    String data = "val1-val2";

    final Map<String, Object> parsed = parser.parse(data);
    ImmutableMap.Builder builder = ImmutableMap.builder();
    builder.put("one", Lists.newArrayList("val1", "val2"));
    Assert.assertEquals(
        "result",
        builder.build(),
        parsed
    );
  }

  @Test(expected = org.mozilla.javascript.EvaluatorException.class)
  public void testFailure()
  {
    final String function = "i am bad javascript";

    new JavaScriptParser(function);
  }
}


text:
using namespace rkcommon::math;

namespace ospray {
namespace testing {

// ----------------------------------------------------------------------------
// Builder
// ----------------------------------------------------------------------------
struct RawVolume : public detail::Builder
{
  RawVolume() = default;
  ~RawVolume() override = default;

  void commit() override;

  cpp::Group buildGroup() const override;
  cpp::World buildWorld() const override;

 private:
  std::pair<cpp::Volume, range1f> createProceduralVolume(
      std::function<bool(vec3f p)> density) const;

  cpp::VolumetricModel createVolumetricModel(
      std::pair<cpp::Volume, range1f> volume, cpp::TransferFunction tfn) const;

  float densityScale{10.f};
  float anisotropy{0.f};
  float gradientShadingScale{1.f};
  cpp::TransferFunction transferFunction;
};

// Inlined definitions ////////////////////////////////////////////////////////

std::pair<cpp::Volume, range1f> RawVolume::createProceduralVolume(
    std::function<bool(vec3f p)> density) const
{
  vec3ul dims{128}; // should be at least 2
  const float spacing = 3.f / (reduce_max(dims) - 1);
  cpp::Volume volume("structuredRegular");

  // generate volume data
  auto numVoxels = dims.product();
  std::vector<float> voxels(numVoxels, 0);
  tasking::parallel_for(dims.z, [&](uint64_t z) {
    for (uint64_t y = 0; y < dims.y; ++y) {
      for (uint64_t x = 0; x < dims.x; ++x) {
        vec3f p = vec3f(x + 0.5f, y + 0.5f, z + 0.5f) / dims;
        if (density(p))
          voxels[dims.x * dims.y * z + dims.x * y + x] =
              0.5f + 0.5f * PerlinNoise::noise(p, 12);
      }
    }
  });

  // calculate voxel range
  range1f voxelRange;
  std::for_each(voxels.begin(), voxels.end(), [&](float &v) {
    if (!std::isnan(v))
      voxelRange.extend(v);
  });

  volume.setParam("data", cpp::CopiedData(voxels.data(), dims));
  volume.setParam("gridOrigin", vec3f(-1.5f, -1.5f, -1.5f));
  volume.setParam("gridSpacing", vec3f(spacing));
  volume.commit();

  return std::make_pair(volume, voxelRange);
}

cpp::VolumetricModel RawVolume::createVolumetricModel(
    std::pair<cpp::Volume, range1f> volume, cpp::TransferFunction tfn) const
{
  tfn.setParam("valueRange", volume.second.toVec2());
  tfn.commit();

  cpp::VolumetricModel volumeModel(volume.first);
  volumeModel.setParam("densityScale", densityScale);
  volumeModel.setParam("anisotropy", anisotropy);
  volumeModel.setParam("transferFunction", tfn);
  volumeModel.setParam("gradientShadingScale", gradientShadingScale);
  volumeModel.commit();

  return volumeModel;
}

void RawVolume::commit()
{
  Builder::commit();

  densityScale = getParam<float>("densityScale", 20.f);
  anisotropy = getParam<float>("anisotropy", 0.f);
  gradientShadingScale =
      getParam<float>("gradientShadingScale", gradientShadingScale);
  transferFunction = getParam<cpp::TransferFunction>(
      "transferFunction", makeTransferFunction({0.f, 1.f}));
}

cpp::Group RawVolume::buildGroup() const
{
  cpp::Group group;

  std::vector<cpp::VolumetricModel> volumetricModels;
  {
    volumetricModels.emplace_back(createVolumetricModel(
        createProceduralVolume(
            [](const vec3f &p) { return turbulentSphere(p, 1.f); }),
        transferFunction));

    volumetricModels.emplace_back(createVolumetricModel(
        createProceduralVolume(
            [](const vec3f &p) { return turbulentTorus(p, 1.f, 0.375f); }),
        transferFunction));

    for (auto volumetricModel : volumetricModels)
      volumetricModel.commit();

    if (!volumetricModels.empty())
      group.setParam("volume", cpp::CopiedData(volumetricModels));
  }

  group.commit();

  return group;
}

cpp::World RawVolume::buildWorld() const
{
  auto group = buildGroup();

  std::vector<cpp::Instance> instanceHandles;
  {
    cpp::Instance instance(group);
    rkcommon::math::AffineSpace3f xform(
        rkcommon::math::LinearSpace3f::scale(1.f), vec3f(0.f, 0.f, 0.f));
    instance.setParam("xfm", xform);
    instance.commit();

    instanceHandles.push_back(instance);

    if (addPlane)
      instanceHandles.push_back(makeGroundPlane(instance.getBounds<box3f>()));
  }

  std::vector<cpp::Light> lightHandles;
  {
    cpp::Light quadLight("quad");
    quadLight.setParam("position", vec3f(-4.0f, 3.0f, 1.0f));
    quadLight.setParam("edge1", vec3f(0.f, 0.0f, -1.0f));
    quadLight.setParam("edge2", vec3f(1.0f, 0.5, 0.0f));
    quadLight.setParam("intensity", 50.0f);
    quadLight.setParam("color", vec3f(2.6f, 2.5f, 2.3f));
    quadLight.commit();
    lightHandles.push_back(quadLight);

    cpp::Light ambientLight("ambient");
    ambientLight.setParam("intensity", 0.4f);
    ambientLight.setParam("color", vec3f(1.f));
    ambientLight.setParam("visible", false);
    ambientLight.commit();
    lightHandles.push_back(ambientLight);
  }

  cpp::World world;
  world.setParam("instance", cpp::CopiedData(instanceHandles));
  world.setParam("light", cpp::CopiedData(lightHandles));

  return world;
}

OSP_REGISTER_TESTING_BUILDER(RawVolume, raw_volume);

} // namespace testing
} // namespace ospray


text:
<!DOCTYPE html>

        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
        <meta name="description" content="" />
        <meta name="author" content="" />

        <title><?php echo $this->template->title->default("Default title"); ?></title>
        <?php echo $this->template->meta; ?>

        <?= get_asset('css', 'bootstrap.css'); ?>
        <?= get_asset('css', 'font-awesome.min.css'); ?>
        <?= get_asset('css', 'style.css'); ?>

        <link href='http://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css' />

                    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">

                    </button>
                    <?php echo $this->template->title->default("Default title"); ?>

HOME

PORTFOLIO

ABOUT

CONTACT

        <?= $this->template->content; ?>

            2014 www.yourdomain.com | All Right Reserved  | Design by www.binarytheme.com

        <?= get_asset('js', 'jquery-1.10.2.js'); ?>
        <?= get_asset('js', 'bootstrap.js'); ?>
        <?= get_asset('js', 'jquery.easing.min.js'); ?>
        <?= get_asset('js', 'custom.js'); ?>


text:
/**
 * Bootstrap Table Japanese translation
 * Author: Azamshul Azizy <azamshul@gmail.com>
 */
(function ($) {
    'use strict';

    $.fn.bootstrapTable.locales['ja-JP'] = {
        formatLoadingMessage: function () {
            return '読み込み中です。少々お待ちください。';
        },
        formatRecordsPerPage: function (pageNumber) {
            return 'ページ当たり最大' + pageNumber + '件';
        },
        formatShowingRows: function (pageFrom, pageTo, totalRows) {
            return '全' + totalRows + '件から、'+ pageFrom + 'から' + pageTo + '件目まで表示しています';
        },
        formatSearch: function () {
            return '検索';
        },
        formatNoMatches: function () {
            return '該当するレコードが見つかりません';
        },
        formatPaginationSwitch: function () {
            return 'ページ数を表示・非表示';
        },
        formatRefresh: function () {
            return '更新';
        },
        formatToggle: function () {
            return 'トグル';
        },
        formatColumns: function () {
            return '列';
        },
        formatAllRows: function () {
            return 'すべて';
        }
    };

    $.extend($.fn.bootstrapTable.defaults, $.fn.bootstrapTable.locales['ja-JP']);

})(jQuery);


text:
class Solution:
    # @param digits, a list of integer digits
    # @return a list of integer digits
    def plusOne(self, digits):
        res_stack = []
        rest = 1
        for i in range(len(digits)-1, -1, -1):
            res_stack.append((rest + digits[i]) % 10)
            rest = (rest + digits[i]) // 10
        if rest == 1:
            res_stack.append(rest)
        return list(reversed(res_stack))


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.cloudfunctions.v2beta.model;

/**
 * Describes a runtime and any special information (e.g., deprecation status) related to it.
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the Cloud Functions API. For a detailed explanation see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class Runtime extends com.google.api.client.json.GenericJson {

  /**
   * The user facing name, eg 'Go 1.13', 'Node.js 12', etc.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String displayName;

  /**
   * The environment for the runtime.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String environment;

  /**
   * The name of the runtime, e.g., 'go113', 'nodejs12', etc.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String name;

  /**
   * The stage of life this runtime is in, e.g., BETA, GA, etc.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String stage;

  /**
   * Warning messages, e.g., a deprecation warning.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.util.List<java.lang.String> warnings;

  /**
   * The user facing name, eg 'Go 1.13', 'Node.js 12', etc.
   * @return value or {@code null} for none
   */
  public java.lang.String getDisplayName() {
    return displayName;
  }

  /**
   * The user facing name, eg 'Go 1.13', 'Node.js 12', etc.
   * @param displayName displayName or {@code null} for none
   */
  public Runtime setDisplayName(java.lang.String displayName) {
    this.displayName = displayName;
    return this;
  }

  /**
   * The environment for the runtime.
   * @return value or {@code null} for none
   */
  public java.lang.String getEnvironment() {
    return environment;
  }

  /**
   * The environment for the runtime.
   * @param environment environment or {@code null} for none
   */
  public Runtime setEnvironment(java.lang.String environment) {
    this.environment = environment;
    return this;
  }

  /**
   * The name of the runtime, e.g., 'go113', 'nodejs12', etc.
   * @return value or {@code null} for none
   */
  public java.lang.String getName() {
    return name;
  }

  /**
   * The name of the runtime, e.g., 'go113', 'nodejs12', etc.
   * @param name name or {@code null} for none
   */
  public Runtime setName(java.lang.String name) {
    this.name = name;
    return this;
  }

  /**
   * The stage of life this runtime is in, e.g., BETA, GA, etc.
   * @return value or {@code null} for none
   */
  public java.lang.String getStage() {
    return stage;
  }

  /**
   * The stage of life this runtime is in, e.g., BETA, GA, etc.
   * @param stage stage or {@code null} for none
   */
  public Runtime setStage(java.lang.String stage) {
    this.stage = stage;
    return this;
  }

  /**
   * Warning messages, e.g., a deprecation warning.
   * @return value or {@code null} for none
   */
  public java.util.List<java.lang.String> getWarnings() {
    return warnings;
  }

  /**
   * Warning messages, e.g., a deprecation warning.
   * @param warnings warnings or {@code null} for none
   */
  public Runtime setWarnings(java.util.List<java.lang.String> warnings) {
    this.warnings = warnings;
    return this;
  }

  @Override
  public Runtime set(String fieldName, Object value) {
    return (Runtime) super.set(fieldName, value);
  }

  @Override
  public Runtime clone() {
    return (Runtime) super.clone();
  }

}


text:
<?php
namespace App\Commands;

use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;
use Carbon\Carbon;

use App\Models\User, App\Models\Device, App\Models\Tracking, App\Models\DataSet, App\Models\DataPoint;
use NestApi\Nest;

class NestData extends Command {

	/**
	 * The console command name.
	 *
	 * @var string
	 */
	protected $name = 'nest:data';

	/**
	 * The console command description.
	 *
	 * @var string
	 */
	protected $description = 'Start record data from Nest devices.';

	/**
	 * Create a new command instance.
	 *
	 * @return void
	 */
	public function __construct()
	{
		parent::__construct();
	}

	/**
	 * Execute the console command.
	 *
	 * @return mixed
	 */
	public function fire()
	{
		$dataInterval = 2;
		$trackingDevices = Tracking::where( 'active', '=', '1' )->get();

		$lastDate = -1;
		while ( true ){

			$date = date('i');
			if ( $lastDate == $date || $date % $dataInterval != 0 ){

				// Take a break
				sleep( 10 );

				// Update the list of devices we are tracking
				$trackingDevices = Tracking::where( 'active', '=', '1' )->get();

				// Move on
				continue;
			}
			$lastDate = $date;

			foreach ( $trackingDevices as $trackingDevice ){

				// Setup some variables
				$dataSet = $trackingDevice->data_set;
				$device = $trackingDevice->device;
				$user = $device->user;

				// Open the nest connection
				$nest = new Nest( $user->email, $user->nest_password );

				// If we don't have a data set or our data interval is out of whack, we need a new data set
				if ( $dataSet === null || ( $dataSet->last_data !== null && Carbon::now()->diffInMinutes( $dataSet->last_data->date ) > $dataInterval ) ){
					$dataSet = new DataSet;
					$trackingDevice->device->dataSets()->save( $dataSet );
					$trackingDevice->dataSet()->associate( $dataSet );
					$trackingDevice->save();
				}

				print "\nNew Data Point\n";
				$ts = date('Y-m-d H:i:s');

				// Get the device and weather information
				$deviceData = $nest->getDeviceInfo( $device->serial );
				$weatherData = $nest->getWeather( $device->postal );
				//var_dump( $deviceData );

				// Handle different variations for the target temperature
				switch ( $deviceData->target->mode ){
					case 'range':
						$target_heat = $deviceData->target->temperature[0];
						$target_cool = $deviceData->target->temperature[1];
						break;
					case 'heat':
						$target_heat = $deviceData->target->temperature;
						$target_cool = null;
						break;
					case 'cool':
						$target_heat = null;
						$target_cool = $deviceData->target->temperature;
						break;
					default:
						$target_heat = null;
						$target_cool = null;
				}

				// Make the data record
				$dataPoint = new DataPoint;
				$dataPoint->data_set_id = $dataSet->id;
				$dataPoint->temperature = $deviceData->current_state->temperature;
				$dataPoint->outside_temperature = $weatherData->outside_temperature;
				$dataPoint->humidity = $deviceData->current_state->humidity;
				$dataPoint->outside_humidity = $weatherData->outside_humidity;
				$dataPoint->target_heat = $target_heat;
				$dataPoint->target_cool = $target_cool;
				$dataPoint->ac = $deviceData->current_state->ac;
				$dataPoint->heat = $deviceData->current_state->heat;
				$dataPoint->aux_heat = $deviceData->current_state->alt_heat;
				$dataPoint->fan = $deviceData->current_state->fan;
				$dataPoint->date = $ts;
				$dataPoint->save();

				// Update the data set
				$dataSet->lastData()->associate( $dataPoint );
				if ( $dataSet->first_data === null ){
					$dataSet->firstData()->associate( $dataPoint );
				}
				$dataSet->save();

				var_dump( $dataPoint->toArray() );
			}
		}
	}

	/**
	 * Get the console command arguments.
	 *
	 * @return array
	 */
	protected function getArguments()
	{
		return [];
		/*
		return array(
			array('example', InputArgument::REQUIRED, 'An example argument.'),
		);
		*/
	}

	/**
	 * Get the console command options.
	 *
	 * @return array
	 */
	protected function getOptions()
	{
		return [];
		/*
		return array(
			array('example', null, InputOption::VALUE_OPTIONAL, 'An example option.', null),
		);
		*/
	}

}


text:
	Cldr._raw = {};

	/**
	 * Cldr.load( json [, json, ...] )
	 *
	 * @json [JSON] CLDR data or [Array] Array of @json's.
	 *
	 * Load resolved or unresolved cldr data.
	 * Overwrite Cldr.load().
	 */
	Cldr.load = function() {
		Cldr._raw = coreLoad( Cldr, Cldr._raw, arguments );
	};

	/**
	 * Overwrite Cldr.prototype.get().
	 */
	Cldr.prototype.get = function( path ) {
		validatePresence( path, "path" );
		validateTypePath( path, "path" );

		// 1: use bundle as locale on item lookup for simplification purposes, because no other extended subtag is used anyway on bundle parent lookup.
		// 2: during init(), this method is called, but bundle is yet not defined. Use "" as a workaround in this very specific scenario.
		return itemLookup( Cldr, this.attributes && this.attributes.bundle /* 1 */ || "" /* 2 */, path, this.attributes );
	};

	// In case cldr/unresolved is loaded after cldr/event, we trigger its overloads again. Because, .get is overwritten in here.
	if ( Cldr._eventInit ) {
		Cldr._eventInit();
	}

	return Cldr;


text:
/*
 * Angular 2 decorators and services
 */
import {
  Component,
  OnInit,
  ViewEncapsulation
} from '@angular/core';
import { AppState } from './app.service';

/*
 * App Component
 * Top Level Component
 */
@Component({
  selector: 'app',
  encapsulation: ViewEncapsulation.None,
  styleUrls: [
    './app.component.scss'
  ],
  templateUrl: './app.component.html'
})
export class AppComponent implements OnInit {
  public angularclassLogo = 'assets/img/angularclass-avatar.png';
  public name = 'Angular 2 Webpack Starter';
  public url = 'https://twitter.com/AngularClass';

  constructor(
    public appState: AppState
  ) { }

  public ngOnInit() {
    console.log('Initial App State', this.appState.state);
  }

}

/*
 * Please review the https://github.com/AngularClass/angular2-examples/ repo for
 * more angular app examples that you may copy/paste
 * (The examples may not be updated as quickly. Please open an issue on github for us to update it)
 * For help or questions please contact us at @AngularClass on twitter
 * or our chat on Slack at https://AngularClass.com/slack-join
 */


text:
var async = require('async'),
	crypto = require('crypto'),
	execFile = require('child_process').execFile,
	fs = require('fs'),
	merge = require('merge'),
	path = require('path'),
	request = require('request'),
	rimraf = require('rimraf');

var defaultOptions = {
	hash: 'sha256'
};

function bareName(file) {
	return path.basename(file, path.extname(file));
}

try {
	addons = JSON.parse(fs.readFileSync('addons.json'));
} catch (err) {
	addons = {};
}

exports.addons = addons;

function saveAddons(callback) {
	return fs.writeFile('addons.json', JSON.stringify(addons, null, '\t'), callback);
}

function extractBlInfo(content, callback) {
	var match = /bl_info\s*=\s*\{[^]*?\}/.exec(content.toString());
	if (!match) {
		return callback(new Error('bl_info missing.'));
	}

	var python = execFile('python', function(err, stdout, stderr) {
		if (err) {
			return callback(err);
		}
		return callback(null, JSON.parse(stdout));
	});

	python.stdin.write(match[0]);
	python.stdin.write('\nimport json\nprint(json.dumps(bl_info, separators=(",", ":")))');
	return python.stdin.end();
}

exports.add = function(url, options, callback) {
	if (!callback) {
		callback = options;
		options = {};
	}
	options = merge(defaultOptions, options);

	if (!url) {
		return callback('Please give an url');
	}

	var hashAlgorithm = options.hash || 'sha256';
	if (crypto.getHashes().indexOf(hashAlgorithm) === -1) {
		throw hashAlgorithm + ' is not supported';
	}

	function handleScript(name, content) {
		var h = crypto.createHash(hashAlgorithm);
		h.update(content);
		var hash = h.digest('hex');

		function addToAddons(name, content, file, peers, callback) {
			return extractBlInfo(content, function(err, info) {
				if (err) {
					return callback(err);
				}

				var fields = ['name', 'description', 'author', 'version', 'blender', 'location', 'category'];
				for (var i = 0, n = fields.length; i < n; ++i) {
					var field = fields[i];
					if (!info.hasOwnProperty(field)) {
						return callback(new Error('Missing field: ' + field + '.'));
					}
				}

				var addon = {
					info: info,
					url: url
				};

				addon[hashAlgorithm] = hash;

				if (peers.length) {
					addon.peers = peers;
				}

				if (file) {
					addon.file = file;
				}

				addons[name] = addon;

				if (!options.simulate) {
					return saveAddons(addons, function(err) {
						return callback(err, addon);
					});
				} else {
					return callback(null, addon);
				}
			});
		}

		return addToAddons(name, content, true, [], function(err, addon) {
			if (err) {
				return async.waterfall([
					function(callback) {
						return rimraf('tmp', callback);
					},
					function(callback) {
						return fs.mkdir('tmp', callback);
					},
					function(callback) {
						return fs.writeFile('tmp/download', content, callback);
					},
					function(callback) {
						return execFile('7z', ['x', '-otmp/archive', 'tmp/download'], callback);
					},
					function(stdout, stderr, callback) {
						var archiveDir = 'tmp/archive';
						return fs.readdir(archiveDir, function(err, files) {
							if (err) {
								return callback(err);
							}

							return async.map(files, function(file, callback) {
								var ext = path.extname(file);
								if (file === '__MACOSX' || ext !== '' || ext !== '.py') {
									return callback();
								}

								var archiveFile = path.join(archiveDir, file);
								return fs.stat(archiveFile, function(err, stats) {
									if (err) {
										return callback(err);
									}

									if (stats.isFile()) {
										return fs.readFile(archiveFile, function(err, content) {
											return callback(err, [bareName(file), content, false]);
										});
									}

									if (stats.isDirectory()) {
										return fs.readFile(path.join(archiveFile, '__init__.py'), function(err, content) {
											return callback(err, [file, content, false]);
										});
									}

									return callback();
								});
							}, callback);
						});
					},
					function(descs, callback) {
						descs = descs.filter(function(desc) {
							return !!desc;
						});

						return async.map(descs, function(desc, callback) {
							desc.push(descs.filter(function(d) {
								return d !== desc;
							}).map(function(d) {
								return d[0];
							}));
							desc.push(callback);
							return addToAddons.apply(this, desc);
						}, callback);
					},
					function(addons, callback) {
						return rimraf('tmp', function(err) {
							return callback(err, addons);
						});
					}
				], callback);
			} else {
				return callback(null, addon);
			}
		});
	}

	if (url.indexOf('://') !== -1) {
		return request({
			url: url,
			encoding: null
		}, function(err, response, body) {
			if (err) {
				return callback(err);
			}

			if (response.statusCode !== 200) {
				return callback(new Error(response.statusCode + ': ' + body));
			}

			return handleScript(bareName(url.split('/').pop()), body);
		});
	} else {
		return fs.readFile(url, function(err, content) {
			if (err) return callback(err);
			return handleScript(path.basename(url, path.extname(url)), content);
		});
	}
};

exports.list = function(options, callback) {
	if (!callback) {
		callback = options;
		options = {};
	}
	options = merge(defaultOptions, options);

	var list = [];
	for (var name in addons) {
		var info = addons[name].info;
		list.push(name + ': ' + info.version.join('.'));
	}
	list.sort().forEach(function(item) {
		return console.log(item);
	});
	return callback();
};

exports.remove = function(name, options, callback) {
	if (!callback) {
		callback = options;
		options = {};
	}
	options = merge(defaultOptions, options);

	if (!addons.hasOwnProperty(name)) {
		return callback(name + " is not in the registry");
	}

	delete addons[name];

	if (!options.simulate) {
		return saveAddons(callback);
	} else {
		return callback();
	}
};

if (require.main === module) {
	ycommands = require('ycommands')
		.usage('Usage: $0 command')
		.help('h')
		.options('hash', {
			default: defaultOptions.hash,
			description: 'Hash algorithm'
		})
		.option('s', {
			alias: 'simulate',
			boolean: true,
			description: 'Do not save changes to addons.json'
		})
		.command('add url|path ...', 'Add some addons', function(argv, callback) {
			return async.each(argv._.slice(1), function(url, callback) {
				return exports.add(url, argv, callback);
			}, callback);
		})
		.command('list', 'List addons', exports.list)
		.command('remove name ...', 'Remove some addons', function(argv, callback) {
			return async.each(argv._.slice(1), function(name, callback) {
				return exports.remove(name, argv, callback);
			}, callback);
		})
		.command('update [name ...]', 'Update some or all addons', function(argv, callback) {
			var names = (argv._.length > 1 ? argv._.slice(1) : Object.keys(addons));
			return async.each(names, function(name, callback) {
				return exports.add(addons[name].url, argv, callback);
			}, callback);
		})
		.execute(function(err) {
			if (err) {
				throw err;
			}
		});
}


text:
from setuptools import setup, find_packages
import sys

with open('requirements.txt') as f:
    reqs = f.read()

reqs = reqs.strip().split('\n')

install = [req for req in reqs if not req.startswith("git+git://")]
depends = [req.replace("git+git://","git+http://") for req in reqs if req.startswith("git+git://")]

setup(
    name='fever-scorer',
    version='0.0.0',
    author='James Thorne',
    author_email='james@jamesthorne.co.uk',
    url='https://jamesthorne.co.uk',
    description='Fact Extraction and VERification scorer',
    long_description="readme",
    license=license,
    package_dir={'fever': 'src/fever'},
    packages=['fever'],
    install_requires=install,
    dependency_links=depends,
)


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

import { jqxTreeGridComponent } from '../../../../../jqwidgets-ts/angular_jqxtreegrid';

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html'
})

export class AppComponent {
    @ViewChild('TreeGrid') treeGrid: jqxTreeGridComponent;

    data: any[] = [
        {
            'id': '1', 'name': 'Corporate Headquarters', 'budget': '1230000', 'location': 'Las Vegas',
            'children':
            [
                {
                    'id': '2', 'name': 'Finance Division', 'budget': '423000', 'location': 'San Antonio',
                    'children':
                    [
                        {
                            'id': '4', 'name': 'Investment Department', 'budget': '310000', 'location': 'San Antonio',
                            'children':
                            [
                                { 'id': '5', 'name': 'Banking Office', 'budget': '240000', 'location': 'San Antonio' },
                                { 'id': '6', 'name': 'Bonds Office', 'budget': '70000', 'location': 'San Antonio' },
                            ]
                        },
                        { 'id': '3', 'name': 'Accounting Department', 'budget': '113000', 'location': 'San Antonio' }
                    ]
                },
                {
                    'id': '7', 'name': 'Operations Division', 'budget': '600000', 'location': 'Miami',
                    'children':
                    [
                        { 'id': '8', 'name': 'Manufacturing Department', 'budget': '300000', 'location': 'Miami' },
                        { 'id': '9', 'name': 'Public Relations Department', 'budget': '200000', 'location': 'Miami' },
                        { 'id': '10', 'name': 'Sales Department', 'budget': '100000', 'location': 'Miami' }
                    ]
                },
                { 'id': '11', 'name': 'Research Division', 'budget': '200000', 'location': 'Boston' },
                { 'id': '12', 'name': 'Development Division', 'budget': '300000', 'location': 'Boston' }
            ]
        }
    ];

    source: any =
    {
        dataType: 'json',
        dataFields: [
            { name: 'name', type: 'string' },
            { name: 'budget', type: 'number' },
            { name: 'id', type: 'number' },
            { name: 'children', type: 'array' },
            { name: 'location', type: 'string' }
        ],
        hierarchy:
        {
            root: 'children'
        },
        localData: this.data,
        id: 'id'
    };

    dataAdapter: any = new jqx.dataAdapter(this.source);

    columns: any[] = [
        { text: 'Name', align: 'left', dataField: 'name', width: 300 },
        { text: 'Location', dataField: 'location', cellsAlign: 'left', align: 'left', width: 250 },
        {
            text: 'Budget', cellsAlign: 'right', align: 'right', dataField: 'budget', cellsFormat: 'c2',
            aggregates: [{
                'Total':
                (aggregatedValue, currentValue, column, record, aggregateLevel) => {
                    if (record.checked && record.level === aggregateLevel) {
                        return aggregatedValue + currentValue;
                    }
                    else {
                        return aggregatedValue;
                    }
                }
            }],
            aggregatesRenderer: (aggregatesText, column, element, aggregates, type) => {
                let renderString = '';
                if (type == 'aggregates') {
                    renderString = '
';
                }
                else {
                    renderString = '
';
                }

                let euro = this.dataAdapter.formatNumber(0.74 * aggregates.Total, 'f2');
                let usd = this.dataAdapter.formatNumber(aggregates.Total, 'f2');
                renderString += "

Total: 	" + usd + " USD
" + euro + " EUR

";
                return renderString;
            }
        }
    ];

    ready(): void {
        this.treeGrid.expandRow(1);
        this.treeGrid.expandRow(2);
    };
}


text:
var utils = require('../utils');
var chalk = require('chalk');
var _ = require('lodash');
var spawn = require('child_process').spawn;

exports.register = function(template, name, options) {
  template = utils.resolveTemplate(template);
  var tmplName = template.split('/').pop().replace('.git', '');
  var args = ['clone', template];

  if (name) {
    args.push(name);
  }

  spawn('git', args, { stdio: 'inherit', cwd: options.root }).on('close', function(code) {
    var key = name || tmplName;
    options.config.templates = options.config.templates || [];
    options.config.templates.push({
      key: key,
      value: {
        path: options.root + '/' + key
      }
    });

    utils.writeBlock(chalk.green('Registered ' + tmplName + (name ? ' as ' + name : '') + '.'));
    utils.writeConfig(options, utils.exit);
  });
};

exports.config = function(maybeOpts) {
  var options = [].slice.call(arguments, -1).pop();
  if (maybeOpts !== options) {
    utils.spawn('config', options).on('close', utils.exit);
  } else {
    // No additional parameters (e.g. "set/get") were passed.
    // Instead, log some help-ish info about config, including
    // the currently possible config parameters.
    utils.writeBlock(
      'The following config values can be set:',
      ['   ', exports.writeOpt('username'), 'Your github username.', chalk.cyan('<String>')],
      ['   ', exports.writeOpt('pattern'), 'Interpolation style or regex pattern.', chalk.cyan('<String|RegExp>')],
      ['   ', exports.writeOpt('private'), 'New repos should marked private.', chalk.cyan('<Boolean>')],
      ['   ', exports.writeOpt('wiki'), 'New repos should include a wiki.', chalk.cyan('<Boolean>')],
      ['   ', exports.writeOpt('issues'), 'New repos should include an issues page.', chalk.cyan('<Boolean>')]
    );
    utils.writeBlock('Additionally, any option besides username can be specified on a registered template with dot notation (e.g. "templateName.wiki")');
  }
};

exports.writeOpt = function(opt) {
  return _.rpad(chalk.magenta(opt) + ':', 20);
};


text:
package fr.openwide.core.jpa.more.business.history.service;

import java.util.Locale;

import com.google.common.base.Optional;

import fr.openwide.core.commons.util.rendering.IRenderer;
import fr.openwide.core.jpa.more.business.history.model.embeddable.HistoryValue;

public interface IHistoryValueService {

	<T> HistoryValue create(T object);

	<T> HistoryValue create(T value, IRenderer<? super T> renderer);

	Object retrieve(HistoryValue value);

	@SuppressWarnings("rawtypes")
	String render(HistoryValue value, IRenderer renderer, Locale locale);

	String render(HistoryValue value, Locale locale);

	/**
	 * @param historyValue The {@link HistoryValue} to be matched against.
	 * @param value The value that we want to compare to historyValue
	 * @return Optional.of(true) or Optional.of(false) if the answer could be determined, or
	 * Optional.absent() if there is not enough information in the {@link HistoryValue} to give a
	 * definitive answer.
	 */
	Optional<Boolean> matches(HistoryValue historyValue, Object value);

}


text:
using testing::NiceMock;

namespace Envoy {
namespace Extensions {
namespace StatSinks {
namespace Hystrix {
namespace {

TEST(StatsConfigTest, ValidHystrixSink) {
  const std::string name = StatsSinkNames::get().Hystrix;

  envoy::config::metrics::v3::HystrixSink sink_config;

  Server::Configuration::StatsSinkFactory* factory =
      Registry::FactoryRegistry<Server::Configuration::StatsSinkFactory>::getFactory(name);
  ASSERT_NE(factory, nullptr);

  ProtobufTypes::MessagePtr message = factory->createEmptyConfigProto();
  TestUtility::jsonConvert(sink_config, *message);

  NiceMock<Server::Configuration::MockServerFactoryContext> server;
  Stats::SinkPtr sink = factory->createStatsSink(*message, server);
  EXPECT_NE(sink, nullptr);
  EXPECT_NE(dynamic_cast<Hystrix::HystrixSink*>(sink.get()), nullptr);
}

} // namespace
} // namespace Hystrix
} // namespace StatSinks
} // namespace Extensions
} // namespace Envoy


text:
const {session, contextGroup, Protocol} = InspectorTest.start('Checks that Runtime.getIsolateId works');

(async function test() {
  const id = await Protocol.Runtime.getIsolateId();
  console.assert(typeof id === 'string');
  console.assert(id.length > 0);
  InspectorTest.completeTest();
})();


text:
use crate::container::public_access_from_header;
use crate::prelude::*;
use azure_sdk_core::errors::{check_status_extract_headers_and_body, AzureError};
use azure_sdk_core::lease::LeaseId;
use azure_sdk_core::prelude::*;
use azure_sdk_core::{No, StoredAccessPolicyList, ToAssign, Yes};
use azure_sdk_storage_core::prelude::*;
use hyper::{Method, StatusCode};
use std::marker::PhantomData;

#[derive(Debug, Clone)]
pub struct SetACLBuilder<'a, C, ContainerNameSet, PublicAccessSet>
where
    ContainerNameSet: ToAssign,
    PublicAccessSet: ToAssign,
    C: Client,
{
    client: &'a C,
    p_container_name: PhantomData<ContainerNameSet>,
    p_public_access: PhantomData<PublicAccessSet>,
    container_name: Option<&'a str>,
    public_access: PublicAccess,
    stored_access_policy_list: Option<&'a StoredAccessPolicyList>,
    client_request_id: Option<&'a str>,
    timeout: Option<u64>,
    lease_id: Option<&'a LeaseId>,
}

impl<'a, C> SetACLBuilder<'a, C, No, No>
where
    C: Client,
{
    #[inline]
    pub(crate) fn new(client: &'a C) -> SetACLBuilder<'a, C, No, No> {
        SetACLBuilder {
            client,
            p_container_name: PhantomData {},
            container_name: None,
            p_public_access: PhantomData {},
            public_access: PublicAccess::None,
            stored_access_policy_list: None,
            client_request_id: None,
            timeout: None,
            lease_id: None,
        }
    }
}

impl<'a, C, ContainerNameSet, PublicAccessSet> ClientRequired<'a, C>
    for SetACLBuilder<'a, C, ContainerNameSet, PublicAccessSet>
where
    ContainerNameSet: ToAssign,
    PublicAccessSet: ToAssign,
    C: Client,
{
    #[inline]
    fn client(&self) -> &'a C {
        self.client
    }
}

//get mandatory no traits methods

//set mandatory no traits methods
impl<'a, C, PublicAccessSet> ContainerNameRequired<'a>
    for SetACLBuilder<'a, C, Yes, PublicAccessSet>
where
    PublicAccessSet: ToAssign,
    C: Client,
{
    #[inline]
    fn container_name(&self) -> &'a str {
        self.container_name.unwrap()
    }
}

impl<'a, C, ContainerNameSet> PublicAccessRequired for SetACLBuilder<'a, C, ContainerNameSet, Yes>
where
    ContainerNameSet: ToAssign,
    C: Client,
{
    #[inline]
    fn public_access(&self) -> PublicAccess {
        self.public_access
    }
}

impl<'a, C, ContainerNameSet, PublicAccessSet> StoredAccessPolicyListOption<'a>
    for SetACLBuilder<'a, C, ContainerNameSet, PublicAccessSet>
where
    ContainerNameSet: ToAssign,
    PublicAccessSet: ToAssign,
    C: Client,
{
    #[inline]
    fn stored_access_policy_list(&self) -> Option<&'a StoredAccessPolicyList> {
        self.stored_access_policy_list
    }
}

impl<'a, C, ContainerNameSet, PublicAccessSet> ClientRequestIdOption<'a>
    for SetACLBuilder<'a, C, ContainerNameSet, PublicAccessSet>
where
    ContainerNameSet: ToAssign,
    PublicAccessSet: ToAssign,
    C: Client,
{
    #[inline]
    fn client_request_id(&self) -> Option<&'a str> {
        self.client_request_id
    }
}

impl<'a, C, ContainerNameSet, PublicAccessSet> TimeoutOption
    for SetACLBuilder<'a, C, ContainerNameSet, PublicAccessSet>
where
    ContainerNameSet: ToAssign,
    PublicAccessSet: ToAssign,
    C: Client,
{
    #[inline]
    fn timeout(&self) -> Option<u64> {
        self.timeout
    }
}

impl<'a, C, ContainerNameSet, PublicAccessSet> LeaseIdOption<'a>
    for SetACLBuilder<'a, C, ContainerNameSet, PublicAccessSet>
where
    ContainerNameSet: ToAssign,
    PublicAccessSet: ToAssign,
    C: Client,
{
    #[inline]
    fn lease_id(&self) -> Option<&'a LeaseId> {
        self.lease_id
    }
}

impl<'a, C, PublicAccessSet> ContainerNameSupport<'a> for SetACLBuilder<'a, C, No, PublicAccessSet>
where
    PublicAccessSet: ToAssign,
    C: Client,
{
    type O = SetACLBuilder<'a, C, Yes, PublicAccessSet>;

    #[inline]
    fn with_container_name(self, container_name: &'a str) -> Self::O {
        SetACLBuilder {
            client: self.client,
            p_container_name: PhantomData {},
            p_public_access: PhantomData {},
            container_name: Some(container_name),
            public_access: self.public_access,
            stored_access_policy_list: self.stored_access_policy_list,
            client_request_id: self.client_request_id,
            timeout: self.timeout,
            lease_id: self.lease_id,
        }
    }
}

impl<'a, C, ContainerNameSet> PublicAccessSupport for SetACLBuilder<'a, C, ContainerNameSet, No>
where
    ContainerNameSet: ToAssign,
    C: Client,
{
    type O = SetACLBuilder<'a, C, ContainerNameSet, Yes>;

    #[inline]
    fn with_public_access(self, public_access: PublicAccess) -> Self::O {
        SetACLBuilder {
            client: self.client,
            p_container_name: PhantomData {},
            p_public_access: PhantomData {},
            container_name: self.container_name,
            public_access,
            stored_access_policy_list: self.stored_access_policy_list,
            client_request_id: self.client_request_id,
            timeout: self.timeout,
            lease_id: self.lease_id,
        }
    }
}

impl<'a, C, ContainerNameSet, PublicAccessSet> StoredAccessPolicyListSupport<'a>
    for SetACLBuilder<'a, C, ContainerNameSet, PublicAccessSet>
where
    ContainerNameSet: ToAssign,
    PublicAccessSet: ToAssign,
    C: Client,
{
    type O = SetACLBuilder<'a, C, ContainerNameSet, PublicAccessSet>;

    #[inline]
    fn with_stored_access_policy_list(
        self,
        stored_access_policy_list: &'a StoredAccessPolicyList,
    ) -> Self::O {
        SetACLBuilder {
            client: self.client,
            p_container_name: PhantomData {},
            p_public_access: PhantomData {},
            container_name: self.container_name,
            public_access: self.public_access,
            stored_access_policy_list: Some(stored_access_policy_list),
            client_request_id: self.client_request_id,
            timeout: self.timeout,
            lease_id: self.lease_id,
        }
    }
}

impl<'a, C, ContainerNameSet, PublicAccessSet> ClientRequestIdSupport<'a>
    for SetACLBuilder<'a, C, ContainerNameSet, PublicAccessSet>
where
    ContainerNameSet: ToAssign,
    PublicAccessSet: ToAssign,
    C: Client,
{
    type O = SetACLBuilder<'a, C, ContainerNameSet, PublicAccessSet>;

    #[inline]
    fn with_client_request_id(self, client_request_id: &'a str) -> Self::O {
        SetACLBuilder {
            client: self.client,
            p_container_name: PhantomData {},
            p_public_access: PhantomData {},
            container_name: self.container_name,
            public_access: self.public_access,
            stored_access_policy_list: self.stored_access_policy_list,
            client_request_id: Some(client_request_id),
            timeout: self.timeout,
            lease_id: self.lease_id,
        }
    }
}

impl<'a, C, ContainerNameSet, PublicAccessSet> TimeoutSupport
    for SetACLBuilder<'a, C, ContainerNameSet, PublicAccessSet>
where
    ContainerNameSet: ToAssign,
    PublicAccessSet: ToAssign,
    C: Client,
{
    type O = SetACLBuilder<'a, C, ContainerNameSet, PublicAccessSet>;

    #[inline]
    fn with_timeout(self, timeout: u64) -> Self::O {
        SetACLBuilder {
            client: self.client,
            p_container_name: PhantomData {},
            p_public_access: PhantomData {},
            container_name: self.container_name,
            public_access: self.public_access,
            stored_access_policy_list: self.stored_access_policy_list,
            client_request_id: self.client_request_id,
            timeout: Some(timeout),
            lease_id: self.lease_id,
        }
    }
}

impl<'a, C, ContainerNameSet, PublicAccessSet> LeaseIdSupport<'a>
    for SetACLBuilder<'a, C, ContainerNameSet, PublicAccessSet>
where
    ContainerNameSet: ToAssign,
    PublicAccessSet: ToAssign,
    C: Client,
{
    type O = SetACLBuilder<'a, C, ContainerNameSet, PublicAccessSet>;

    #[inline]
    fn with_lease_id(self, lease_id: &'a LeaseId) -> Self::O {
        SetACLBuilder {
            client: self.client,
            p_container_name: PhantomData {},
            p_public_access: PhantomData {},
            container_name: self.container_name,
            public_access: self.public_access,
            stored_access_policy_list: self.stored_access_policy_list,
            client_request_id: self.client_request_id,
            timeout: self.timeout,
            lease_id: Some(lease_id),
        }
    }
}

// methods callable only when every mandatory field has been filled
impl<'a, C> SetACLBuilder<'a, C, Yes, Yes>
where
    C: Client,
{
    pub async fn finalize(self) -> Result<PublicAccess, AzureError> {
        let mut uri = format!(
            "{}/{}?restype=container&comp=acl",
            self.client().blob_uri(),
            self.container_name()
        );

        if let Some(nm) = TimeoutOption::to_uri_parameter(&self) {
            uri = format!("{}&{}", uri, nm);
        }

        let xml = if let Some(sapl) = self.stored_access_policy_list {
            let xml = sapl.to_xml();
            Some(xml)
        } else {
            None
        };

        let future_response = self.client().perform_request(
            &uri,
            &Method::PUT,
            &|mut request| {
                request = ClientRequestIdOption::add_header(&self, request);
                request = LeaseIdOption::add_header(&self, request);
                request = PublicAccessRequired::add_header(&self, request);
                request
            },
            match xml {
                Some(ref x) => Some(x.as_bytes()),
                None => Some(&[]),
            },
        )?;

        let (headers, _body) =
            check_status_extract_headers_and_body(future_response, StatusCode::OK).await?;

        public_access_from_header(&headers)
    }
}


text:
Using the code
==============

The requirements are:

* `Python <http://www.python.org/>`_ 2.6 or higher (Python 3 works as well)
* `numpy <http://www.numpy.org/>`_ and `scipy <http://www.scipy.org/>`_

Download the code using the `Download ZIP
<https://github.com/simple-dmrg/sophisticated-dmrg/archive/master.zip>`_
button on github, or run the following command from a terminal::

    $ wget -O sophisticated-dmrg-master.zip https://github.com/simple-dmrg/sophisticated-dmrg/archive/master.zip

Within a terminal, execute the following to unpack the code::

    $ unzip sophisticated-dmrg-master.zip
    $ cd sophisticated-dmrg-master/

Once the relevant software is installed, each program is contained
entirely in a single file.  The first program, for instance, can be
run by issuing::

    $ python sophisticated_dmrg.py

.. note::

    If you see an error that looks like this::

        SyntaxError: future feature print_function is not defined

    then you are using a version of Python below 2.6.  Although it
    would be best to upgrade, it may be possible to make the code work
    on Python versions below 2.6 without much trouble.