text:
#include <dotslashzero/clib/clib.h>

#include <dotslashzero/lb_common/version.h>

#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

#if defined(__cplusplus)
#error Please use pure C compiler for this file.
#endif /* defined(__cplusplus) */

#define DSZ_CLIBCORE_INLINE inline

#if defined(_MSC_VER)
#define snprintf sprintf_s
#undef strncpy
#define strncpy(buffer, source, bufferSize) strncpy_s(buffer, bufferSize, source, _TRUNCATE)
#undef DSZ_CLIBCORE_INLINE
#define DSZ_CLIBCORE_INLINE __inline
#endif /* defined(_MSC_VER) */

#define DSZ_CLIBCORE_ERROR_NUM_TO_CLIB_ERROR_NUM(errorNum) ((size_t) errorNum)

/*
// These have to be macros because they are used in struct type declarations.
*/
#define DSZ_CLIBCORE_ADDRESS_STREET_SIZE 16
#define DSZ_CLIBCORE_ADDRESS_CITY_SIZE 16
#define DSZ_CLIBCORE_ADDRESS_PROVINCE_SIZE 16
#define DSZ_CLIBCORE_ADDRESS_ZIP_CODE_SIZE 16
#define DSZ_CLIBCORE_ADDRESS_COUNTRY_SIZE 16
#define DSZ_CLIBCORE_ADDRESS_STRING_SIZE 80
#define DSZ_CLIBCORE_PERSON_LAST_NAME_SIZE 16
#define DSZ_CLIBCORE_PERSON_FIRST_NAME_SIZE 16
#define DSZ_CLIBCORE_PERSON_STRING_SIZE 160

typedef enum DszCLibCoreErrorNum_
{
    DSZ_CLIBCORE_ERROR_NUM_NO_ERROR          = 0,
    DSZ_CLIBCORE_ERROR_NUM_GENERAL_ERROR     = 1,
    DSZ_CLIBCORE_ERROR_NUM_EXTERNAL_ERROR    = 2
}
DszCLibCoreErrorNum;

typedef DszCLibCoreErrorNum* DszCLibCoreErrorNumPtr;

typedef struct DszCLibCoreAddress_
{
    int StreetNum;
    char Street[DSZ_CLIBCORE_ADDRESS_STREET_SIZE];
    char City[DSZ_CLIBCORE_ADDRESS_CITY_SIZE];
    char Province[DSZ_CLIBCORE_ADDRESS_PROVINCE_SIZE];
    char ZipCode[DSZ_CLIBCORE_ADDRESS_ZIP_CODE_SIZE];
    char Country[DSZ_CLIBCORE_ADDRESS_COUNTRY_SIZE];
}
DszCLibCoreAddress;

typedef DszCLibCoreAddress* DszCLibCoreAddressPtr;

typedef struct DszCLibCorePerson_
{
    char LastName[DSZ_CLIBCORE_PERSON_LAST_NAME_SIZE];
    char FirstName[DSZ_CLIBCORE_PERSON_FIRST_NAME_SIZE];
    int Age;
    DszCLibCoreAddressPtr Address;
}
DszCLibCorePerson;

typedef DszCLibCorePerson* DszCLibCorePersonPtr;

typedef DszCLibErrorNum (*DszCLibCoreGenerateIntFunction)(
    int data, int* pInt,
    void* pUserData);
typedef DszCLibErrorNum (*DszCLibCoreGenerateStringFunction)(
    int data, char* pString, size_t stringSize,
    size_t* pCharsWritten,
    void* pUserData);

typedef struct DszCLibCoreGenerator_
{
    DszCLibCoreGenerateIntFunction GenerateInt;
    DszCLibCoreGenerateStringFunction GenerateString;
}
DszCLibCoreGenerator;

typedef DszCLibCoreGenerator* DszCLibCoreGeneratorPtr;

typedef struct DszCLibCorePrinter_
{
    DszCLibCoreGeneratorPtr Generator;
}
DszCLibCorePrinter;

typedef DszCLibCorePrinter* DszCLibCorePrinterPtr;

static DSZ_CLIBCORE_INLINE char const* DszCLibCoreGetErrorMessage(
    DszCLibCoreErrorNum errorNum)
{
    switch (errorNum) {
        case (DSZ_CLIBCORE_ERROR_NUM_NO_ERROR):
            return ("No error.");
        case (DSZ_CLIBCORE_ERROR_NUM_GENERAL_ERROR):
            return ("General error.");
        case (DSZ_CLIBCORE_ERROR_NUM_EXTERNAL_ERROR):
            return ("External error.");
        default:
            return ("Unknown error.");
    }
}

DSZ_CLIB_API(void) DszCLibErrorNumGetMessage(
    DszCLibErrorNum errorNum,
    char* pMessage, size_t messageSize,
    size_t* pCharsWritten)
{
    char const* errorMessage = DszCLibCoreGetErrorMessage(errorNum);
    size_t numChars = strlen(errorMessage);

    if ((pMessage != NULL) && (messageSize > 0)) {
        strncpy(pMessage, errorMessage, messageSize);
        pMessage[messageSize - 1] = '\0';
        numChars = strlen(pMessage);
    }

    if (pCharsWritten != NULL)
        *pCharsWritten = numChars;

    return;
}

DSZ_CLIB_API(DszCLibErrorNum) DszCLibLibraryInitialize(void)
{
    /* no operation */
    return (DSZ_CLIBCORE_ERROR_NUM_TO_CLIB_ERROR_NUM(DSZ_CLIBCORE_ERROR_NUM_NO_ERROR));
}

DSZ_CLIB_API(DszCLibErrorNum) DszCLibLibraryUninitialize(void)
{
    /* no operation */
    return (DSZ_CLIBCORE_ERROR_NUM_TO_CLIB_ERROR_NUM(DSZ_CLIBCORE_ERROR_NUM_NO_ERROR));
}

DSZ_CLIB_API(DszCLibErrorNum) DszCLibLibraryGetVersionString(
    char* pVersionString, size_t versionStringSize,
    size_t* pCharsWritten)
{
    size_t numChars = strlen(DSZ_LB_VERSION_STRING);

    if ((pVersionString != NULL) && (versionStringSize > 0)) {
        strncpy(pVersionString, DSZ_LB_VERSION_STRING, versionStringSize);
        pVersionString[versionStringSize - 1] = '\0';
        numChars = strlen(pVersionString);
    }

    if (pCharsWritten != NULL)
        *pCharsWritten = numChars;

    return (DSZ_CLIBCORE_ERROR_NUM_TO_CLIB_ERROR_NUM(DSZ_CLIBCORE_ERROR_NUM_NO_ERROR));
}

DSZ_CLIB_API(DszCLibErrorNum) DszCLibLibraryGetVersionMajor(
    size_t* pVersionMajor)
{
    if (pVersionMajor != NULL)
        *pVersionMajor = DSZ_LB_VERSION_MAJOR;

    return (DSZ_CLIBCORE_ERROR_NUM_TO_CLIB_ERROR_NUM(DSZ_CLIBCORE_ERROR_NUM_NO_ERROR));
}

DSZ_CLIB_API(DszCLibErrorNum) DszCLibLibraryGetVersionMinor(
    size_t* pVersionMinor)
{
    if (pVersionMinor != NULL)
        *pVersionMinor = DSZ_LB_VERSION_MINOR;

    return (DSZ_CLIBCORE_ERROR_NUM_TO_CLIB_ERROR_NUM(DSZ_CLIBCORE_ERROR_NUM_NO_ERROR));
}

DSZ_CLIB_API(DszCLibErrorNum) DszCLibLibraryGetVersionPatch(
    size_t* pVersionPatch)
{
    if (pVersionPatch != NULL)
        *pVersionPatch = DSZ_LB_VERSION_PATCH;

    return (DSZ_CLIBCORE_ERROR_NUM_TO_CLIB_ERROR_NUM(DSZ_CLIBCORE_ERROR_NUM_NO_ERROR));
}

DSZ_CLIB_API(DszCLibErrorNum) DszCLibLibraryGetVersionExtra(
    char* pVersionExtraString, size_t versionExtraStringSize,
    size_t* pCharsWritten)
{
    size_t numChars = strlen(DSZ_LB_VERSION_EXTRA);

    if ((pVersionExtraString != NULL) && (versionExtraStringSize > 0)) {
        strncpy(pVersionExtraString, DSZ_LB_VERSION_EXTRA, versionExtraStringSize);
        pVersionExtraString[versionExtraStringSize - 1] = '\0'; /* for safety */
        numChars = strlen(pVersionExtraString);
    }

    if (pCharsWritten != NULL)
        *pCharsWritten = numChars;

    return (DSZ_CLIBCORE_ERROR_NUM_TO_CLIB_ERROR_NUM(DSZ_CLIBCORE_ERROR_NUM_NO_ERROR));
}

DSZ_CLIB_API(DszCLibErrorNum) DszCLibAddressCreate(
    int streetNum,
    char const* street,
    char const* city,
    char const* province,
    char const* zipCode,
    char const* country,
    DszCLibAddress* pAddress)
{
    DszCLibCoreAddressPtr pCoreAddress = NULL;

    if (pAddress == NULL)
        return (DSZ_CLIBCORE_ERROR_NUM_TO_CLIB_ERROR_NUM(DSZ_CLIBCORE_ERROR_NUM_EXTERNAL_ERROR));

    pCoreAddress = (DszCLibCoreAddressPtr) malloc(sizeof (DszCLibCoreAddress));

    if (pCoreAddress == NULL)
        return (DSZ_CLIBCORE_ERROR_NUM_TO_CLIB_ERROR_NUM(DSZ_CLIBCORE_ERROR_NUM_GENERAL_ERROR));

    pCoreAddress->StreetNum = streetNum;

    strncpy(pCoreAddress->Street, street, DSZ_CLIBCORE_ADDRESS_STREET_SIZE);
    pCoreAddress->Street[DSZ_CLIBCORE_ADDRESS_STREET_SIZE - 1] = '\0';

    strncpy(pCoreAddress->City, city, DSZ_CLIBCORE_ADDRESS_CITY_SIZE);
    pCoreAddress->City[DSZ_CLIBCORE_ADDRESS_CITY_SIZE - 1] = '\0';

    strncpy(pCoreAddress->Province, province, DSZ_CLIBCORE_ADDRESS_PROVINCE_SIZE);
    pCoreAddress->Province[DSZ_CLIBCORE_ADDRESS_PROVINCE_SIZE - 1] = '\0';

    strncpy(pCoreAddress->ZipCode, zipCode, DSZ_CLIBCORE_ADDRESS_ZIP_CODE_SIZE);
    pCoreAddress->ZipCode[DSZ_CLIBCORE_ADDRESS_ZIP_CODE_SIZE - 1] = '\0';

    strncpy(pCoreAddress->Country, country, DSZ_CLIBCORE_ADDRESS_COUNTRY_SIZE);
    pCoreAddress->Country[DSZ_CLIBCORE_ADDRESS_COUNTRY_SIZE - 1] = '\0';

    *pAddress = (DszCLibAddress) pCoreAddress; /* DszCLibAddress is an opaque pointer to DszCLibCoreAddress */

    return (DSZ_CLIBCORE_ERROR_NUM_TO_CLIB_ERROR_NUM(DSZ_CLIBCORE_ERROR_NUM_NO_ERROR));
}

DSZ_CLIB_API(DszCLibErrorNum) DszCLibAddressDestroy(
    DszCLibAddress address)
{
    DszCLibCoreAddressPtr pCoreAddress = (DszCLibCoreAddressPtr) address;

    if (pCoreAddress == NULL)
        return (DSZ_CLIBCORE_ERROR_NUM_TO_CLIB_ERROR_NUM(DSZ_CLIBCORE_ERROR_NUM_GENERAL_ERROR));

    free(pCoreAddress);

    return (DSZ_CLIBCORE_ERROR_NUM_TO_CLIB_ERROR_NUM(DSZ_CLIBCORE_ERROR_NUM_NO_ERROR));
}

DSZ_CLIB_API(DszCLibErrorNum) DszCLibAddressGetStreetNum(
    DszCLibAddress address,
    int* pStreetNum)
{
    DszCLibCoreAddressPtr pCoreAddress = (DszCLibCoreAddressPtr) address;

    if (pStreetNum == NULL)
        return (DSZ_CLIBCORE_ERROR_NUM_TO_CLIB_ERROR_NUM(DSZ_CLIBCORE_ERROR_NUM_EXTERNAL_ERROR));

    if (pCoreAddress == NULL)
        return (DSZ_CLIBCORE_ERROR_NUM_TO_CLIB_ERROR_NUM(DSZ_CLIBCORE_ERROR_NUM_GENERAL_ERROR));

    *pStreetNum = pCoreAddress->StreetNum;

    return (DSZ_CLIBCORE_ERROR_NUM_TO_CLIB_ERROR_NUM(DSZ_CLIBCORE_ERROR_NUM_NO_ERROR));
}

DSZ_CLIB_API(DszCLibErrorNum) DszCLibAddressGetStreet(
    DszCLibAddress address,
    char* pStreet, size_t streetSize,
    size_t* pCharsWritten)
{
    DszCLibCoreAddressPtr pCoreAddress = (DszCLibCoreAddressPtr) address;
    size_t numChars = 0;

    if (pCoreAddress == NULL)
        return (DSZ_CLIBCORE_ERROR_NUM_TO_CLIB_ERROR_NUM(DSZ_CLIBCORE_ERROR_NUM_GENERAL_ERROR));

    numChars = strlen(pCoreAddress->Street);

    if ((pStreet != NULL) && (streetSize > 0)) {
        strncpy(pStreet, pCoreAddress->Street, streetSize);
        pStreet[streetSize - 1] = '\0';
        numChars = strlen(pStreet);
    }

    if (pCharsWritten != NULL)
        *pCharsWritten = numChars;

    return (DSZ_CLIBCORE_ERROR_NUM_TO_CLIB_ERROR_NUM(DSZ_CLIBCORE_ERROR_NUM_NO_ERROR));
}

DSZ_CLIB_API(DszCLibErrorNum) DszCLibAddressGetCity(
    DszCLibAddress address,
    char* pCity, size_t citySize,
    size_t* pCharsWritten)
{
    DszCLibCoreAddressPtr pCoreAddress = (DszCLibCoreAddressPtr) address;
    size_t numChars = 0;

    if (pCoreAddress == NULL)
        return (DSZ_CLIBCORE_ERROR_NUM_TO_CLIB_ERROR_NUM(DSZ_CLIBCORE_ERROR_NUM_GENERAL_ERROR));

    numChars = strlen(pCoreAddress->City);

    if ((pCity != NULL) && (citySize > 0)) {
        strncpy(pCity, pCoreAddress->City, citySize);
        pCity[citySize - 1] = '\0';
        numChars = strlen(pCity);
    }

    if (pCharsWritten != NULL)
        *pCharsWritten = numChars;

    return (DSZ_CLIBCORE_ERROR_NUM_TO_CLIB_ERROR_NUM(DSZ_CLIBCORE_ERROR_NUM_NO_ERROR));
}

DSZ_CLIB_API(DszCLibErrorNum) DszCLibAddressGetProvince(
    DszCLibAddress address,
    char* pProvince, size_t provinceSize,
    size_t* pCharsWritten)
{
    DszCLibCoreAddressPtr pCoreAddress = (DszCLibCoreAddressPtr) address;
    size_t numChars = 0;

    if (pCoreAddress == NULL)
        return (DSZ_CLIBCORE_ERROR_NUM_TO_CLIB_ERROR_NUM(DSZ_CLIBCORE_ERROR_NUM_GENERAL_ERROR));

    numChars = strlen(pCoreAddress->Province);

    if ((pProvince != NULL) && (provinceSize > 0)) {
        strncpy(pProvince, pCoreAddress->Province, provinceSize);
        pProvince[provinceSize - 1] = '\0';
        numChars = strlen(pProvince);
    }

    if (pCharsWritten != NULL)
        *pCharsWritten = numChars;

    return (DSZ_CLIBCORE_ERROR_NUM_TO_CLIB_ERROR_NUM(DSZ_CLIBCORE_ERROR_NUM_NO_ERROR));
}

DSZ_CLIB_API(DszCLibErrorNum) DszCLibAddressGetZipCode(
    DszCLibAddress address,
    char* pZipCode, size_t zipCodeSize,
    size_t* pCharsWritten)
{
    DszCLibCoreAddressPtr pCoreAddress = (DszCLibCoreAddressPtr) address;
    size_t numChars = 0;

    if (pCoreAddress == NULL)
        return (DSZ_CLIBCORE_ERROR_NUM_TO_CLIB_ERROR_NUM(DSZ_CLIBCORE_ERROR_NUM_GENERAL_ERROR));

    numChars = strlen(pCoreAddress->ZipCode);

    if ((pZipCode != NULL) && (zipCodeSize > 0)) {
        strncpy(pZipCode, pCoreAddress->ZipCode, zipCodeSize);
        pZipCode[zipCodeSize - 1] = '\0';
        numChars = strlen(pZipCode);
    }

    if (pCharsWritten != NULL)
        *pCharsWritten = numChars;

    return (DSZ_CLIBCORE_ERROR_NUM_TO_CLIB_ERROR_NUM(DSZ_CLIBCORE_ERROR_NUM_NO_ERROR));
}

DSZ_CLIB_API(DszCLibErrorNum) DszCLibAddressGetCountry(
    DszCLibAddress address,
    char* pCountry, size_t countrySize,
    size_t* pCharsWritten)
{
    DszCLibCoreAddressPtr pCoreAddress = (DszCLibCoreAddressPtr) address;
    size_t numChars = 0;

    if (pCoreAddress == NULL)
        return (DSZ_CLIBCORE_ERROR_NUM_TO_CLIB_ERROR_NUM(DSZ_CLIBCORE_ERROR_NUM_GENERAL_ERROR));

    numChars = strlen(pCoreAddress->Country);

    if ((pCountry != NULL) && (countrySize > 0)) {
        strncpy(pCountry, pCoreAddress->Country, countrySize);
        pCountry[countrySize - 1] = '\0';
        numChars = strlen(pCountry);
    }

    if (pCharsWritten != NULL)
        *pCharsWritten = numChars;

    return (DSZ_CLIBCORE_ERROR_NUM_TO_CLIB_ERROR_NUM(DSZ_CLIBCORE_ERROR_NUM_NO_ERROR));
}

DSZ_CLIB_API(DszCLibErrorNum) DszCLibAddressToString(
    DszCLibAddress address,
    char* pAddressString, size_t addressStringSize,
    size_t* pCharsWritten)
{
    DszCLibCoreAddressPtr pCoreAddress = (DszCLibCoreAddressPtr) address;
    size_t numChars = 0;
    char coreAddressString[DSZ_CLIBCORE_ADDRESS_STRING_SIZE];

    if (pCoreAddress == NULL)
        return (DSZ_CLIBCORE_ERROR_NUM_TO_CLIB_ERROR_NUM(DSZ_CLIBCORE_ERROR_NUM_GENERAL_ERROR));

    memset(coreAddressString, 0, DSZ_CLIBCORE_ADDRESS_STRING_SIZE);
    snprintf(
        coreAddressString, DSZ_CLIBCORE_ADDRESS_STRING_SIZE,
        "%d %s\n%s, %s\n%s %s",
        pCoreAddress->StreetNum,
        pCoreAddress->Street,
        pCoreAddress->City,
        pCoreAddress->Province,
        pCoreAddress->ZipCode,
        pCoreAddress->Country);

    numChars = strlen(coreAddressString);

    if ((pAddressString != NULL) && (addressStringSize > 0)) {
        strncpy(pAddressString, coreAddressString, addressStringSize);
        pAddressString[addressStringSize - 1] = '\0';
        numChars = strlen(pAddressString);
    }

    if (pCharsWritten != NULL)
        *pCharsWritten = numChars;

    return (DSZ_CLIBCORE_ERROR_NUM_TO_CLIB_ERROR_NUM(DSZ_CLIBCORE_ERROR_NUM_NO_ERROR));
}

DSZ_CLIB_API(DszCLibErrorNum) DszCLibPersonCreate(
    char const* lastName,
    char const* firstName,
    int age,
    DszCLibAddress address,
    DszCLibPerson* pPerson)
{
    DszCLibCorePersonPtr pCorePerson = NULL;
    DszCLibErrorNum errorNum = DSZ_CLIBCORE_ERROR_NUM_NO_ERROR;
    DszCLibCoreAddressPtr pCoreAddress = (DszCLibCoreAddressPtr) address;
    DszCLibCoreAddressPtr pCorePersonAddress = NULL;

    if (pPerson == NULL)
        return (DSZ_CLIBCORE_ERROR_NUM_TO_CLIB_ERROR_NUM(DSZ_CLIBCORE_ERROR_NUM_EXTERNAL_ERROR));

    if (pCoreAddress == NULL)
        return (DSZ_CLIBCORE_ERROR_NUM_TO_CLIB_ERROR_NUM(DSZ_CLIBCORE_ERROR_NUM_GENERAL_ERROR));

    pCorePerson = (DszCLibCorePersonPtr) malloc(sizeof (DszCLibCorePerson));
    if (pCorePerson == NULL)
        return (DSZ_CLIBCORE_ERROR_NUM_TO_CLIB_ERROR_NUM(DSZ_CLIBCORE_ERROR_NUM_GENERAL_ERROR));

    strncpy(pCorePerson->LastName, lastName, DSZ_CLIBCORE_PERSON_LAST_NAME_SIZE);
    pCorePerson->LastName[DSZ_CLIBCORE_PERSON_LAST_NAME_SIZE - 1] = '\0';

    strncpy(pCorePerson->FirstName, firstName, DSZ_CLIBCORE_PERSON_FIRST_NAME_SIZE);
    pCorePerson->FirstName[DSZ_CLIBCORE_PERSON_FIRST_NAME_SIZE - 1] = '\0';

    pCorePerson->Age = age;

    /* make a copy of address */
    errorNum = DszCLibAddressCreate(
        pCoreAddress->StreetNum,
        pCoreAddress->Street,
        pCoreAddress->City,
        pCoreAddress->Province,
        pCoreAddress->ZipCode,
        pCoreAddress->Country,
        (DszCLibAddress*) &(pCorePersonAddress));

    if (errorNum != 0) {
        if (pCorePerson != NULL)
            free(pCorePerson);
        return (errorNum);
    }

    pCorePerson->Address = pCorePersonAddress;

    *pPerson = (DszCLibPerson) pCorePerson;

    return (DSZ_CLIBCORE_ERROR_NUM_TO_CLIB_ERROR_NUM(DSZ_CLIBCORE_ERROR_NUM_NO_ERROR));
}

DSZ_CLIB_API(DszCLibErrorNum) DszCLibPersonDestroy(
    DszCLibPerson person)
{
    DszCLibCorePersonPtr pCorePerson = (DszCLibCorePersonPtr) person;

    if (pCorePerson == NULL)
        return (DSZ_CLIBCORE_ERROR_NUM_TO_CLIB_ERROR_NUM(DSZ_CLIBCORE_ERROR_NUM_GENERAL_ERROR));

    DszCLibAddressDestroy((DszCLibAddress) pCorePerson->Address);
    free(pCorePerson);

    return (DSZ_CLIBCORE_ERROR_NUM_TO_CLIB_ERROR_NUM(DSZ_CLIBCORE_ERROR_NUM_NO_ERROR));
}

DSZ_CLIB_API(DszCLibErrorNum) DszCLibPersonGetLastName(
    DszCLibPerson person,
    char* pLastName, size_t lastNameSize,
    size_t* pCharsWritten)
{
    DszCLibCorePersonPtr pCorePerson = (DszCLibCorePersonPtr) person;
    size_t numChars = 0;

    if (pCorePerson == NULL)
        return (DSZ_CLIBCORE_ERROR_NUM_TO_CLIB_ERROR_NUM(DSZ_CLIBCORE_ERROR_NUM_GENERAL_ERROR));

    numChars = strlen(pCorePerson->LastName);

    if ((pLastName != NULL) && (lastNameSize > 0)) {
        strncpy(pLastName, pCorePerson->LastName, lastNameSize);
        pLastName[lastNameSize - 1] = '\0';
        numChars = strlen(pLastName);
    }

    if (pCharsWritten != NULL)
        *pCharsWritten = numChars;

    return (DSZ_CLIBCORE_ERROR_NUM_TO_CLIB_ERROR_NUM(DSZ_CLIBCORE_ERROR_NUM_NO_ERROR));
}

DSZ_CLIB_API(DszCLibErrorNum) DszCLibPersonGetFirstName(
    DszCLibPerson person,
    char* pFirstName, size_t firstNameSize,
    size_t* pCharsWritten)
{
    DszCLibCorePersonPtr pCorePerson = (DszCLibCorePersonPtr) person;
    size_t numChars = 0;

    if (pCorePerson == NULL)
        return (DSZ_CLIBCORE_ERROR_NUM_TO_CLIB_ERROR_NUM(DSZ_CLIBCORE_ERROR_NUM_GENERAL_ERROR));

    numChars = strlen(pCorePerson->FirstName);

    if ((pFirstName != NULL) && (firstNameSize > 0)) {
        strncpy(pFirstName, pCorePerson->FirstName, firstNameSize);
        pFirstName[firstNameSize - 1] = '\0';
        numChars = strlen(pFirstName);
    }

    if (pCharsWritten != NULL)
        *pCharsWritten = numChars;

    return (DSZ_CLIBCORE_ERROR_NUM_TO_CLIB_ERROR_NUM(DSZ_CLIBCORE_ERROR_NUM_NO_ERROR));
}

DSZ_CLIB_API(DszCLibErrorNum) DszCLibPersonGetAge(
    DszCLibPerson person,
    int* pAge)
{
    DszCLibCorePerson* pCorePerson = (DszCLibCorePerson*) person;

    if (pAge == NULL)
        return (DSZ_CLIBCORE_ERROR_NUM_TO_CLIB_ERROR_NUM(DSZ_CLIBCORE_ERROR_NUM_EXTERNAL_ERROR));

    if (pCorePerson == NULL)
        return (DSZ_CLIBCORE_ERROR_NUM_TO_CLIB_ERROR_NUM(DSZ_CLIBCORE_ERROR_NUM_GENERAL_ERROR));

    *pAge = pCorePerson->Age;

    return (DSZ_CLIBCORE_ERROR_NUM_TO_CLIB_ERROR_NUM(DSZ_CLIBCORE_ERROR_NUM_NO_ERROR));
}

DSZ_CLIB_API(DszCLibErrorNum) DszCLibPersonGetAddress(
    DszCLibPerson person,
    DszCLibAddress* pAddress)
{
    DszCLibCorePersonPtr pCorePerson = (DszCLibCorePersonPtr) person;
    DszCLibCoreAddressPtr pCoreAddress = NULL;
    DszCLibErrorNum errorNum = DSZ_CLIBCORE_ERROR_NUM_NO_ERROR;

    if (pAddress == NULL)
        return (DSZ_CLIBCORE_ERROR_NUM_TO_CLIB_ERROR_NUM(DSZ_CLIBCORE_ERROR_NUM_EXTERNAL_ERROR));

    if (pCorePerson == NULL)
        return (DSZ_CLIBCORE_ERROR_NUM_TO_CLIB_ERROR_NUM(DSZ_CLIBCORE_ERROR_NUM_GENERAL_ERROR));

    pCoreAddress = pCorePerson->Address;

    if (pCoreAddress == NULL)
        return (DSZ_CLIBCORE_ERROR_NUM_TO_CLIB_ERROR_NUM(DSZ_CLIBCORE_ERROR_NUM_GENERAL_ERROR));

    errorNum = DszCLibAddressCreate(
        pCoreAddress->StreetNum,
        pCoreAddress->Street,
        pCoreAddress->City,
        pCoreAddress->Province,
        pCoreAddress->ZipCode,
        pCoreAddress->Country,
        pAddress);

    return (DSZ_CLIBCORE_ERROR_NUM_TO_CLIB_ERROR_NUM(errorNum));
}

DSZ_CLIB_API(DszCLibErrorNum) DszCLibPersonToString(
    DszCLibPerson person,
    char* pPersonString, size_t personStringSize,
    size_t* pCharsWritten)
{
    DszCLibCorePersonPtr pCorePerson = (DszCLibCorePersonPtr) person;
    DszCLibErrorNum errorNum = DSZ_CLIBCORE_ERROR_NUM_NO_ERROR;
    size_t numChars = 0;
    char coreAddressString[DSZ_CLIBCORE_ADDRESS_STRING_SIZE];
    char corePersonString[DSZ_CLIBCORE_PERSON_STRING_SIZE];

    if (pCorePerson == NULL)
        return (DSZ_CLIBCORE_ERROR_NUM_TO_CLIB_ERROR_NUM(DSZ_CLIBCORE_ERROR_NUM_GENERAL_ERROR));

    memset(coreAddressString, 0, DSZ_CLIBCORE_ADDRESS_STRING_SIZE);
    errorNum = DszCLibAddressToString(
        (DszCLibAddress) pCorePerson->Address,
        coreAddressString, DSZ_CLIBCORE_ADDRESS_STRING_SIZE,
        NULL);

    if (errorNum != DSZ_CLIBCORE_ERROR_NUM_NO_ERROR)
        return (DSZ_CLIBCORE_ERROR_NUM_TO_CLIB_ERROR_NUM(errorNum));

    coreAddressString[DSZ_CLIBCORE_ADDRESS_STRING_SIZE - 1] = '\0';

    memset(corePersonString, 0, DSZ_CLIBCORE_PERSON_STRING_SIZE);
    snprintf(
        corePersonString, DSZ_CLIBCORE_PERSON_STRING_SIZE,
        "%s, %s\n%d years old\n%s",
        pCorePerson->LastName, pCorePerson->FirstName,
        pCorePerson->Age,
        coreAddressString);

    numChars = strlen(corePersonString);

    if ((pPersonString != NULL) && (personStringSize > 0)) {
        strncpy(pPersonString, corePersonString, personStringSize);
        pPersonString[personStringSize - 1] = '\0';
        numChars = strlen(pPersonString);
    }

    if (pCharsWritten != NULL)
        *pCharsWritten = numChars;

    return (DSZ_CLIBCORE_ERROR_NUM_TO_CLIB_ERROR_NUM(DSZ_CLIBCORE_ERROR_NUM_NO_ERROR));
}

DSZ_CLIB_API(DszCLibErrorNum) DszCLibGeneratorCreate(
    DszCLibGenerateIntFunction fnGenerateInt,
    DszCLibGenerateStringFunction fnGenerateString,
    DszCLibGenerator* pGenerator)
{
    DszCLibCoreGeneratorPtr pCoreGenerator = NULL;

    if (pGenerator == NULL)
        return (DSZ_CLIBCORE_ERROR_NUM_TO_CLIB_ERROR_NUM(DSZ_CLIBCORE_ERROR_NUM_EXTERNAL_ERROR));

    pCoreGenerator = (DszCLibCoreGeneratorPtr) malloc(sizeof (DszCLibCoreGenerator));

    if (pCoreGenerator == NULL)
        return (DSZ_CLIBCORE_ERROR_NUM_TO_CLIB_ERROR_NUM(DSZ_CLIBCORE_ERROR_NUM_GENERAL_ERROR));

    memset((void*) pCoreGenerator, 0, sizeof (pCoreGenerator));

    pCoreGenerator->GenerateInt = (DszCLibCoreGenerateIntFunction) fnGenerateInt;
    pCoreGenerator->GenerateString = (DszCLibCoreGenerateStringFunction) fnGenerateString;

    *pGenerator = (DszCLibGenerator) pCoreGenerator;

    return (DSZ_CLIBCORE_ERROR_NUM_TO_CLIB_ERROR_NUM(DSZ_CLIBCORE_ERROR_NUM_NO_ERROR));
}

DSZ_CLIB_API(DszCLibErrorNum) DszCLibGeneratorDestroy(
    DszCLibGenerator generator)
{
    DszCLibCoreGeneratorPtr pCoreGenerator = (DszCLibCoreGeneratorPtr) generator;

    if (pCoreGenerator == NULL)
        return (DSZ_CLIBCORE_ERROR_NUM_TO_CLIB_ERROR_NUM(DSZ_CLIBCORE_ERROR_NUM_GENERAL_ERROR));

    free(pCoreGenerator);

    return (DSZ_CLIBCORE_ERROR_NUM_TO_CLIB_ERROR_NUM(DSZ_CLIBCORE_ERROR_NUM_NO_ERROR));
}

DSZ_CLIB_API(DszCLibErrorNum) DszCLibPrinterCreate(
    DszCLibGenerator generator,
    DszCLibPrinter* pPrinter)
{
    DszCLibCorePrinterPtr pCorePrinter = NULL;
    DszCLibCoreGeneratorPtr pCoreGenerator = (DszCLibCoreGeneratorPtr) generator;

    if (pPrinter == NULL)
        return (DSZ_CLIBCORE_ERROR_NUM_TO_CLIB_ERROR_NUM(DSZ_CLIBCORE_ERROR_NUM_EXTERNAL_ERROR));

    if (pCoreGenerator == NULL)
        return (DSZ_CLIBCORE_ERROR_NUM_TO_CLIB_ERROR_NUM(DSZ_CLIBCORE_ERROR_NUM_GENERAL_ERROR));

    pCorePrinter = (DszCLibCorePrinterPtr) malloc(sizeof (DszCLibCorePrinter));
    if (pCorePrinter == NULL)
        return (DSZ_CLIBCORE_ERROR_NUM_TO_CLIB_ERROR_NUM(DSZ_CLIBCORE_ERROR_NUM_GENERAL_ERROR));

    pCorePrinter->Generator = pCoreGenerator;

    *pPrinter = (DszCLibPrinter) pCorePrinter;

    return (DSZ_CLIBCORE_ERROR_NUM_TO_CLIB_ERROR_NUM(DSZ_CLIBCORE_ERROR_NUM_NO_ERROR));
}

DSZ_CLIB_API(DszCLibErrorNum) DszCLibPrinterDestroy(
    DszCLibPrinter printer)
{
    DszCLibCorePrinterPtr pCorePrinter = (DszCLibCorePrinterPtr) printer;

    if (pCorePrinter == NULL)
        return (DSZ_CLIBCORE_ERROR_NUM_TO_CLIB_ERROR_NUM(DSZ_CLIBCORE_ERROR_NUM_GENERAL_ERROR));

    DszCLibGeneratorDestroy((DszCLibGenerator) pCorePrinter->Generator);
    free(pCorePrinter);

    return (DSZ_CLIBCORE_ERROR_NUM_TO_CLIB_ERROR_NUM(DSZ_CLIBCORE_ERROR_NUM_NO_ERROR));
}

DSZ_CLIB_API(DszCLibErrorNum) DszCLibPrinterPrintInt(
    DszCLibPrinter printer)
{
    return (DszCLibPrinterPrintIntWithUserData(printer, NULL));
}

DSZ_CLIB_API(DszCLibErrorNum) DszCLibPrinterPrintIntWithUserData(
    DszCLibPrinter printer,
    void* pUserData)
{
    DszCLibErrorNum errorNum = DSZ_CLIB_ERROR_NUM_NO_ERROR;
    DszCLibCorePrinterPtr pCorePrinter = (DszCLibCorePrinterPtr) printer;
    DszCLibCoreGeneratorPtr pCoreGenerator = NULL;
    DszCLibCoreGenerateIntFunction fnCoreGenerateInt = NULL;
    time_t data = time(NULL);
    int generatedInt = 0;

    if (pCorePrinter == NULL)
        return (DSZ_CLIBCORE_ERROR_NUM_TO_CLIB_ERROR_NUM(DSZ_CLIBCORE_ERROR_NUM_GENERAL_ERROR));

    pCoreGenerator = pCorePrinter->Generator;

    if (pCoreGenerator == NULL)
        return (DSZ_CLIBCORE_ERROR_NUM_TO_CLIB_ERROR_NUM(DSZ_CLIBCORE_ERROR_NUM_GENERAL_ERROR));

    fnCoreGenerateInt = pCoreGenerator->GenerateInt;

    if (fnCoreGenerateInt == NULL)
        return (DSZ_CLIBCORE_ERROR_NUM_TO_CLIB_ERROR_NUM(DSZ_CLIBCORE_ERROR_NUM_GENERAL_ERROR));

    errorNum = fnCoreGenerateInt((int) data, &generatedInt, pUserData);

    if (errorNum != DSZ_CLIB_ERROR_NUM_NO_ERROR)
        return (errorNum);

    fprintf(stdout, "The value of int is: %d\n", generatedInt);

    return (DSZ_CLIBCORE_ERROR_NUM_TO_CLIB_ERROR_NUM(DSZ_CLIBCORE_ERROR_NUM_NO_ERROR));
}

DSZ_CLIB_API(DszCLibErrorNum) DszCLibPrinterPrintString(
    DszCLibPrinter printer)
{
    return(DszCLibPrinterPrintStringWithUserData(printer, NULL));
}

DSZ_CLIB_API(DszCLibErrorNum) DszCLibPrinterPrintStringWithUserData(
    DszCLibPrinter printer,
    void* pUserData)
{
    size_t const GENERATED_STRING_SIZE_EXTRA = 8; /* for buffer safety */

    DszCLibErrorNum errorNum = DSZ_CLIBCORE_ERROR_NUM_TO_CLIB_ERROR_NUM(DSZ_CLIBCORE_ERROR_NUM_NO_ERROR);
    DszCLibCorePrinterPtr pCorePrinter = (DszCLibCorePrinterPtr) printer;
    DszCLibCoreGeneratorPtr pCoreGenerator = NULL;
    DszCLibCoreGenerateStringFunction fnCoreGenerateString = NULL;
    int data = (int) time(NULL);
    size_t generatedStringSize = 0;
    char* pGeneratedString = NULL;

    if (pCorePrinter == NULL)
        return (DSZ_CLIBCORE_ERROR_NUM_TO_CLIB_ERROR_NUM(DSZ_CLIBCORE_ERROR_NUM_GENERAL_ERROR));

    pCoreGenerator = pCorePrinter->Generator;

    if (pCoreGenerator == NULL)
        return (DSZ_CLIBCORE_ERROR_NUM_TO_CLIB_ERROR_NUM(DSZ_CLIBCORE_ERROR_NUM_GENERAL_ERROR));

    fnCoreGenerateString = pCoreGenerator->GenerateString;

    if (fnCoreGenerateString == NULL)
        return (DSZ_CLIBCORE_ERROR_NUM_TO_CLIB_ERROR_NUM(DSZ_CLIBCORE_ERROR_NUM_GENERAL_ERROR));

    /* note: the "do {...} while (false);"" usage here is a way to mimic RAII in pure C */
    do {
        errorNum = fnCoreGenerateString(data, NULL, 0, &generatedStringSize, pUserData);

        if (generatedStringSize == 0) {
            errorNum = DSZ_CLIBCORE_ERROR_NUM_TO_CLIB_ERROR_NUM(DSZ_CLIBCORE_ERROR_NUM_GENERAL_ERROR);
            break;
        }

        generatedStringSize += GENERATED_STRING_SIZE_EXTRA; /* for buffer safety */

        pGeneratedString = (char*) malloc((sizeof (char)) * (generatedStringSize));

        if (pGeneratedString == NULL) {
            errorNum = DSZ_CLIBCORE_ERROR_NUM_TO_CLIB_ERROR_NUM(DSZ_CLIBCORE_ERROR_NUM_GENERAL_ERROR);
            break;
        }

        memset(pGeneratedString, 0, generatedStringSize);

        errorNum = fnCoreGenerateString((int) data, pGeneratedString, generatedStringSize, NULL, pUserData);

        if (errorNum != DSZ_CLIB_ERROR_NUM_NO_ERROR)
            break;

        pGeneratedString[generatedStringSize - 1] = '\0';

        fprintf(stdout, "The value of string is: %s\n", pGeneratedString);
    }
    while (false);

    if (pGeneratedString != NULL)
        free(pGeneratedString);

    return (errorNum);
}


text:
const {NodeVM} = require('vm2')

module.exports = function check (target, code, assertions, testContext = {}) {
  const vm = new NodeVM({
    console: 'inherit',
    require: {
      builtin: ['assert']
    },
    sandbox: {
      testContext
    },
    timeout: 3000
  })

  vm.run(`
    ${code}

    testContext.${target} = ${target}
  `)
  return vm.run(`
    const assert = require('assert')
    let correct = false
    let log = {}
    try {
      ${assertions.reduce((acc, assertion) => `assert.deepEqual(testContext['${assertion.actual}'], ${assertion.expected}, '${assertion.message}')\n`, '')}
      correct = true
    } catch (err) {
      log = { err, testContext }
    }

    module.exports = { correct, log }
  `)
}

redpajama_set_name: RedPajamaGithub


text:
package com.pivotal.example.xd.controller;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;

import javax.annotation.PreDestroy;
import javax.servlet.ServletContext;

import org.apache.log4j.Logger;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.pivotal.example.xd.HeatMap;
import com.pivotal.example.xd.Order;
import com.pivotal.example.xd.OrderGenerator;
import com.pivotal.example.xd.RabbitClient;

/**
 * Handles requests for the application home page.
 */
@Controller
public class OrderController {

	@Autowired
	ServletContext context;

	private static Map<String,Queue<Order>> stateOrdersMap = new HashMap<String, Queue<Order>>();
	private static RabbitClient client ;

	boolean generatingData = false;

	static Logger logger = Logger.getLogger(OrderController.class);

	OrderGenerator generator = new OrderGenerator();
	Thread threadSender = new Thread (generator);

    public OrderController(){

    	client = RabbitClient.getInstance();

    	for (int i=0; i<HeatMap.states.length; i++){
    		stateOrdersMap.put(HeatMap.states[i], new ArrayBlockingQueue<Order>(10));
    	}

    	if(client.getRabbitURI() != null){
    		threadSender.start();
        	client.startMessageListener();
        	client.startOrderProcessing();
    	}

    }

	private int getOrderSum(String state){

		int sum = 0;
		Queue<Order> q  = stateOrdersMap.get(state);
		Iterator<Order> it = q.iterator();
		while (it.hasNext()){
			sum += it.next().getAmount();
		}

		return sum;
	}

	public static synchronized void registerOrder(Order order){
		Queue<Order> orderQueue = stateOrdersMap.get(order.getState());
		if (!orderQueue.offer(order)){
			orderQueue.remove();
			orderQueue.add(order);
		}
	}

	@RequestMapping(value = "/")
	public String home(Model model) throws Exception{
		model.addAttribute("rabbitURI", client.getRabbitURI());

		ObjectMapper mapper = new ObjectMapper();

		//add details about VCAP APPLICATION
		if(System.getenv("VCAP_APPLICATION") != null){
			Map vcapMap = mapper.readValue(System.getenv("VCAP_APPLICATION"), Map.class);
			model.addAttribute("vcap_app", vcapMap);
		}

        return "WEB-INF/views/pcfdemo.jsp";
    }

    @RequestMapping(value="/getData")
    public @ResponseBody double getData(@RequestParam("state") String state){
    	if (!stateOrdersMap.containsKey(state)) return 0;
    	Queue<Order> q = stateOrdersMap.get(state);
    	if (q.size()==0) return 0;
    	Order[] orders = q.toArray(new Order[]{});
    	return orders[orders.length-1].getAmount();

    }

    @RequestMapping(value="/startStream")
    public @ResponseBody String startStream(){
		logger.warn("Rabbit URI "+client.getRabbitURI());
		if (client.getRabbitURI()==null) return "Please bind a RabbitMQ service";

    	if (generatingData) return "Data already being generated";

    	generatingData = true;

    	generator.startGen();
    	return "Started";

    }

    @RequestMapping(value="/stopStream")
    public @ResponseBody String stopStream(){
		logger.warn("Rabbit URI "+client.getRabbitURI());
		if (client.getRabbitURI()==null) return "Please bind a RabbitMQ service";

    	if (!generatingData) return "Not Streaming";
    	generatingData = false;
    	generator.stopGen();

    	return "Stopped";

    }

    @RequestMapping(value="/killApp")
    public @ResponseBody String kill(){
		logger.warn("Killing application instance");
		System.exit(-1);
    	return "Killed";

    }

    @RequestMapping(value="/getHeatMap")
    public @ResponseBody HeatMap getHistograms(){
    	HeatMap heatMap = new HeatMap();
    	for (int i=0; i<HeatMap.states.length; i++){
    		heatMap.addOrderSum(HeatMap.states[i], getOrderSum(HeatMap.states[i]));
    	}

    	heatMap.assignColors();
    	return heatMap;

    }

    @PreDestroy
    public void shutdownThread(){

    	generator.shutdown();
    }

}


text:
package org.eknet.publet.gitr.webui.scripts

import org.eknet.publet.engine.scala.ScalaScript
import org.eknet.publet.web.util.RenderUtils._
import GitrControl._
import org.eknet.publet.com.twitter.json.Json
import org.eclipse.jgit.revwalk.RevCommit
import org.fusesource.scalate.TemplateEngine
import org.eknet.publet.web.util.{PubletWeb, PubletWebContext, RenderUtils}
import org.eknet.publet.vfs.{ContentType, Path, Content}
import scala.Some
import org.eknet.gitr.{GitrMan, GitrRepository, RepositoryName}
import org.eknet.publet.gitr.auth.{RepositoryModel, DefaultRepositoryStore, GitAction}
import org.eknet.publet.gitr.GitRequestUtils
import org.eknet.publet.web.shiro.Security

/**
 * @author Eike Kettner eike.kettner@gmail.com
 * @since 30.05.12 19:25
 */
class GitrControl extends ScalaScript {

  def serve() = {
    getRepositoryModelFromParam match {
      case None => repositoryListing
      case Some(model) => getAction match {
        case "log" => {
          GitRequestUtils.checkGitAction(GitAction.pull, model)
          logView
        }
        case "commit" => {
          GitRequestUtils.checkGitAction(GitAction.pull, model)
          commitContents
        }
        case "admin" => {
          GitRequestUtils.checkGitAction(GitAction.admin, model)
          repositoryAdmin
        }
        case _ => {
          GitRequestUtils.checkGitAction(GitAction.pull, model)
          sourceView
        }
      }
    }
  }

  def renderEmptyRepoPage(): Option[Content] = {
    renderTemplate(gitremptyRepoTemplate, repoHeadMap)
  }

  def repoHeadMap: Map[String, Any] = {
    val repoModel = getRepositoryModelFromParam
    val repo = getRepositoryFromParam
    val info = repo.flatMap(r => repoModel.map(rm => new RepositoryInfo(r, rm)))
    val currentHead = getRev
    Map(
      "repositoryInfo" -> info,
      "currentHead" -> currentHead
    )
  }

  def pageHeaderMap: Map[String, Any] = {
    val base = repoHeadMap
    val repo = getRepositoryFromParam
    val revisions = repo
      .map(r => r.getLocalBranches ::: r.getLocalTags)
      .map(_.map(_.name))
      .map(names => Json.build(names).toString)
      .getOrElse("")
    base ++ Map("repository"->repo, "revisions" -> revisions)
  }

  def repositoryAdmin: Option[Content] = {
    renderTemplate(gitrrepoAdminTemplate, repoHeadMap)
  }

  def repositoryListing: Option[Content] = {
    renderTemplate(gitradminTemplate, Map[String, Any]())
  }

  def sourceView: Option[Content] = {
    val repo = getRepositoryFromParam
    if (repo.isEmpty) {
      RenderUtils.renderMessage("No repository!", "Repository not found.", "error")
    } else {
      val c = getCommitFromRequest(repo.get)
      if (c.isEmpty) {
        renderEmptyRepoPage()
      } else {
        val params = pageHeaderMap ++ Map("path" -> (getPath.asString))
        renderTemplate(gitrsourceTemplate, params)
      }
    }
  }

  def logView: Option[Content] = {
    import collection.JavaConversions._

    getRepositoryFromParam flatMap ( repo => {
      repo.getCommit(getRev) flatMap ( commit => {
        val log = repo.git.log()
        val path = getPath
        if (!path.isRoot) {
          log.addPath(path.toRelative.asString)
        }
        log.add(commit.getId)
        val pageSize = PubletWeb.publetSettings("gitrweb.pageSize").getOrElse("25").toInt
        val page = getPage

        val commits = CommitGroup.newBuilder
        def collectCommits(iter:Iterator[RevCommit], cur: Int) {
          if (cur < (pageSize*page) && iter.hasNext) {
            val revCommit = iter.next()
            if (cur >= (pageSize*(page-1))) {
              commits.addByDay(CommitInfo("", "", false, revCommit, PubletWebContext.getLocale))
            }
            collectCommits(iter, cur+1)
          }
        }
        val commitIter = log.call().iterator()
        val nextPage = if (commitIter.hasNext) {
          Some("?r="+getReponame.get+ "&page="+(page+1)+"&do=log&h="+getRev)
        } else {
          None
        }
        val prevPage = if (page>1) {
          Some("?r="+getReponame.get+ "&page="+(page-1)+"&do=log&h="+getRev)
        } else {
          None
        }
        collectCommits(commitIter, 0)
        val commitInfos = commits.build
        val paramMap = pageHeaderMap ++ Map("path" -> (getPath.asString),
          "prevPage" -> prevPage,
          "nextPage" -> nextPage,
          "commits" -> commitInfos)
        renderTemplate(gitrlogTemplate, paramMap)

      }) orElse(renderEmptyRepoPage())
    }) orElse(RenderUtils.renderMessage("No repository!", "Repository not found.", "error"))
  }

  def commitContents = {
    getRepositoryFromParam map ( repo => {
      getCommitFromRequest(repo) flatMap ( commit => {
        val files = repo.getFilesInCommit(commit)
        val parent = repo.getParentCommit(commit).orNull
        val attrs = pageHeaderMap ++ Map(
          "path" -> (getPath.asString),
          "commit" -> commit,
          "changedFiles" -> files,
          "parent" -> parent)
        RenderUtils.renderTemplate(gitrcommitTemplate, attrs)
      })
    }) getOrElse {
      makeJson(Map("success"->false, "message"->"Repository not found."))
    }
  }
}

object GitrControl {

  lazy val mountPoint = PubletWeb.publetSettings("gitr.mountpoint").getOrElse("/gitr")

  /** Permission granted to administrate the repository (incl. delete) */
  val adminPerm = GitAction.admin.name

  /** Permission granted to allow creation of new repositories. */
  val createPerm = GitAction.create.name

  /** Permission granted to allow creation of new root repositories */
  val createRootPerm = GitAction.createRoot.name

  val gitradminTemplate = mountPoint+"/_gitradmin.page"
  val gitrrepoAdminTemplate = mountPoint+"/_repoadmin.page"
  val gitrsourceTemplate = mountPoint+"/_gitrbrowse.page"
  val gitrlogTemplate = mountPoint+"/_gitrlog.page"
  val gitrheaderTemplate = mountPoint+"/_gitrpagehead.page"
  val gitrcommitTemplate = mountPoint+"/_gitrcommit.page"
  val gitremptyRepoTemplate = mountPoint+"/_emptyrepo.page"

  val rParam = "r"   // repo name, default = "None"
  val hParam = "h"   // revision, default = "master"
  val pParam = "p"   // pathname, default = "/"
  val doParam = "do" // log|source, default = source
  val pageParam = "page" // the page to display

  def getPage = PubletWebContext.param(pageParam).getOrElse("1").toInt
  def getReponame = PubletWebContext.param(rParam)
  def getRev = PubletWebContext.param(hParam).collect({ case e if (!e.isEmpty) => e}).getOrElse("master")
  def getPath = {
    val cp = PubletWebContext.param(pParam).getOrElse("")
    if (cp.isEmpty) Path.root
    else {
      Path(Path(cp).segments, false, false)
    }
  }
  def getAction = PubletWebContext.param(doParam).getOrElse("source")

  def getRepositoryFromParam = PubletWebContext.param(rParam) flatMap (repoName => PubletWeb.instance[GitrMan].get.get(RepositoryName(repoName)))
  def getRepositoryModelFromParam = PubletWebContext.param(rParam).map(n=>PubletWeb.instance[DefaultRepositoryStore].get.getRepository(RepositoryName(n)))

  def getCommitFromRequest(repo:GitrRepository): Option[RevCommit] = {
    val param = getRev
    repo.getCommit(param)
  }

  lazy val nocachingTemplateEngine = {
    val templ = new TemplateEngine()
    templ.allowCaching = false
    templ
  }
  lazy val wikiExtensions = ContentType.markdown.extensions ++ ContentType.textile.extensions

  def getCloneUrl(repoName: RepositoryName) = {
    val url = PubletWebContext.urlOf("/git/"+ repoName.fullNameDotGit)
    if (Security.isAuthenticated) {
      url.replaceFirst("://", "://"+ Security.username+"@")
    } else {
      url
    }
  }

  def checkGitAction(action: GitAction.Action, model: RepositoryModel) {
    GitRequestUtils.checkGitAction(action, model)
  }

  def hasGitAction(action: GitAction.Action, model: RepositoryModel) = {
    GitRequestUtils.hasGitAction(action, model)
  }
}


text:
.. _simulation-setup:

################
Simulation setup
################

This is where you define the load you want to inject to your server.

You can configure assertions and protocols with these two methods:

* ``assertions``: set assertions on the simulation, see the dedicated section :ref:`here <assertions>`
* ``protocols``: set protocols definitions, see the dedicated section :ref:`here <http-protocol>`.

.. _simulation-inject:

Injection
=========

The definition of the injection profile of users is done with the ``inject`` method. This method takes as argument a sequence of injection steps that will be processed sequentially.
E.g.:

.. includecode:: code/SimulationSetup.scala#injection

The building blocks for profile injection the way you want are:

#. ``nothingFor(duration)``: Pause for a given duration.
#. ``atOnceUsers(nbUsers)``: Injects a given number of users at once.
#. ``rampUsers(nbUsers) over(duration)``: Injects a given number of users with a linear ramp over a given duration.
#. ``constantUsersPerSec(rate) during(duration)``: Injects users at a constant rate, defined in users per second, during a given duration. Users will be injected at regular intervals.
#. ``constantUsersPerSec(rate) during(duration) randomized``: Injects users at a constant rate, defined in users per second, during a given duration. Users will be injected at randomized intervals.
#. ``rampUsersPerSec(rate1) to (rate2) during(duration)``: Injects users from starting rate to target rate, defined in users per second, during a given duration. Users will be injected at regular intervals.
#. ``rampUsersPerSec(rate1) to(rate2) during(duration) randomized``: Injects users from starting rate to target rate, defined in users per second, during a given duration. Users will be injected at randomized intervals.
#. ``splitUsers(nbUsers) into(injectionStep) separatedBy(duration)``: Repeatedly execute the defined injection step separated by a pause of the given duration until reaching *nbUsers*, the total number of users to inject.
#. ``splitUsers(nbUsers) into(injectionStep1) separatedBy(injectionStep2)``: Repeatedly execute the first defined injection step (*injectionStep1*) separated by the execution of the second injection step (*injectionStep2*) until reaching *nbUsers*, the total number of users to inject.
#. ``heavisideUsers(nbUsers) over(duration)``: Injects a given number of users following a smooth approximation of the `heaviside step function <http://en.wikipedia.org/wiki/Heaviside_step_function>`__ stretched to a given duration.

.. warning::

  Use the proper injection model that match your use case!

  Your load model is not only about getting the expected throughput (number of requests per second), but also open and close the proper number of connections per second.

  Basic load testing tools such as `wrk <https://github.com/wg/wrk>`_ and `ab <http://httpd.apache.org/docs/2.2/programs/ab.html>`_ only support **closed models**:
  users loop over the scenario so, assuming keep alive is used, you get as many open connections as you have users and you never close them.
  This kind of model is mostly suited for call centers, where new users are queued until an operator hangs up.

  With Gatling's ``constantUsersPerSec`` and ``rampUsersPerSec``, you can build **open models**:
  new users keep on arriving no matter how many users are already there, even if the system over test starts slowing down or crashing.
  This kind of model is the best one for most use cases.

  Then, you have to understand that Gatling's default behavior is mimic human users with browsers, so each virtual user has its own connections.
  If you have a high creation rate of users with a short lifespan, you'll end up opening and closing tons of connections every seconds.
  As a consequence, you might run out of resources (such as ephemeral ports, because your OS can't recycle them fast enough).
  If that's the case, you might:

   * consider scaling out
   * reconsider your injection model: maybe you're testing a webservice that's used by just a few clients, so you should be using a closed model and just few connections
   * tune Gatling's behavior and :ref:`share the connection pool amongst virtual users <http-protocol-connection-sharing>`.

.. _simulation-setup-pause:

Global Pause configuration
==========================

The pauses can be configured on ``Simulation`` with a bunch of methods:

* ``disablePauses``: disable the pauses for the simulation
* ``constantPauses``: the duration of each pause is precisely that specified in the ``pause(duration)`` element.
* ``exponentialPauses``: the duration of each pause is on average that specified in the ``pause(duration)`` element and follow an exponential distribution.
* ``normalPausesWithStdDevDuration(stdDev: Duration)``: the duration of each pause is on average that specified in the ``pause(duration)`` element and follow an normal distribution. ``stdDev`` is a Duration.
* ``normalPausesWithPercentageDuration(stdDev: Double)``: the duration of each pause is on average that specified in the ``pause(duration)`` element and follow an normal distribution. ``stdDev`` is a percentage of the pause value.
* ``customPauses(custom: Expression[Long])``: the pause duration is computed by the provided ``Expression[Long]``.
  In this case the filled duration is bypassed.
* ``uniformPausesPlusOrMinusPercentage(plusOrMinus: Double)`` and ``uniformPausesPlusOrMinusDuration(plusOrMinus: Duration)``:
  the duration of each pause is on average that specified in the ``pause(duration)`` element and follow a uniform distribution.

.. note:: Pause definition can also be configured at scenario level.

.. _simulation-setup-throttling:

Throttling
==========

If you want to reason in terms of requests per second and not in terms of concurrent users,
consider using constantUsersPerSec(...) to set the arrival rate of users, and therefore requests,
without need for throttling as well as it will be redundant in most cases.

If this is not sufficient for some reason then Gatling supports throttling with the ``throttle`` method

.. note::

  * You still have to inject users at the scenario level.
    Throttling tries to ensure a targeted throughput with the given scenarios and their injection profiles (number of users and duration).
    It's a bottleneck, ie an upper limit.
    If you don't provide enough users, you won't reach the throttle.
    If your injection lasts less than the throttle, your simulation will simply stop when all the users are done.
    If your injection lasts longer than the throttle, the simulation will stop at the end of the throttle.
  * Throttling can also be configured :ref:`per scenario <scenario-throttling>`.

.. includecode:: code/SimulationSetup.scala#throttling

This simulation will reach 100 req/s with a ramp of 10 seconds, then hold this throughput for 1 minute, jump to 50 req/s and finally hold this throughput for 2 hours.

The building block for the throttling are:

* ``reachRps(target) in (duration)``: target a throughput with a ramp over a given duration.
* ``jumpToRps(target)``: jump immediately to a given targeted throughput.
* ``holdFor(duration)``: hold the current throughput for a given duration.

.. _simulation-setup-maxduration:

Maximum duration
================

Finally, you can configure the maximum duration of your simulation with the method ``maxDuration``.
It is useful if you need to bound the duration of your simulation when you can't predict it.

.. includecode:: code/SimulationSetup.scala#max-duration


text:
namespace mozc {
namespace session {

namespace {
const size_t kMaxSession = 64;
const size_t kDefaultSaveInterval = 500;
const char kIMEOnCommand[] = "IMEOn";
const char kIMEOffCommand[] = "IMEOff";
// Used for selected_indices
// We use negative integer for transliterated candidates,
// but we have transliterated candidates at most 20 or so.
// So we can use INT_MIN for special meaning.
const int kSelectDirectly = INT_MIN;

void ExtractActivationKeys(istream *ifs, set<string> *keys) {
  DCHECK(keys);
  string line;
  getline(*ifs, line);  // first line is comment.
  while (getline(*ifs, line)) {
    Util::ChopReturns(&line);
    if (line.empty() || line[0] == '#') {
      // empty or comment
      continue;
    }
    vector<string> rules;
    Util::SplitStringUsing(line, "\t", &rules);
    if (rules.size() == 3 &&
        (rules[2] == kIMEOnCommand || rules[2] == kIMEOffCommand)) {
      keys->insert(line);
    }
  }
}

config::Config::SessionKeymap kKeyMaps[] = {
  config::Config::ATOK,
  config::Config::MSIME,
  config::Config::KOTOERI,
};

bool IMEActivationKeyCustomized() {
  const config::Config::SessionKeymap keymap = GET_CONFIG(session_keymap);
  if (keymap != config::Config::CUSTOM) {
    return false;
  }
  const string &custom_keymap_table = GET_CONFIG(custom_keymap_table);
  istringstream ifs_custom(custom_keymap_table);
  set<string> customized;
  ExtractActivationKeys(&ifs_custom, &customized);
  for (size_t i = 0; i < arraysize(kKeyMaps); ++i) {
    const char *keymap_file =
        keymap::KeyMapManager::GetKeyMapFileName(kKeyMaps[i]);
    scoped_ptr<istream> ifs(ConfigFileStream::Open(keymap_file));
    if (ifs.get() == NULL) {
      LOG(ERROR) << "can not open default keymap table " << i;
      continue;
    }
    set<string> keymap_table;
    ExtractActivationKeys(ifs.get(), &keymap_table);
    if (includes(keymap_table.begin(), keymap_table.end(),
                 customized.begin(), customized.end())) {
      // customed keymap is subset of preset keymap
      return false;
    }
  }
  return true;
}

// Set current config data to registry
// This is expected not to be called so often, so we do not cache this.
void SetConfigStats() {
  const uint32 keymap = GET_CONFIG(session_keymap);
  usage_stats::UsageStats::SetInteger("ConfigSessionKeymap", keymap);
  const uint32 preedit_method = GET_CONFIG(preedit_method);
  usage_stats::UsageStats::SetInteger("ConfigPreeditMethod", preedit_method);
  const bool custom_roman = (!GET_CONFIG(custom_roman_table).empty() &&
                             preedit_method == config::Config::ROMAN);
  usage_stats::UsageStats::SetBoolean("ConfigCustomRomanTable", custom_roman);
  const uint32 punctuation_method = GET_CONFIG(punctuation_method);
  usage_stats::UsageStats::SetInteger("ConfigPunctuationMethod",
                                      punctuation_method);
  const uint32 symbol_method = GET_CONFIG(symbol_method);
  usage_stats::UsageStats::SetInteger("ConfigSymbolMethod", symbol_method);
  const uint32 history_level = GET_CONFIG(history_learning_level);
  usage_stats::UsageStats::SetInteger("ConfigHistoryLearningLevel",
                                      history_level);

  const bool use_date = GET_CONFIG(use_date_conversion);
  usage_stats::UsageStats::SetBoolean("ConfigUseDateConversion", use_date);
  const bool use_single_kanji = GET_CONFIG(use_single_kanji_conversion);
  usage_stats::UsageStats::SetBoolean("ConfigUseSingleKanjiConversion",
                                      use_single_kanji);
  const bool use_symbol = GET_CONFIG(use_symbol_conversion);
  usage_stats::UsageStats::SetBoolean("ConfigUseSymbolConversion", use_symbol);
  const bool use_number = GET_CONFIG(use_number_conversion);
  usage_stats::UsageStats::SetBoolean("ConfigUseNumberConversion", use_number);
  const bool use_emoticon = GET_CONFIG(use_emoticon_conversion);
  usage_stats::UsageStats::SetBoolean("ConfigUseEmoticonConversion",
                                      use_emoticon);
  const bool use_calculator = GET_CONFIG(use_calculator);
  usage_stats::UsageStats::SetBoolean("ConfigUseCalculator", use_calculator);
  const bool use_t13n = GET_CONFIG(use_t13n_conversion);
  usage_stats::UsageStats::SetBoolean("ConfigUseT13nConversion", use_t13n);
  const bool use_zip_code = GET_CONFIG(use_zip_code_conversion);
  usage_stats::UsageStats::SetBoolean("ConfigUseZipCodeConversion",
                                      use_zip_code);
  const bool use_spelling_correction = GET_CONFIG(use_spelling_correction);
  usage_stats::UsageStats::SetBoolean("ConfigUseSpellingCorrection",
                                      use_spelling_correction);
  const bool incognito = GET_CONFIG(incognito_mode);
  usage_stats::UsageStats::SetBoolean("ConfigIncognito", incognito);

  const uint32 selection = GET_CONFIG(selection_shortcut);
  usage_stats::UsageStats::SetInteger("ConfigSelectionShortcut", selection);

  const bool use_history = GET_CONFIG(use_history_suggest);
  usage_stats::UsageStats::SetBoolean("ConfigUseHistorySuggest", use_history);
  const bool use_dictionary = GET_CONFIG(use_dictionary_suggest);
  usage_stats::UsageStats::SetBoolean("ConfigUseDictionarySuggest",
                                      use_dictionary);
  const bool use_realtime_conversion = GET_CONFIG(use_realtime_conversion);
  usage_stats::UsageStats::SetBoolean("ConfigUseRealtimeConversion",
                                      use_realtime_conversion);

  const uint32 suggest_size = GET_CONFIG(suggestions_size);
  usage_stats::UsageStats::SetInteger("ConfigSuggestionsSize", suggest_size);

  const bool use_auto_ime_turn_off = GET_CONFIG(use_auto_ime_turn_off);
  usage_stats::UsageStats::SetBoolean("ConfigUseAutoIMETurnOff",
                                      use_auto_ime_turn_off);
  const bool use_cascading_window = GET_CONFIG(use_cascading_window);
  usage_stats::UsageStats::SetBoolean("ConfigUseCascadingWindow",
                                      use_cascading_window);

  const uint32 shift = GET_CONFIG(shift_key_mode_switch);
  usage_stats::UsageStats::SetInteger("ConfigShiftKeyModeSwitch", shift);
  const uint32 space = GET_CONFIG(space_character_form);
  usage_stats::UsageStats::SetInteger("ConfigSpaceCharacterForm", space);
  const uint32 numpad = GET_CONFIG(numpad_character_form);
  usage_stats::UsageStats::SetInteger("ConfigNumpadCharacterForm", numpad);

  const bool use_auto_conversion = GET_CONFIG(use_auto_conversion);
  usage_stats::UsageStats::SetBoolean("ConfigUseAutoConversion",
                                      use_auto_conversion);
  const uint32 auto_conversion_key = GET_CONFIG(auto_conversion_key);
  usage_stats::UsageStats::SetInteger("ConfigAutoConversionKey",
                                      auto_conversion_key);

  const uint32 yen_sign_character = GET_CONFIG(yen_sign_character);
  usage_stats::UsageStats::SetInteger("ConfigYenSignCharacter",
                                      yen_sign_character);

  const bool use_japanese_layout = GET_CONFIG(use_japanese_layout);
  usage_stats::UsageStats::SetBoolean("ConfigUseJapaneseLayout",
                                       use_japanese_layout);

  const bool ime_activation_key_customized = IMEActivationKeyCustomized();
  usage_stats::UsageStats::SetBoolean("IMEActivationKeyCustomized",
                                      ime_activation_key_customized);
}

// Return true if the value is in the candidate.
bool FindInCandidates(const string &value,
                      const commands::CandidateList &candidates) {
  for (size_t i = 0; i < candidates.candidates_size(); ++i) {
    if (value == candidates.candidates(i).value()) {
      return true;
    }
  }
  return false;
}

// Return session state mode from candidate mode
session::SessionState::Mode GetSessionModeFromCandidateList(
    const commands::CandidateList &candidate_list) {
  switch (candidate_list.category()) {
    case commands::CONVERSION:
      return session::SessionState::CONVERSION;
    case commands::PREDICTION:
      return session::SessionState::PREDICTION;
    case commands::SUGGESTION:
      return session::SessionState::SUGGESTION;
    default:
      DLOG(FATAL) << "invalid candidate category";
      return session::SessionState::COMPOSITION;
  }
}

// Return true if input is mouse select command
bool IsMouseSelect(const commands::Input &input) {
  return (input.type() == commands::Input::SEND_COMMAND &&
          input.has_command() &&
          (input.command().type() ==
              commands::SessionCommand::SELECT_CANDIDATE ||
           input.command().type() ==
              commands::SessionCommand::SUBMIT_CANDIDATE));
}

// Return true if resegmented
bool IsResegmented(const commands::Preedit &prev_preedit,
                   const commands::Preedit &cur_preedit) {
  if (prev_preedit.segment_size() != cur_preedit.segment_size()) {
    return true;
  }
  int changed_segment = 0;
  for (size_t i = 0; i < prev_preedit.segment_size(); ++i) {
    if (prev_preedit.segment(i).key() != cur_preedit.segment(i).key()) {
      ++changed_segment;
    }
  }
  return (changed_segment > 1);
}

// Return true if given preedits are same in value.
bool IsSamePreedit(const commands::Preedit &prev_preedit,
                   const commands::Preedit &cur_preedit) {
  if (prev_preedit.segment_size() != cur_preedit.segment_size()) {
    return false;
  }
  for (size_t i = 0; i < prev_preedit.segment_size(); ++i) {
    if (prev_preedit.segment(i).value() != cur_preedit.segment(i).value()) {
      return false;
    }
  }
  return true;
}

// Find candidate with value and set its index to |idx|.
// Return false if |value| is not found in candidates.
bool GetSelectedIndex(const string &value,
                      const commands::Candidates &candidates, int *idx) {
  DCHECK(idx != NULL);
  *idx = 0;
  if (candidates.has_subcandidates() &&
      (candidates.subcandidates().category() == commands::TRANSLITERATION)) {
    for (size_t i = 0; i < candidates.subcandidates().candidate_size(); ++i) {
      if (value == candidates.subcandidates().candidate(i).value()) {
        const int t13n_idx = candidates.subcandidates().candidate(i).index();
        // t13n candidates
        *idx = (-t13n_idx - 1);
        return true;
      }
    }
  }
  for (size_t i = 0; i < candidates.candidate_size(); ++i) {
    if (value == candidates.candidate(i).value()) {
      *idx = candidates.candidate(i).index();
      return true;
    }
  }
  return false;
}

// Return true if state's candidates have given category
bool CheckCandidateCategory(const SessionState *state,
                            commands::Category category) {
  return (state->has_candidates() &&
          state->candidates().category() == category);
}

}  // namespace

class EventConverter {
 public:
  EventConverter() {
    specialkey_map_[commands::KeyEvent::NO_SPECIALKEY] = "NO_SPECIALKEY";
    specialkey_map_[commands::KeyEvent::DIGIT] = "DIGIT";
    specialkey_map_[commands::KeyEvent::ON] = "ON";
    specialkey_map_[commands::KeyEvent::OFF] = "OFF";
    specialkey_map_[commands::KeyEvent::SPACE] = "SPACE";
    specialkey_map_[commands::KeyEvent::ENTER] = "ENTER";
    specialkey_map_[commands::KeyEvent::LEFT] = "LEFT";
    specialkey_map_[commands::KeyEvent::RIGHT] = "RIGHT";
    specialkey_map_[commands::KeyEvent::UP] = "UP";
    specialkey_map_[commands::KeyEvent::DOWN] = "DOWN";
    specialkey_map_[commands::KeyEvent::ESCAPE] = "ESCAPE";
    specialkey_map_[commands::KeyEvent::DEL] = "DEL";
    specialkey_map_[commands::KeyEvent::BACKSPACE] = "BACKSPACE";
    specialkey_map_[commands::KeyEvent::HENKAN] = "HENKAN";
    specialkey_map_[commands::KeyEvent::MUHENKAN] = "MUHENKAN";
    specialkey_map_[commands::KeyEvent::KANA] = "KANA";
    specialkey_map_[commands::KeyEvent::HOME] = "HOME";
    specialkey_map_[commands::KeyEvent::END] = "END";
    specialkey_map_[commands::KeyEvent::TAB] = "TAB";
    specialkey_map_[commands::KeyEvent::F1] = "F1";
    specialkey_map_[commands::KeyEvent::F2] = "F2";
    specialkey_map_[commands::KeyEvent::F3] = "F3";
    specialkey_map_[commands::KeyEvent::F4] = "F4";
    specialkey_map_[commands::KeyEvent::F5] = "F5";
    specialkey_map_[commands::KeyEvent::F6] = "F6";
    specialkey_map_[commands::KeyEvent::F7] = "F7";
    specialkey_map_[commands::KeyEvent::F8] = "F8";
    specialkey_map_[commands::KeyEvent::F9] = "F9";
    specialkey_map_[commands::KeyEvent::F10] = "F10";
    specialkey_map_[commands::KeyEvent::F11] = "F11";
    specialkey_map_[commands::KeyEvent::F12] = "F12";
    specialkey_map_[commands::KeyEvent::PAGE_UP] = "PAGE_UP";
    specialkey_map_[commands::KeyEvent::PAGE_DOWN] = "PAGE_DOWN";
    specialkey_map_[commands::KeyEvent::INSERT] = "INSERT";
    specialkey_map_[commands::KeyEvent::F13] = "F13";
    specialkey_map_[commands::KeyEvent::F14] = "F14";
    specialkey_map_[commands::KeyEvent::F15] = "F15";
    specialkey_map_[commands::KeyEvent::F16] = "F16";
    specialkey_map_[commands::KeyEvent::F17] = "F17";
    specialkey_map_[commands::KeyEvent::F18] = "F18";
    specialkey_map_[commands::KeyEvent::F19] = "F19";
    specialkey_map_[commands::KeyEvent::F20] = "F20";
    specialkey_map_[commands::KeyEvent::F21] = "F21";
    specialkey_map_[commands::KeyEvent::F22] = "F22";
    specialkey_map_[commands::KeyEvent::F23] = "F23";
    specialkey_map_[commands::KeyEvent::F24] = "F24";
    specialkey_map_[commands::KeyEvent::EISU] = "EISU";
    specialkey_map_[commands::KeyEvent::NUMPAD0] = "NUMPAD0";
    specialkey_map_[commands::KeyEvent::NUMPAD1] = "NUMPAD1";
    specialkey_map_[commands::KeyEvent::NUMPAD2] = "NUMPAD2";
    specialkey_map_[commands::KeyEvent::NUMPAD3] = "NUMPAD3";
    specialkey_map_[commands::KeyEvent::NUMPAD4] = "NUMPAD4";
    specialkey_map_[commands::KeyEvent::NUMPAD5] = "NUMPAD5";
    specialkey_map_[commands::KeyEvent::NUMPAD6] = "NUMPAD6";
    specialkey_map_[commands::KeyEvent::NUMPAD7] = "NUMPAD7";
    specialkey_map_[commands::KeyEvent::NUMPAD8] = "NUMPAD8";
    specialkey_map_[commands::KeyEvent::NUMPAD9] = "NUMPAD9";
    specialkey_map_[commands::KeyEvent::MULTIPLY] = "MULTIPLY";
    specialkey_map_[commands::KeyEvent::ADD] = "ADD";
    specialkey_map_[commands::KeyEvent::SEPARATOR] = "SEPARATOR";
    specialkey_map_[commands::KeyEvent::SUBTRACT] = "SUBTRACT";
    specialkey_map_[commands::KeyEvent::DECIMAL] = "DECIMAL";
    specialkey_map_[commands::KeyEvent::DIVIDE] = "DIVIDE";
    specialkey_map_[commands::KeyEvent::EQUALS] = "EQUALS";
    specialkey_map_[commands::KeyEvent::ASCII] = "ASCII";
    specialkey_map_[commands::KeyEvent::HANKAKU] = "HANKAKU";
    specialkey_map_[commands::KeyEvent::KANJI] = "KANJI";
    specialkey_map_[commands::KeyEvent::KATAKANA] = "KATAKANA";
  }

  const map<uint32, string> &GetSpecialKeyMap() const {
    return specialkey_map_;
  }

 private:
  map<uint32, string> specialkey_map_;
};

SessionUsageObserver::SessionUsageObserver() :
    update_count_(0),
    save_interval_(kDefaultSaveInterval) {
  SetConfigStats();
}

SessionUsageObserver::~SessionUsageObserver() {
  SaveStats();
}

void SessionUsageObserver::SetInterval(uint32 val) {
  save_interval_ = val;
}

void SessionUsageObserver::SaveStats() {
  for (map<string, uint32>::const_iterator iter = count_cache_.begin();
       iter != count_cache_.end(); ++iter) {
    usage_stats::UsageStats::IncrementCountBy(iter->first, iter->second);
  }
  count_cache_.clear();

  for (map<string, vector<uint32> >::const_iterator iter
           = timing_cache_.begin();
       iter != timing_cache_.end(); ++iter) {
    usage_stats::UsageStats::UpdateTimingBy(iter->first, iter->second);
  }
  timing_cache_.clear();

  for (map<string, int>::const_iterator iter = integer_cache_.begin();
       iter != integer_cache_.end(); ++iter) {
    usage_stats::UsageStats::SetInteger(iter->first, iter->second);
  }
  integer_cache_.clear();

  for (map<string, bool>::const_iterator iter = boolean_cache_.begin();
       iter != boolean_cache_.end(); ++iter) {
    usage_stats::UsageStats::SetBoolean(iter->first, iter->second);
  }
  boolean_cache_.clear();

  update_count_ = 0;
  usage_stats::UsageStats::Sync();
  VLOG(3) << "Save Stats";
}

void SessionUsageObserver::IncrementCount(const string &name) {
  IncrementCountBy(name, 1);
}

void SessionUsageObserver::IncrementCountBy(const string &name,
                                            uint64 count) {
  DCHECK(usage_stats::UsageStats::IsListed(name))
      << name << " is not in the stats list";
  count_cache_[name] += count;
  ++update_count_;
  if (update_count_ >= save_interval_) {
    SaveStats();
  }
}

void SessionUsageObserver::UpdateTiming(const string &name, uint64 val) {
  DCHECK(usage_stats::UsageStats::IsListed(name))
      << name << " is not in the stats list";
  timing_cache_[name].push_back(val);
  ++update_count_;
  if (update_count_ >= save_interval_) {
    SaveStats();
  }
}

void SessionUsageObserver::SetInteger(const string &name, int val) {
  DCHECK(usage_stats::UsageStats::IsListed(name))
      << name << " is not in the stats list";
  integer_cache_[name] = val;
  ++update_count_;
  if (update_count_ >= save_interval_) {
    SaveStats();
  }
}

void SessionUsageObserver::SetBoolean(const string &name, bool val) {
  DCHECK(usage_stats::UsageStats::IsListed(name))
      << name << " is not in the stats list";
  boolean_cache_[name] = val;
  ++update_count_;
  if (update_count_ >= save_interval_) {
    SaveStats();
  }
}

void SessionUsageObserver::EvalCreateSession(const commands::Input &input,
                                             const commands::Output &output,
                                             map<uint64, SessionState> *states) {
  // Number of create session
  IncrementCount("SessionCreated");
  SessionState state;
  state.set_id(output.id());
  state.set_created_time(time(NULL));
  // TODO(toshiyuki): LRU?
  if (states->size() <= kMaxSession) {
    states->insert(make_pair(output.id(), state));
  }
}

void SessionUsageObserver::UpdateMode(const commands::Input &input,
                                      const commands::Output &output,
                                      SessionState *state) const {
  if (!output.has_preedit()) {
    state->set_mode(session::SessionState::COMPOSITION);
    return;
  }

  bool has_highlighted = false;
  for (size_t i = 0; i < output.preedit().segment_size(); ++i) {
    if (output.preedit().segment(i).annotation() ==
        commands::Preedit::Segment::HIGHLIGHT) {
      has_highlighted = true;
      break;
    }
  }

  if (!has_highlighted) {
    state->set_mode(session::SessionState::COMPOSITION);
    return;
  }

  // Mouse select and no candidate window now.
  if (IsMouseSelect(input)) {
    if (state->has_all_candidate_words()) {
      state->set_mode(
          GetSessionModeFromCandidateList(state->all_candidate_words()));
    }
    return;
  }

  if (output.has_all_candidate_words()) {
    state->set_mode(
        GetSessionModeFromCandidateList(output.all_candidate_words()));
    return;
  }

  if (state->mode() == session::SessionState::COMPOSITION) {
    // First conversion
    state->set_mode(session::SessionState::CONVERSION);
  }
}

// Update selected indices
void SessionUsageObserver::UpdateSelectedIndices(const commands::Input &input,
                                                 const commands::Output &output,
                                                 SessionState *state) const {
  if (!output.has_preedit()) {
    state->clear_selected_indices();
    return;
  }

  if (state->selected_indices_size() == 0) {
    for (size_t i = 0; i < output.preedit().segment_size(); ++i) {
      state->add_selected_indices(0);
    }
  }

  if (IsSamePreedit(state->preedit(), output.preedit())) {
    // no change
    return;
  }

  if (IsResegmented(state->preedit(), output.preedit())) {
    // When the conversion result is resegmented, keep the
    // unchanged indices and set others to '0'.
    vector<int> new_indices;
    int changed_idx = 0;
    for (size_t i = 0; i < output.preedit().segment_size(); ++i) {
      if ((output.preedit().segment(i).annotation() ==
           commands::Preedit::Segment::HIGHLIGHT)) {
        changed_idx = i;
        break;
      }
    }
    for (size_t i = 0; i < changed_idx; ++i) {
      new_indices.push_back(state->selected_indices(i));
    }
    for (size_t i = changed_idx; i < output.preedit().segment_size(); ++i) {
      new_indices.push_back(0);
    }
    state->clear_selected_indices();
    for (size_t i = 0; i < new_indices.size(); ++i) {
      state->add_selected_indices(new_indices[i]);
    }
  } else {
    int changed_idx = 0;
    // Find target segment.
    for (size_t i = 0; i < output.preedit().segment_size(); ++i) {
      if ((output.preedit().segment(i).annotation() ==
           commands::Preedit::Segment::HIGHLIGHT)) {
        changed_idx = i;
        break;
      }
    }
    const string &new_value = output.preedit().segment(changed_idx).value();
    int idx = 0;
    if (output.has_candidates() &&
        GetSelectedIndex(new_value, output.candidates(), &idx)) {
      state->set_selected_indices(changed_idx, idx);
    } else if (IsMouseSelect(input) &&
               state->has_candidates() &&
               GetSelectedIndex(new_value, state->candidates(), &idx)) {
      // Candidate can be selected by mouse
      state->set_selected_indices(changed_idx, idx);
    } else {
      state->set_selected_indices(changed_idx, kSelectDirectly);
    }
  }
}

void SessionUsageObserver::UpdateState(const commands::Input &input,
                                       const commands::Output &output,
                                       SessionState *state) {
  // Preedit
  if (!state->has_preedit() && output.has_preedit()) {
    // Start preedit
    state->set_start_preedit_time(time(NULL));
  } else if (state->has_preedit() && output.has_preedit()) {
    // Continue preedit
  } else if (state->has_preedit() && !output.has_preedit()) {
    // Finish preedit
    const uint64 duration = time(NULL) - state->start_preedit_time();
    UpdateTiming("PreeditDuration", duration);
  } else {
    // no preedit
  }

  // Candidates
  if (!state->has_candidates() && output.has_candidates()) {
    const commands::Candidates &cands = output.candidates();
    switch (cands.category()) {
      case commands::CONVERSION:
        state->set_start_conversion_window_time(time(NULL));
        break;
      case commands::PREDICTION:
        state->set_start_prediction_window_time(time(NULL));
        break;
      case commands::SUGGESTION:
        state->set_start_suggestion_window_time(time(NULL));
        break;
      default:
        LOG(WARNING) << "candidate window has invalid category";
        break;
    }
  } else if (state->has_candidates() &&
             state->candidates().category() == commands::SUGGESTION) {
    if (!output.has_candidates() ||
        output.candidates().category() != commands::SUGGESTION) {
      const uint64 suggest_duration
          = time(NULL) - state->start_suggestion_window_time();
      UpdateTiming("SuggestionWindowDuration",
                   suggest_duration);
    }
    if (output.has_candidates()) {
      switch (output.candidates().category()) {
        case commands::CONVERSION:
          state->set_start_conversion_window_time(time(NULL));
          break;
        case commands::PREDICTION:
          state->set_start_prediction_window_time(time(NULL));
          break;
        case commands::SUGGESTION:
          // continue suggestion
          break;
        default:
          LOG(WARNING) << "candidate window has invalid category";
          break;
      }
    }
  } else if (state->has_candidates() &&
             state->candidates().category() == commands::PREDICTION) {
    if (!output.has_candidates() ||
        output.candidates().category() != commands::PREDICTION) {
      const uint64 predict_duration
          = time(NULL) - state->start_prediction_window_time();
      UpdateTiming("PredictionWindowDuration",
                   predict_duration);
    }
    // no transition
  } else if (state->has_candidates() &&
             state->candidates().category() == commands::CONVERSION) {
    if (!output.has_candidates() ||
        output.candidates().category() != commands::CONVERSION) {
      const uint64 conversion_duration
          = time(NULL) - state->start_conversion_window_time();
      UpdateTiming("ConversionWindowDuration",
                   conversion_duration);
    }
    // no transition
  }

  UpdateSelectedIndices(input, output, state);
  UpdateMode(input, output, state);

  // Cascading window
  if ((!state->has_candidates() ||
       (state->has_candidates() &&
        !state->candidates().has_subcandidates())) &&
      output.has_candidates() && output.candidates().has_subcandidates()) {
    IncrementCount("ShowCascadingWindow");
  }

  // Update Preedit
  if (output.has_preedit()) {
    state->mutable_preedit()->CopyFrom(output.preedit());
  } else {
    state->clear_preedit();
  }

  // Update Candidates
  if (output.has_candidates()) {
    state->mutable_candidates()->CopyFrom(output.candidates());
  } else {
    state->clear_candidates();
  }
  if (output.has_all_candidate_words()) {
    state->mutable_all_candidate_words()->
        CopyFrom(output.all_candidate_words());
  } else {
    state->clear_all_candidate_words();
  }

  if ((!state->has_result() ||
       state->result().type() != commands::Result::STRING) &&
      output.has_result() &&
      output.result().type() == commands::Result::STRING) {
    state->set_committed(true);
  }

  // Update Result
  if (output.has_result()) {
    state->mutable_result()->CopyFrom(output.result());
  } else {
    state->clear_result();
  }
}

void SessionUsageObserver::UpdateClientSideStats(const commands::Input &input,
                                                 SessionState *state) {
  switch (input.command().usage_stats_event()) {
    case commands::SessionCommand::INFOLIST_WINDOW_SHOW:
      if (!state->has_start_infolist_window_time()) {
        state->set_start_infolist_window_time(time(NULL));
      }
      break;
    case commands::SessionCommand::INFOLIST_WINDOW_HIDE:
      if (state->has_start_infolist_window_time()) {
        const uint64 infolist_duration
            = time(NULL) - state->start_infolist_window_time();
        DLOG(INFO) << "infolist_duration:" << infolist_duration;
        UpdateTiming("InfolistWindowDuration", infolist_duration);
        state->clear_start_infolist_window_time();
      }
      break;
    default:
      LOG(WARNING) << "client side usage stats event has invalid category";
      break;
  }
}

void SessionUsageObserver::EvalSendKey(const commands::Input &input,
                                       const commands::Output &output) {
  if (input.has_key() && input.key().has_key_code()) {
    // Number of consumed ASCII(printable) typing
    IncrementCount("ASCIITyping");
  }

  if (input.has_key() && input.key().has_special_key()) {
    // Number of consumed Non-ASCII (special key) typing
    IncrementCount("NonASCIITyping");
    const map<uint32, string> special_key_map =
        Singleton<EventConverter>::get()->GetSpecialKeyMap();
    map<uint32, string>::const_iterator iter =
        special_key_map.find(input.key().special_key());
    if (iter != special_key_map.end()) {
      IncrementCount(iter->second);
    }
  }
}

void SessionUsageObserver::UpdateCandidateStats(const string &base_name,
                                                uint32 index) {
  if (index <= 9) {
    const string stats_name = base_name + Util::SimpleItoa(index);
    IncrementCount(stats_name);
  } else {
    const string stats_name = base_name + "GE10";
    IncrementCount(stats_name);
  }
}

void SessionUsageObserver::CheckOutput(const commands::Input &input,
                                       const commands::Output &output,
                                       const SessionState *state) {
  if (!output.has_result() ||
      output.result().type() != commands::Result::STRING) {
    // No commit string
    return;
  }

  // commit preedit
  IncrementCount("Commit");

  const string &submit_value = output.result().value();

  if (state->mode() == session::SessionState::SUGGESTION ||
      (CheckCandidateCategory(state, commands::SUGGESTION) &&
       FindInCandidates(submit_value, state->all_candidate_words()))) {
    // We should check the candidate contents because suggestion
    // candidates are shown automatically.
    IncrementCount("CommitFromSuggestion");
    if (input.command().type() == commands::SessionCommand::SUBMIT_CANDIDATE ||
        state->selected_indices_size() == 0) {
      // Committed zero-query suggest candidate
      UpdateCandidateStats("SuggestionCandidates", input.command().id());
    } else {
      const uint32 index = state->selected_indices(0);
      if (index == kSelectDirectly) {
        // Treat as top candidate
        UpdateCandidateStats("SuggestionCandidates", 0);
      } else {
        UpdateCandidateStats("SuggestionCandidates", index);
      }
    }
  } else if (state->mode() == session::SessionState::PREDICTION ||
             CheckCandidateCategory(state, commands::PREDICTION)) {
    IncrementCount("CommitFromPrediction");
    DCHECK(state->selected_indices_size() == 1);
    const uint32 index = state->selected_indices(0);
    if (index == kSelectDirectly) {
      // Treat as top candidate
      UpdateCandidateStats("PredictionCandidates", 0);
    } else {
      UpdateCandidateStats("PredictionCandidates", index);
    }
  } else if (state->mode() == session::SessionState::CONVERSION ||
             CheckCandidateCategory(state, commands::CONVERSION)) {
    IncrementCount("CommitFromConversion");
    for (size_t i = 0; i < state->selected_indices_size(); ++i) {
      const int index = state->selected_indices(i);
      if (index == kSelectDirectly) {
        // Treat as top conversion candidate
        // This may treat 'F8' result to 'ConversionCandidates0'.
        UpdateCandidateStats("ConversionCandidates", 0);
      } else  if (index < 0) {
        const int t13n_index = -index-1;
        UpdateCandidateStats("TransliterationCandidates", t13n_index);
      } else {
        UpdateCandidateStats("ConversionCandidates", index);
      }
    }
  } else if (state->has_preedit()) {
    IncrementCount("CommitFromComposition");
  }

  if (state->has_preedit()) {
    uint64 total_len = 0;
    for (size_t i = 0; i < state->preedit().segment_size(); ++i) {
      const uint32 len = state->preedit().segment(i).value_length();
      total_len += len;
      UpdateTiming("SubmittedSegmentLength", len);
    }
    UpdateTiming("SubmittedLength", total_len);
    UpdateTiming("SubmittedSegmentNumber",state->preedit().segment_size());
    IncrementCountBy("SubmittedTotalLength", total_len);
  } else {
    // Zero-query Suggest
    size_t length = Util::CharsLen(submit_value.c_str(), submit_value.size());
    UpdateTiming("SubmittedSegmentLength", length);
    UpdateTiming("SubmittedLength", length);
    UpdateTiming("SubmittedSegmentNumber", 1);
    IncrementCountBy("SubmittedTotalLength", length);
  }
}

void SessionUsageObserver::EvalCommandHandler(
    const commands::Command &command) {
  const commands::Input &input = command.input();
  const commands::Output &output = command.output();

  IncrementCount("SessionAllEvent");
  UpdateTiming("ElapsedTime", output.elapsed_time());

  if (output.has_performed_command() &&
      !output.performed_command().empty()) {
    IncrementCount("Performed_" + output.performed_command());
  }

  if (input.type() == commands::Input::SEND_KEY) {
    if (output.has_consumed() && output.consumed()) {
      IncrementCount("ConsumedSendKey");
    } else {
      IncrementCount("UnconsumedSendKey");
    }
    EvalSendKey(input, output);
  }

  if (input.type() == commands::Input::CREATE_SESSION) {
    EvalCreateSession(input, output, &states_);
    SaveStats();
    return;
  } else if (!input.has_id()) {
    LOG(WARNING) << "no id";
    // Should have id
    return;
  }

  if (input.type() == commands::Input::SET_CONFIG) {
    IncrementCount("SetConfig");
    SetConfigStats();
  }
  if (input.type() == commands::Input::SHUTDOWN) {
    IncrementCount("ShutDown");
  }
  if (input.type() == commands::Input::CLEAR_USER_HISTORY) {
    IncrementCount("ClearUserHistory");
  }
  if (input.type() == commands::Input::CLEAR_USER_PREDICTION) {
    IncrementCount("ClearUserPrediction");
  }
  if (input.type() == commands::Input::CLEAR_UNUSED_USER_PREDICTION) {
    IncrementCount("ClearUnusedUserPrediction");
  }

  if (input.id() == 0) {
    VLOG(3) << "id == 0";
    return;
  }

  map<uint64, SessionState>::iterator iter = states_.find(input.id());
  if (iter == states_.end()) {
    LOG(WARNING) << "unknown session";
    // Unknown session
    return;
  }
  SessionState *state = &iter->second;
  DCHECK(state);

  if (input.type() == commands::Input::DELETE_SESSION) {
    // Session duration sec
    const uint64 duration = time(NULL) - state->created_time();
    UpdateTiming("SessionDuration", duration);

    states_.erase(iter);
    SaveStats();
    return;
  }

  // Backspace key after commit
  if (state->committed() &&
       // for Applications supporting TEST_SEND_KEY
      (input.type() == commands::Input::TEST_SEND_KEY ||
       // other Applications
       input.type() == commands::Input::SEND_KEY)) {
    if (input.has_key() && input.key().has_special_key() &&
        input.key().special_key() == commands::KeyEvent::BACKSPACE &&
        state->has_result() &&
        state->result().type() == commands::Result::STRING) {
      IncrementCount("BackSpaceAfterCommit");
      // Count only one for each submitted result.
    }
    state->set_committed(false);
  }

  if (IsMouseSelect(input)) {
    IncrementCount("MouseSelect");
  }

  // Client side event
  if ((input.type() == commands::Input::SEND_COMMAND) &&
      (input.has_command()) &&
      (input.command().type() ==
           commands::SessionCommand::USAGE_STATS_EVENT) &&
      (input.command().has_usage_stats_event())) {
    UpdateClientSideStats(input, state);
  }

  if ((input.type() == commands::Input::SEND_COMMAND ||
       input.type() == commands::Input::SEND_KEY) &&
      output.has_consumed() &&
      output.consumed()) {
    // update states only when input was consumed
    CheckOutput(input, output, state);
    UpdateState(input, output, state);
  }
}

void SessionUsageObserver::Reload() {
}

}  // namespace mozc::session
}  // namespace mozc


text:
require 'page_navigation'

module Mohawk
  module Navigation
    include PageNavigation

    def on(cls, extra={}, &block)
      screen = cls.new extra
      screen.wait_until_present "Unable to locate #{cls} using #{screen.adapter.locator}"
      block.call screen if block
      screen
    end
  end
end


text:
name              "pubbub"
description       "Deploys Paper Bubbles Dev Env"
version           "0.0.1"


text:
var express = require('express'),
  cons = require('consolidate'),
  config = require('config'),
  app = express(),
  port = process.env.PORT || 4000;

app.use(express.bodyParser());
app.engine('html', cons.hogan);
app.set('view engine', 'html');
app.set('views', __dirname + '/views');

var rootDir = require('path').dirname(module.filename);
var pubDir = rootDir + config.app.pubDir;
var srcDir = rootDir + config.app.srcDir;
app.use(express.static(pubDir));

app.listen(config.app.port);

app.get('/', function(req, res) {
  res.render('index');
});

app.post('/compare/', function(req, res) {
  var sim = require(srcDir + 'sim');
  var result = sim.compare([req.body.doc1, req.body.doc2]);
  result = (result * 100).toFixed(2) + "%";
  res.send(result);
});


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
N. Amer. Fl. (New York) 7: 1018 (1939)

#### Original name
Urocystis fraseri G.P. Clinton & Zundel

### Remarks
null


text:
package org.metafacture.metamorph.test;

import java.io.FileNotFoundException;
import java.io.StringReader;

import org.junit.runners.model.InitializationError;
import org.junit.runners.model.Statement;
import org.metafacture.commons.ResourceUtil;
import org.metafacture.commons.XmlUtil;
import org.metafacture.commons.reflection.ReflectionUtil;
import org.metafacture.framework.StreamPipe;
import org.metafacture.framework.StreamReceiver;
import org.metafacture.javaintegration.EventList;
import org.metafacture.metamorph.Metamorph;
import org.metafacture.metamorph.test.reader.MultiFormatReader;
import org.metafacture.metamorph.test.reader.Reader;
import org.metafacture.metamorph.test.validators.StreamValidator;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

/**
 * Runs a test defined in a Metamorph-Test definition.
 *
 * @author Christoph Böhme
 *
 */
final class MetamorphTestCase extends Statement {

	private static final String NO_DATA_FOUND =
			"Please specify either element content or a src attribute";

	private static final String NAME_ATTR = "name";
	private static final String IGNORE_ATTR = "ignore";
	private static final String RESULT_TAG = "result";
	private static final String TRANSFORMATION_TAG = "transformation";
	private static final String INPUT_TAG = "input";
	private static final String SRC_ATTR = "src";
	private static final String TYPE_ATTR = "type";
	private static final String STRICT_RECORD_ORDER_ATTR = "strict-record-order";
	private static final String STRICT_KEY_ORDER_ATTR = "strict-key-order";
	private static final String STRICT_VALUE_ORDER_ATTR = "strict-value-order";

	private static final String MIME_METAMORPH = "text/x-metamorph+xml";
	private static final String MIME_JAVACLASS = "application/java";

	private final Element config;

	MetamorphTestCase(final Element config) {
		this.config = config;
	}

	public String getName() {
		return config.getAttribute(NAME_ATTR);
	}

	public boolean isIgnore() {
		return Boolean.parseBoolean(config.getAttribute(IGNORE_ATTR));
	}

	@Override
	public void evaluate() throws InitializationError {
		final Reader inputReader = getReader(INPUT_TAG);
		@SuppressWarnings("unchecked")
		final StreamPipe<StreamReceiver>transformation = getTransformation();
		final EventList resultStream = new EventList();

		if (transformation == null) {
			inputReader.setReceiver(resultStream);
		} else {
			inputReader.setReceiver(transformation).setReceiver(resultStream);
		}

		inputReader.process(getInputData());
		inputReader.closeStream();

		final StreamValidator validator = new StreamValidator(resultStream.getEvents());
		validator.setErrorHandler(msg -> { throw new AssertionError(msg); });

		final Element result = (Element) config.getElementsByTagName(RESULT_TAG).item(0);
		validator.setStrictRecordOrder(Boolean.parseBoolean(
				result.getAttribute(STRICT_RECORD_ORDER_ATTR)));
		validator.setStrictKeyOrder(Boolean.parseBoolean(
				result.getAttribute(STRICT_KEY_ORDER_ATTR)));
		validator.setStrictValueOrder(Boolean.parseBoolean(
				result.getAttribute(STRICT_VALUE_ORDER_ATTR)));

		final Reader resultReader = getReader(RESULT_TAG);
		resultReader.setReceiver(validator);

		resultReader.process(getExpectedResult());
		validator.closeStream();
	}

	private Reader getReader(final String tag) {
		final Element element = (Element) config.getElementsByTagName(tag).item(0);
		final String mimeType = element.getAttribute(TYPE_ATTR);
		return new MultiFormatReader(mimeType);
	}

	@SuppressWarnings("rawtypes")
	private StreamPipe getTransformation() throws InitializationError {
		final NodeList nodes = config.getElementsByTagName(TRANSFORMATION_TAG);
		if (nodes.getLength() == 0) {
			return null;
		}
		final Element transformationElement = (Element) nodes.item(0);

		final String type = transformationElement.getAttribute(TYPE_ATTR);
		final String src = transformationElement.getAttribute(SRC_ATTR);

		if (MIME_METAMORPH.equals(type)) {
			if (src.isEmpty()) {
				final InputSource transformationSource =
						new InputSource(getDataEmbedded(transformationElement));
				transformationSource.setSystemId(transformationElement.getBaseURI());
				return new Metamorph(transformationSource);
			}
			return new Metamorph(src);

		} else if (MIME_JAVACLASS.equals(type)) {
			if (src.isEmpty()) {
				throw new InitializationError(
						"class defining transformation not specified");
			}
			return ReflectionUtil.loadClass(src, StreamPipe.class).newInstance();
		}
		throw new InitializationError("transformation of type " + type +
				" is not supperted");
	}

	private java.io.Reader getInputData() throws InitializationError {
		final Element input = (Element) config.getElementsByTagName(INPUT_TAG).item(0);

		if (input.hasAttribute(SRC_ATTR)) {
			return getDataFromSource(input.getAttribute(SRC_ATTR));
		}
		return getDataEmbedded(input);
	}

	private java.io.Reader getExpectedResult() throws InitializationError {
		final Element result = (Element) config.getElementsByTagName(RESULT_TAG).item(0);
		if (result.hasAttribute(SRC_ATTR)) {
			return getDataFromSource(result.getAttribute(SRC_ATTR));
		}
		return getDataEmbedded(result);
	}

	private java.io.Reader getDataFromSource(final String src)
			throws InitializationError {
		try {
			return ResourceUtil.getReader(src);
		} catch (final FileNotFoundException e) {
			throw new InitializationError("Could not find input file '" + src +
					"': " + e.getMessage());
		}
	}

	private java.io.Reader getDataEmbedded(final Element input)
			throws InitializationError {
		final String inputType = input.getAttribute(TYPE_ATTR);
		if (input.hasChildNodes()) {
			if (XmlUtil.isXmlMimeType(inputType)) {
				return new StringReader(XmlUtil.nodeListToString(input.getChildNodes()));
			}
			return new StringReader(input.getTextContent());
		}
		throw new InitializationError(NO_DATA_FOUND);
	}

}


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Html;
using Microsoft.DotNet.Interactive;
using Microsoft.DotNet.Interactive.Formatting;
using static Microsoft.DotNet.Interactive.Formatting.PocketViewTags;

namespace Microsoft.Data.Analysis.Interactive
{
    public class DataFrameKernelExtension : IKernelExtension
    {
        public Task OnLoadAsync(Kernel kernel)
        {
            RegisterDataFrame();

            return Task.CompletedTask;
        }

        public static void RegisterDataFrame()
        {
            Formatter<DataFrame>.Register((df, writer) =>
            {
                const int MAX = 10000;
                const int SIZE = 10;

                var uniqueId = DateTime.Now.Ticks;

                var header = new List<IHtmlContent>
                {
                    th(i("index"))
                };
                header.AddRange(df.Columns.Select(c => (IHtmlContent)th(c.Name)));

                if (df.Rows.Count > SIZE)
                {
                    var maxMessage = df.Rows.Count > MAX ? $" (showing a max of {MAX} rows)" : string.Empty;
                    var title = h3[style: "text-align: center;"]($"DataFrame - {df.Rows.Count} rows {maxMessage}");

                    // table body
                    var maxRows = Math.Min(MAX, df.Rows.Count);
                    var rows = new List<List<IHtmlContent>>();
                    for (var index = 0; index < maxRows; index++)
                    {
                        var cells = new List<IHtmlContent>
                        {
                            td(i((index)))
                        };
                        foreach (var obj in df.Rows[index])
                        {
                            cells.Add(td(obj));
                        }
                        rows.Add(cells);
                    }

                    //navigator
                    var footer = new List<IHtmlContent>();
                    BuildHideRowsScript(uniqueId);

                    var paginateScriptFirst = BuildHideRowsScript(uniqueId) + GotoPageIndex(uniqueId, 0) + BuildPageScript(uniqueId, SIZE);
                    footer.Add(button[style: "margin: 2px;", onclick: paginateScriptFirst]("⏮"));

                    var paginateScriptPrevTen = BuildHideRowsScript(uniqueId) + UpdatePageIndex(uniqueId, -10, (maxRows - 1) / SIZE) + BuildPageScript(uniqueId, SIZE);
                    footer.Add(button[style: "margin: 2px;", onclick: paginateScriptPrevTen]("⏪"));

                    var paginateScriptPrev = BuildHideRowsScript(uniqueId) + UpdatePageIndex(uniqueId, -1, (maxRows - 1) / SIZE) + BuildPageScript(uniqueId, SIZE);
                    footer.Add(button[style: "margin: 2px;", onclick: paginateScriptPrev]("◀"));

                    footer.Add(b[style: "margin: 2px;"]("Page"));
                    footer.Add(b[id: $"page_{uniqueId}", style: "margin: 2px;"]("1"));

                    var paginateScriptNext = BuildHideRowsScript(uniqueId) + UpdatePageIndex(uniqueId, 1, (maxRows - 1) / SIZE) + BuildPageScript(uniqueId, SIZE);
                    footer.Add(button[style: "margin: 2px;", onclick: paginateScriptNext]("▶"));

                    var paginateScriptNextTen = BuildHideRowsScript(uniqueId) + UpdatePageIndex(uniqueId, 10, (maxRows - 1) / SIZE) + BuildPageScript(uniqueId, SIZE);
                    footer.Add(button[style: "margin: 2px;", onclick: paginateScriptNextTen]("⏩"));

                    var paginateScriptLast = BuildHideRowsScript(uniqueId) + GotoPageIndex(uniqueId, (maxRows - 1) / SIZE) + BuildPageScript(uniqueId, SIZE);
                    footer.Add(button[style: "margin: 2px;", onclick: paginateScriptLast]("⏭"));

                    //table
                    var t = table[id: $"table_{uniqueId}"](
                        caption(title),
                        thead(tr(header)),
                        tbody(rows.Select(r => tr[style: "display: none"](r))),
                        tfoot(tr(td[colspan: df.Columns.Count + 1, style: "text-align: center;"](footer)))
                    );
                    writer.Write(t);

                    //show first page
                    writer.Write($"<script>{BuildPageScript(uniqueId, SIZE)}</script>");
                }
                else
                {
                    var rows = new List<List<IHtmlContent>>();
                    for (var index = 0; index < df.Rows.Count; index++)
                    {
                        var cells = new List<IHtmlContent>
                        {
                            td(i((index)))
                        };
                        foreach (var obj in df.Rows[index])
                        {
                            cells.Add(td(obj));
                        }
                        rows.Add(cells);
                    }

                    //table
                    var t = table[id: $"table_{uniqueId}"](
                        thead(tr(header)),
                        tbody(rows.Select(r => tr(r)))
                    );
                    writer.Write(t);
                }
            }, "text/html");
        }

        private static string BuildHideRowsScript(long uniqueId)
        {
            var script = $"var allRows = document.querySelectorAll('#table_{uniqueId} tbody tr:nth-child(n)'); ";
            script += "for (let i = 0; i < allRows.length; i++) { allRows[i].style.display='none'; } ";
            return script;
        }

        private static string BuildPageScript(long uniqueId, int size)
        {
            var script = $"var page = parseInt(document.querySelector('#page_{uniqueId}').innerHTML) - 1; ";
            script += $"var pageRows = document.querySelectorAll(`#table_{uniqueId} tbody tr:nth-child(n + ${{page * {size} + 1 }})`); ";
            script += $"for (let j = 0; j < {size}; j++) {{ pageRows[j].style.display='table-row'; }} ";
            return script;
        }

        private static string GotoPageIndex(long uniqueId, long page)
        {
            var script = $"document.querySelector('#page_{uniqueId}').innerHTML = {page + 1}; ";
            return script;
        }

        private static string UpdatePageIndex(long uniqueId, int step, long maxPage)
        {
            var script = $"var page = parseInt(document.querySelector('#page_{uniqueId}').innerHTML) - 1; ";
            script += $"page = parseInt(page) + parseInt({step}); ";
            script += $"page = page < 0 ? 0 : page; ";
            script += $"page = page > {maxPage} ? {maxPage} : page; ";
            script += $"document.querySelector('#page_{uniqueId}').innerHTML = page + 1; ";
            return script;
        }
    }
}


text:
The Opsoro construction system is based around a grid system. Grid plates form
the backbone onto which the modules are attached. Modules can be attached to a
grid plate using a single M3x10 cap screw. The video below shows a quick
demonstration of this principle.

<video autoplay="" loop="" muted="" playsinline="" preload="true">
  <source src="/video/minigrid-demo.webm" type="video/webm">
  <source src="/video/minigrid-demo.mp4" type="video/mp4">
</video>

## Dimensions
The figure above shows the basic grid dimensions. The grid consists of
3mm × 3mm square holes, spaced at an 8mm interval. The design files for a
standard A4-sized grid can be found
[here](https://github.com/OPSORO/BUILD/tree/master/grid). The A4 grid can be
used as a starting point, however nothing is stopping you from creating
custom-sized grids.

<img src="/images/grid/grid-dimensions.png" style="width: 50%;">


text:
<?php

namespace App\Http\Models;

use Illuminate\Database\Eloquent\Model;
use DB;

class Scores extends Model
{
    /**
     * モデルと関連しているテーブル
     *
     * @var string
     */
     protected $table = 'scores';
     public $timestamps = false;

     public static function ranking()
     {
        $r = DB::table('scores')
        ->select(DB::raw('users.name as name, sum(questions.score) as score'))
        ->leftJoin('questions', 'scores.question_id', '=','questions.id')
        ->whereRaw('scores.flag = questions.flag')
        ->leftJoin('users', 'scores.user_id', '=','users.id')
        ->groupBy('name')
        ->orderBy('score', 'DESC')
        ->get();
        return $r;
     }
}


text:
<?php
include('../starfish/starfish.php');
starfish::config(array(
	// Basic configuration
    'site_url' => 'http://'.$_SERVER['HTTP_HOST'].'/api-tester/',
	'site_title' => 'Simple API Tester',
	'site_description' => 'Test your API without building a user interface (without a UI)',

    'friendly' => false,
    'router'   => '',
	'root'	   => '../starfish/',
	'objects'  => './objects/',
    'aliases'  => array('s'),
    'debug'    => true,
	'tpl'	   => './template/',

	'session'  => 'apiTester'
));
starfish::init();

// Default path and object / Load saved query
starfish::on('get', '', function() {
    starfish::obj('tester')->html();
});
starfish::on('get', '/exec/::hash', function($hash=false) {
    starfish::obj('tester')->html($hash, true);
});
starfish::on('get', '/load/::hash', function($hash=false) {
    starfish::obj('tester')->html($hash);
});

// Button actions
starfish::on('post', '', function() {
    $hash = starfish::obj('tester')->params_to_string( starfish::params() );

    if (starfish::params('submit') == 'submit')
    {
        starfish::redirect('./exec/'.$hash);
    }
    else
    {
        starfish::redirect('./load/'.$hash);
    }
});

// Run the script
starfish::exec();
?>