text:
package org.codehaus.griffon.compile.core.ast.transform;

import griffon.annotations.core.Nonnull;
import griffon.core.mvc.MVCGroup;
import org.codehaus.groovy.ast.ClassNode;
import org.codehaus.groovy.ast.MethodNode;
import org.codehaus.groovy.ast.stmt.EmptyStatement;

import static java.lang.reflect.Modifier.PUBLIC;
import static org.codehaus.griffon.compile.core.ast.GriffonASTUtils.NO_EXCEPTIONS;
import static org.codehaus.griffon.compile.core.ast.GriffonASTUtils.NO_PARAMS;
import static org.codehaus.griffon.compile.core.ast.GriffonASTUtils.injectMethod;
import static org.codehaus.griffon.compile.core.ast.GriffonASTUtils.injectProperty;
import static org.codehaus.griffon.compile.core.ast.GriffonASTUtils.param;
import static org.codehaus.griffon.compile.core.ast.GriffonASTUtils.params;
import static org.codehaus.groovy.ast.ClassHelper.MAP_TYPE;
import static org.codehaus.groovy.ast.ClassHelper.VOID_TYPE;

/**
 * @author Andres Almiray
 * @since 2.0.0
 */
public class GriffonMvcArtifactASTInjector extends GriffonArtifactASTInjector {
    private static final ClassNode MVC_GROUP_TYPE = makeClassSafe(MVCGroup.class);

    @Override
    public void inject(@Nonnull ClassNode classNode, @Nonnull String artifactType) {
        super.inject(classNode, artifactType);

        injectProperty(classNode, "mvcGroup", MVC_GROUP_TYPE);

        // void mvcGroupInit(Map args)
        injectMethod(classNode, new MethodNode(
            "mvcGroupInit",
            PUBLIC,
            VOID_TYPE,
            params(param(makeClassSafe(MAP_TYPE), "args")),
            NO_EXCEPTIONS,
            new EmptyStatement()
        ));

        // void mvcGroupDestroy()
        injectMethod(classNode, new MethodNode(
            "mvcGroupDestroy",
            PUBLIC,
            VOID_TYPE,
            NO_PARAMS,
            NO_EXCEPTIONS,
            new EmptyStatement()
        ));
    }
}


text:
(function(window, $, app) {
    app.define('CTA', '.btnShopThe, .btnShopTheWhite, .btnShopTheTwoLine, .btnShopTheTwoLineWhite');

    var ctaBlack = '.btnShopThe, .btnShopTheTwoLine';
    var ctaWhite = '.btnShopTheWhite, .btnShopTheTwoLineWhite';

    var ctaOne = '.btnShopThe, .btnShopTheWhite';
    var ctaTwo = '.btnShopTheTwoLine, .btnShopTheTwoLineWhite';

    function CtaEditor() {
        var getLink = function() {
            return app.ContentEditor.getSelection().find('a');
        };

        this.detectSelectedCta = function() {
            var $selected = app.ContentEditor.getSelection();
            var $a = getLink();

            $('#ctaId').val($a.data('magtool'));
            $('#ctaContent').val($a.text());

            if ($selected.is(ctaBlack)) {
                $('#ctaBlack').prop('checked', true);
            } else {
                $('#ctaWhite').prop('checked', true);
            }
        };

        this.changeId = function(id) {
            getLink().attr('data-magtool', id);
        };

        this.changeContent = function(txt) {
            getLink().text(txt);
        };

        this.changeColor = function(color) {
            var $selected = app.ContentEditor.getSelection();
            var $selectionControls = app.UI.getSelectionControls();

            if (color == 'black') {
                if ($selected.is(ctaOne)) {
                    $selected.removeClass('btnShopTheWhite').addClass('btnShopThe');
                } else {
                    $selected.removeClass('btnShopTheTwoLineWhite').addClass('btnShopTheTwoLine');
                }
            } else {
                if ($selected.is(ctaOne)) {
                    $selected.removeClass('btnShopThe').addClass('btnShopTheWhite');
                } else {
                    $selected.removeClass('btnShopTheTwoLine').addClass('btnShopTheTwoLineWhite');
                }
            }
        };
    }

    app.registerModule('CtaEditor', CtaEditor);
})(window, jQuery, MagTool);

redpajama_set_name: RedPajamaGithub


text:
My very first article, I'm not even decent at writing but I love it.
I'm not sure what I want to put here yet..


text: C:\Python35\python.exe C:\Users\Jonathan.Astemborski\Desktop\JIRA-Import\Features\create_issues.py


text:
#include <stdio.h>
#include <stdlib.h>
#include "unicode/utypes.h"
#include "cmemory.h"
#include "cstring.h"
#include "filestrm.h"
#include "unicode/udata.h"
#include "unicode/utf16.h"
#include "utrie.h"
#include "unewdata.h"
#include "gensprep.h"
#include "uhash.h"

#define DO_DEBUG_OUT 0

/*
 * StringPrep profile file format ------------------------------------
 *
 * The file format prepared and written here contains a 16-bit trie and a mapping table.
 *
 * Before the data contents described below, there are the headers required by
 * the udata API for loading ICU data. Especially, a UDataInfo structure
 * precedes the actual data. It contains platform properties values and the
 * file format version.
 *
 * The following is a description of format version 2.
 *
 * Data contents:
 *
 * The contents is a parsed, binary form of RFC3454 and possibly
 * NormalizationCorrections.txt depending on the options specified on the profile.
 *
 * Any Unicode code point from 0 to 0x10ffff can be looked up to get
 * the trie-word, if any, for that code point. This means that the input
 * to the lookup are 21-bit unsigned integers, with not all of the
 * 21-bit range used.
 *
 * *.spp files customarily begin with a UDataInfo structure, see udata.h and .c.
 * After that there are the following structures:
 *
 * int32_t indexes[_SPREP_INDEX_TOP];           -- _SPREP_INDEX_TOP=16, see enum in sprpimpl.h file
 *
 * UTrie stringPrepTrie;                        -- size in bytes=indexes[_SPREP_INDEX_TRIE_SIZE]
 *
 * uint16_t mappingTable[];                     -- Contains the sequecence of code units that the code point maps to
 *                                                 size in bytes = indexes[_SPREP_INDEX_MAPPING_DATA_SIZE]
 *
 * The indexes array contains the following values:
 *  indexes[_SPREP_INDEX_TRIE_SIZE]                  -- The size of the StringPrep trie in bytes
 *  indexes[_SPREP_INDEX_MAPPING_DATA_SIZE]          -- The size of the mappingTable in bytes
 *  indexes[_SPREP_NORM_CORRECTNS_LAST_UNI_VERSION]  -- The index of Unicode version of last entry in NormalizationCorrections.txt
 *  indexes[_SPREP_ONE_UCHAR_MAPPING_INDEX_START]    -- The starting index of 1 UChar  mapping index in the mapping table
 *  indexes[_SPREP_TWO_UCHARS_MAPPING_INDEX_START]   -- The starting index of 2 UChars mapping index in the mapping table
 *  indexes[_SPREP_THREE_UCHARS_MAPPING_INDEX_START] -- The starting index of 3 UChars mapping index in the mapping table
 *  indexes[_SPREP_FOUR_UCHARS_MAPPING_INDEX_START]  -- The starting index of 4 UChars mapping index in the mapping table
 *  indexes[_SPREP_OPTIONS]                          -- Bit set of options to turn on in the profile, e.g: USPREP_NORMALIZATION_ON, USPREP_CHECK_BIDI_ON
 *
 *
 * StringPrep Trie :
 *
 * The StringPrep tries is a 16-bit trie that contains data for the profile.
 * Each code point is associated with a value (trie-word) in the trie.
 *
 * - structure of data words from the trie
 *
 *  i)  A value greater than or equal to _SPREP_TYPE_THRESHOLD (0xFFF0)
 *      represents the type associated with the code point
 *      if(trieWord >= _SPREP_TYPE_THRESHOLD){
 *          type = trieWord - 0xFFF0;
 *      }
 *      The type can be :
 *             USPREP_UNASSIGNED
 *             USPREP_PROHIBITED
 *             USPREP_DELETE
 *
 *  ii) A value less than _SPREP_TYPE_THRESHOLD means the type is USPREP_MAP and
 *      contains distribution described below
 *
 *      0       -  ON : The code point is prohibited (USPREP_PROHIBITED). This is to allow for codepoint that are both prohibited and mapped.
 *      1       -  ON : The value in the next 14 bits is an index into the mapping table
 *                 OFF: The value in the next 14 bits is an delta value from the code point
 *      2..15   -  Contains data as described by bit 1. If all bits are set
 *                 (value = _SPREP_MAX_INDEX_VALUE) then the type is USPREP_DELETE
 *
 *
 * Mapping Table:
 * The data in mapping table is sorted according to the length of the mapping sequence.
 * If the type of the code point is USPREP_MAP and value in trie word is an index, the index
 * is compared with start indexes of sequence length start to figure out the length according to
 * the following algorithm:
 *
 *              if(       index >= indexes[_SPREP_ONE_UCHAR_MAPPING_INDEX_START] &&
 *                        index < indexes[_SPREP_TWO_UCHARS_MAPPING_INDEX_START]){
 *                   length = 1;
 *               }else if(index >= indexes[_SPREP_TWO_UCHARS_MAPPING_INDEX_START] &&
 *                        index < indexes[_SPREP_THREE_UCHARS_MAPPING_INDEX_START]){
 *                   length = 2;
 *               }else if(index >= indexes[_SPREP_THREE_UCHARS_MAPPING_INDEX_START] &&
 *                        index < indexes[_SPREP_FOUR_UCHARS_MAPPING_INDEX_START]){
 *                   length = 3;
 *               }else{
 *                   // The first position in the mapping table contains the length
 *                   // of the sequence
 *                   length = mappingTable[index++];
 *
 *               }
 *
 */

/* file data ---------------------------------------------------------------- */
/* indexes[] value names */

#if UCONFIG_NO_IDNA

/* dummy UDataInfo cf. udata.h */
static UDataInfo dataInfo = {
    sizeof(UDataInfo),
    0,

    U_IS_BIG_ENDIAN,
    U_CHARSET_FAMILY,
    U_SIZEOF_UCHAR,
    0,

    { 0, 0, 0, 0 },                 /* dummy dataFormat */
    { 0, 0, 0, 0 },                 /* dummy formatVersion */
    { 0, 0, 0, 0 }                  /* dummy dataVersion */
};

#else

static int32_t indexes[_SPREP_INDEX_TOP]={ 0 };

static uint16_t* mappingData= NULL;
static int32_t mappingDataCapacity = 0; /* we skip the first index in mapping data */
static int16_t currentIndex = 0; /* the current index into the data trie */
static int32_t maxLength = 0;  /* maximum length of mapping string */

/* UDataInfo cf. udata.h */
static UDataInfo dataInfo={
    sizeof(UDataInfo),
    0,

    U_IS_BIG_ENDIAN,
    U_CHARSET_FAMILY,
    U_SIZEOF_UCHAR,
    0,

    { 0x53, 0x50, 0x52, 0x50 },                 /* dataFormat="SPRP" */
    { 3, 2, UTRIE_SHIFT, UTRIE_INDEX_SHIFT },   /* formatVersion */
    { 3, 2, 0, 0 }                              /* dataVersion (Unicode version) */
};
void
setUnicodeVersion(const char *v) {
    UVersionInfo version;
    u_versionFromString(version, v);
    uprv_memcpy(dataInfo.dataVersion, version, 4);
}

void
setUnicodeVersionNC(UVersionInfo version){
    uint32_t univer = version[0] << 24;
    univer += version[1] << 16;
    univer += version[2] << 8;
    univer += version[3];
    indexes[_SPREP_NORM_CORRECTNS_LAST_UNI_VERSION] = univer;
}
static UNewTrie *sprepTrie;

#define MAX_DATA_LENGTH 11500

#define SPREP_DELTA_RANGE_POSITIVE_LIMIT              8191
#define SPREP_DELTA_RANGE_NEGATIVE_LIMIT              -8192

extern void
init() {

    sprepTrie = (UNewTrie *)uprv_calloc(1, sizeof(UNewTrie));

    /* initialize the two tries */
    if(NULL==utrie_open(sprepTrie, NULL, MAX_DATA_LENGTH, 0, 0, FALSE)) {
        fprintf(stderr, "error: failed to initialize tries\n");
        exit(U_MEMORY_ALLOCATION_ERROR);
    }
}

static UHashtable* hashTable = NULL;

typedef struct ValueStruct {
    UChar* mapping;
    int16_t length;
    UStringPrepType type;
} ValueStruct;

/* Callback for deleting the value from the hashtable */
static void U_CALLCONV valueDeleter(void* obj){
    ValueStruct* value = (ValueStruct*) obj;
    uprv_free(value->mapping);
    uprv_free(value);
}

/* Callback for hashing the entry */
static int32_t U_CALLCONV hashEntry(const UHashTok parm) {
    return  parm.integer;
}

/* Callback for comparing two entries */
static UBool U_CALLCONV compareEntries(const UHashTok p1, const UHashTok p2) {
    return (UBool)(p1.integer != p2.integer);
}

static void
storeMappingData(){

    int32_t pos = UHASH_FIRST;
    const UHashElement* element = NULL;
    ValueStruct* value  = NULL;
    int32_t codepoint = 0;
    int32_t elementCount = 0;
    int32_t writtenElementCount = 0;
    int32_t mappingLength = 1; /* minimum mapping length */
    int32_t oldMappingLength = 0;
    uint16_t trieWord =0;
    int32_t limitIndex = 0;

    if (hashTable == NULL) {
        return;
    }
    elementCount = uhash_count(hashTable);

	/*initialize the mapping data */
    mappingData = (uint16_t*) uprv_calloc(mappingDataCapacity, U_SIZEOF_UCHAR);

    while(writtenElementCount < elementCount){

        while( (element = uhash_nextElement(hashTable, &pos))!=NULL){

            codepoint = element->key.integer;
            value = (ValueStruct*)element->value.pointer;

            /* store the start of indexes */
            if(oldMappingLength != mappingLength){
                /* Assume that index[] is used according to the enums defined */
                if(oldMappingLength <=_SPREP_MAX_INDEX_TOP_LENGTH){
                    indexes[_SPREP_NORM_CORRECTNS_LAST_UNI_VERSION+mappingLength] = currentIndex;
                }
                if(oldMappingLength <= _SPREP_MAX_INDEX_TOP_LENGTH &&
                   mappingLength == _SPREP_MAX_INDEX_TOP_LENGTH +1){

                    limitIndex = currentIndex;

                }
                oldMappingLength = mappingLength;
            }

            if(value->length == mappingLength){
                uint32_t savedTrieWord = 0;
                trieWord = currentIndex << 2;
                /* turn on the 2nd bit to signal that the following bits contain an index */
                trieWord += 0x02;

                if(trieWord > _SPREP_TYPE_THRESHOLD){
                    fprintf(stderr,"trieWord cannot contain value greater than 0x%04X.\n",_SPREP_TYPE_THRESHOLD);
                    exit(U_ILLEGAL_CHAR_FOUND);
                }
                /* figure out if the code point has type already stored */
                savedTrieWord= utrie_get32(sprepTrie,codepoint,NULL);
                if(savedTrieWord!=0){
                    if((savedTrieWord- _SPREP_TYPE_THRESHOLD) == USPREP_PROHIBITED){
                        /* turn on the first bit in trie word */
                        trieWord += 0x01;
                    }else{
                        /*
                         * the codepoint has value something other than prohibited
                         * and a mapping .. error!
                         */
                        fprintf(stderr,"Type for codepoint \\U%08X already set!.\n", (int)codepoint);
                        exit(U_ILLEGAL_ARGUMENT_ERROR);
                    }
                }

                /* now set the value in the trie */
                if(!utrie_set32(sprepTrie,codepoint,trieWord)){
                    fprintf(stderr,"Could not set the value for code point.\n");
                    exit(U_ILLEGAL_ARGUMENT_ERROR);
                }

                /* written the trie word for the codepoint... increment the count*/
                writtenElementCount++;

                /* sanity check are we exceeding the max number allowed */
                if(currentIndex+value->length+1 > _SPREP_MAX_INDEX_VALUE){
                    fprintf(stderr, "Too many entries in the mapping table %i. Maximum allowed is %i\n",
                        currentIndex+value->length, _SPREP_MAX_INDEX_VALUE);
                    exit(U_INDEX_OUTOFBOUNDS_ERROR);
                }

                /* copy the mapping data */
                /* write the length */
                if(mappingLength > _SPREP_MAX_INDEX_TOP_LENGTH ){
                     /* the cast here is safe since we donot expect the length to be > 65535 */
                     mappingData[currentIndex++] = (uint16_t) mappingLength;
                }
                /* copy the contents to mappindData array */
                uprv_memmove(mappingData+currentIndex, value->mapping, value->length*U_SIZEOF_UCHAR);
                currentIndex += value->length;
                if (currentIndex > mappingDataCapacity) {
                    /* If this happens there is a bug in the computation of the mapping data size in storeMapping() */
                    fprintf(stderr, "gensprep, fatal error at %s, %d.  Aborting.\n", __FILE__, __LINE__);
                    exit(U_INTERNAL_PROGRAM_ERROR);
                }
            }
        }
        mappingLength++;
        pos = -1;
    }
    /* set the last length for range check */
    if(mappingLength <= _SPREP_MAX_INDEX_TOP_LENGTH){
        indexes[_SPREP_NORM_CORRECTNS_LAST_UNI_VERSION+mappingLength] = currentIndex+1;
    }else{
        indexes[_SPREP_FOUR_UCHARS_MAPPING_INDEX_START] = limitIndex;
    }

}

extern void setOptions(int32_t options){
    indexes[_SPREP_OPTIONS] = options;
}
extern void
storeMapping(uint32_t codepoint, uint32_t* mapping,int32_t length,
             UStringPrepType type, UErrorCode* status){

    UChar* map = NULL;
    int16_t adjustedLen=0, i, j;
    uint16_t trieWord = 0;
    ValueStruct *value = NULL;
    uint32_t savedTrieWord = 0;

    /* initialize the hashtable */
    if(hashTable==NULL){
        hashTable = uhash_open(hashEntry, compareEntries, NULL, status);
        uhash_setValueDeleter(hashTable, valueDeleter);
    }

    /* figure out if the code point has type already stored */
    savedTrieWord= utrie_get32(sprepTrie,codepoint,NULL);
    if(savedTrieWord!=0){
        if((savedTrieWord- _SPREP_TYPE_THRESHOLD) == USPREP_PROHIBITED){
            /* turn on the first bit in trie word */
            trieWord += 0x01;
        }else{
            /*
             * the codepoint has value something other than prohibited
             * and a mapping .. error!
             */
            fprintf(stderr,"Type for codepoint \\U%08X already set!.\n", (int)codepoint);
            exit(U_ILLEGAL_ARGUMENT_ERROR);
        }
    }

    /* figure out the real length */
    for(i=0; i<length; i++){
        adjustedLen += U16_LENGTH(mapping[i]);
    }

    if(adjustedLen == 0){
        trieWord = (uint16_t)(_SPREP_MAX_INDEX_VALUE << 2);
        /* make sure that the value of trieWord is less than the threshold */
        if(trieWord < _SPREP_TYPE_THRESHOLD){
            /* now set the value in the trie */
            if(!utrie_set32(sprepTrie,codepoint,trieWord)){
                fprintf(stderr,"Could not set the value for code point.\n");
                exit(U_ILLEGAL_ARGUMENT_ERROR);
            }
            /* value is set so just return */
            return;
        }else{
            fprintf(stderr,"trieWord cannot contain value greater than threshold 0x%04X.\n",_SPREP_TYPE_THRESHOLD);
            exit(U_ILLEGAL_CHAR_FOUND);
        }
    }

    if(adjustedLen == 1){
        /* calculate the delta */
        int16_t delta = (int16_t)((int32_t)codepoint - (int16_t) mapping[0]);
        if(delta >= SPREP_DELTA_RANGE_NEGATIVE_LIMIT && delta <= SPREP_DELTA_RANGE_POSITIVE_LIMIT){

            trieWord = delta << 2;

            /* make sure that the second bit is OFF */
            if((trieWord & 0x02) != 0 ){
                fprintf(stderr,"The second bit in the trie word is not zero while storing a delta.\n");
                exit(U_INTERNAL_PROGRAM_ERROR);
            }
            /* make sure that the value of trieWord is less than the threshold */
            if(trieWord < _SPREP_TYPE_THRESHOLD){
                /* now set the value in the trie */
                if(!utrie_set32(sprepTrie,codepoint,trieWord)){
                    fprintf(stderr,"Could not set the value for code point.\n");
                    exit(U_ILLEGAL_ARGUMENT_ERROR);
                }
                /* value is set so just return */
                return;
            }
        }
        /*
         * if the delta is not in the given range or if the trieWord is larger than the threshold
         * just fall through for storing the mapping in the mapping table
         */
    }

    map = (UChar*) uprv_calloc(adjustedLen + 1, U_SIZEOF_UCHAR);

    for (i=0, j=0; i<length; i++) {
        U16_APPEND_UNSAFE(map, j, mapping[i]);
    }

    value = (ValueStruct*) uprv_malloc(sizeof(ValueStruct));
    value->mapping = map;
    value->type    = type;
    value->length  = adjustedLen;
    if(value->length > _SPREP_MAX_INDEX_TOP_LENGTH){
        mappingDataCapacity++;
    }
    if(maxLength < value->length){
        maxLength = value->length;
    }
    uhash_iput(hashTable,codepoint,value,status);
    mappingDataCapacity += adjustedLen;

    if(U_FAILURE(*status)){
        fprintf(stderr, "Failed to put entries into the hastable. Error: %s\n", u_errorName(*status));
        exit(*status);
    }
}

extern void
storeRange(uint32_t start, uint32_t end, UStringPrepType type,UErrorCode* status){
    uint16_t trieWord = 0;

    if((int)(_SPREP_TYPE_THRESHOLD + type) > 0xFFFF){
        fprintf(stderr,"trieWord cannot contain value greater than 0xFFFF.\n");
        exit(U_ILLEGAL_CHAR_FOUND);
    }
    trieWord = (_SPREP_TYPE_THRESHOLD + type); /* the top 4 bits contain the value */
    if(start == end){
        uint32_t savedTrieWord = utrie_get32(sprepTrie, start, NULL);
        if(savedTrieWord>0){
            if(savedTrieWord < _SPREP_TYPE_THRESHOLD && type == USPREP_PROHIBITED){
                /*
                 * A mapping is stored in the trie word
                 * and the only other possible type that a
                 * code point can have is USPREP_PROHIBITED
                 *
                 */

                /* turn on the 0th bit in the savedTrieWord */
                savedTrieWord += 0x01;

                /* the downcast is safe since we only save 16 bit values */
                trieWord = (uint16_t)savedTrieWord;

                /* make sure that the value of trieWord is less than the threshold */
                if(trieWord < _SPREP_TYPE_THRESHOLD){
                    /* now set the value in the trie */
                    if(!utrie_set32(sprepTrie,start,trieWord)){
                        fprintf(stderr,"Could not set the value for code point.\n");
                        exit(U_ILLEGAL_ARGUMENT_ERROR);
                    }
                    /* value is set so just return */
                    return;
                }else{
                    fprintf(stderr,"trieWord cannot contain value greater than threshold 0x%04X.\n",_SPREP_TYPE_THRESHOLD);
                    exit(U_ILLEGAL_CHAR_FOUND);
                }

            }else if(savedTrieWord != trieWord){
                fprintf(stderr,"Value for codepoint \\U%08X already set!.\n", (int)start);
                exit(U_ILLEGAL_ARGUMENT_ERROR);
            }
            /* if savedTrieWord == trieWord .. fall through and set the value */
        }
        if(!utrie_set32(sprepTrie,start,trieWord)){
            fprintf(stderr,"Could not set the value for code point \\U%08X.\n", (int)start);
            exit(U_ILLEGAL_ARGUMENT_ERROR);
        }
    }else{
        if(!utrie_setRange32(sprepTrie, start, end+1, trieWord, FALSE)){
            fprintf(stderr,"Value for certain codepoint already set.\n");
            exit(U_ILLEGAL_CHAR_FOUND);
        }
    }

}

/* folding value: just store the offset (16 bits) if there is any non-0 entry */
static uint32_t U_CALLCONV
getFoldedValue(UNewTrie *trie, UChar32 start, int32_t offset) {
    uint32_t value;
    UChar32 limit=0;
    UBool inBlockZero;

    limit=start+0x400;
    while(start<limit) {
        value=utrie_get32(trie, start, &inBlockZero);
        if(inBlockZero) {
            start+=UTRIE_DATA_BLOCK_LENGTH;
        } else if(value!=0) {
            return (uint32_t)offset;
        } else {
            ++start;
        }
    }
    return 0;

}

#endif /* #if !UCONFIG_NO_IDNA */

extern void
generateData(const char *dataDir, const char* bundleName) {
    static uint8_t sprepTrieBlock[100000];

    UNewDataMemory *pData;
    UErrorCode errorCode=U_ZERO_ERROR;
    int32_t size, dataLength;
    char* fileName = (char*) uprv_malloc(uprv_strlen(bundleName) +100);

#if UCONFIG_NO_IDNA

    size=0;

#else

    int32_t sprepTrieSize;

    /* sort and add mapping data */
    storeMappingData();

    sprepTrieSize=utrie_serialize(sprepTrie, sprepTrieBlock, sizeof(sprepTrieBlock), getFoldedValue, TRUE, &errorCode);
    if(U_FAILURE(errorCode)) {
        fprintf(stderr, "error: utrie_serialize(sprep trie) failed, %s\n", u_errorName(errorCode));
        exit(errorCode);
    }

    size = sprepTrieSize + mappingDataCapacity*U_SIZEOF_UCHAR + sizeof(indexes);
    if(beVerbose) {
        printf("size of sprep trie              %5u bytes\n", (int)sprepTrieSize);
        printf("size of " U_ICUDATA_NAME "_%s." DATA_TYPE " contents: %ld bytes\n", bundleName,(long)size);
        printf("size of mapping data array %5u bytes\n",(int)mappingDataCapacity * U_SIZEOF_UCHAR);
        printf("Number of code units in mappingData (currentIndex) are: %i \n", currentIndex);
        printf("Maximum length of the mapping string is : %i \n", (int)maxLength);
    }

#endif

    fileName[0]=0;
    uprv_strcat(fileName,bundleName);
    /* write the data */
    pData=udata_create(dataDir, DATA_TYPE, fileName, &dataInfo,
                       haveCopyright ? U_COPYRIGHT_STRING : NULL, &errorCode);
    if(U_FAILURE(errorCode)) {
        fprintf(stderr, "gensprep: unable to create the output file, error %d\n", errorCode);
        exit(errorCode);
    }

#if !UCONFIG_NO_IDNA

    indexes[_SPREP_INDEX_TRIE_SIZE]=sprepTrieSize;
    indexes[_SPREP_INDEX_MAPPING_DATA_SIZE]=mappingDataCapacity*U_SIZEOF_UCHAR;

    udata_writeBlock(pData, indexes, sizeof(indexes));
    udata_writeBlock(pData, sprepTrieBlock, sprepTrieSize);
    udata_writeBlock(pData, mappingData, indexes[_SPREP_INDEX_MAPPING_DATA_SIZE]);

#endif

    /* finish up */
    dataLength=udata_finish(pData, &errorCode);
    if(U_FAILURE(errorCode)) {
        fprintf(stderr, "gensprep: error %d writing the output file\n", errorCode);
        exit(errorCode);
    }

    if(dataLength!=size) {
        fprintf(stderr, "gensprep error: data length %ld != calculated size %ld\n",
            (long)dataLength, (long)size);
        exit(U_INTERNAL_PROGRAM_ERROR);
    }

#if !UCONFIG_NO_IDNA
    /* done with writing the data .. close the hashtable */
    if (hashTable != NULL) {
        uhash_close(hashTable);
    }
#endif

    uprv_free(fileName);
}

#if !UCONFIG_NO_IDNA

extern void
cleanUpData(void) {
    uprv_free(mappingData);
    utrie_close(sprepTrie);
    uprv_free(sprepTrie);
}

#endif /* #if !UCONFIG_NO_IDNA */

/*
 * Hey, Emacs, please set the following:
 *
 * Local Variables:
 * indent-tabs-mode: nil
 * End:
 *
 */


text: A simple file uploader plugin with various configurations support upto IE 8.


text:
@class MPAlphaMaskView, NSLayoutConstraint, UIButton, UIImage, UIImageView, UILabel, UIView;

@interface MPTakeoverNotificationViewController : MPNotificationViewController
{
    struct CGPoint _viewStart;
    BOOL _touching;
    UIImage *_backgroundImage;
    UIImageView *_imageView;
    UILabel *_titleView;
    UILabel *_bodyView;
    UIButton *_okayButton;
    UIButton *_closeButton;
    MPAlphaMaskView *_imageAlphaMaskView;
    UIImageView *_backgroundImageView;
    NSLayoutConstraint *_imageWidth;
    NSLayoutConstraint *_imageHeight;
    UIView *_imageDragView;
    UIView *_bgMask;
}

- (void).cxx_destruct;
@property(retain, nonatomic) UIImage *backgroundImage; // @synthesize backgroundImage=_backgroundImage;
@property(retain, nonatomic) UIImageView *backgroundImageView; // @synthesize backgroundImageView=_backgroundImageView;
- (void)beginAppearanceTransition:(BOOL)arg1 animated:(BOOL)arg2;
@property(retain, nonatomic) UIView *bgMask; // @synthesize bgMask=_bgMask;
@property(retain, nonatomic) UILabel *bodyView; // @synthesize bodyView=_bodyView;
@property(retain, nonatomic) UIButton *closeButton; // @synthesize closeButton=_closeButton;
- (void)didPan:(id)arg1;
- (void)endAppearanceTransition;
- (void)hideWithAnimation:(BOOL)arg1 completion:(CDUnknownBlockType)arg2;
@property(retain, nonatomic) MPAlphaMaskView *imageAlphaMaskView; // @synthesize imageAlphaMaskView=_imageAlphaMaskView;
@property(retain, nonatomic) UIView *imageDragView; // @synthesize imageDragView=_imageDragView;
@property(retain, nonatomic) NSLayoutConstraint *imageHeight; // @synthesize imageHeight=_imageHeight;
@property(retain, nonatomic) UIImageView *imageView; // @synthesize imageView=_imageView;
@property(retain, nonatomic) NSLayoutConstraint *imageWidth; // @synthesize imageWidth=_imageWidth;
@property(retain, nonatomic) UIButton *okayButton; // @synthesize okayButton=_okayButton;
- (int)preferredStatusBarStyle;
- (int)preferredStatusBarUpdateAnimation;
- (void)pressedClose;
- (void)pressedOkay;
@property(retain, nonatomic) UILabel *titleView; // @synthesize titleView=_titleView;
- (unsigned int)supportedInterfaceOrientations;
- (void)viewDidLayoutSubviews;
- (void)viewDidLoad;

@end


text:
<!doctype html>

    <meta charset="utf-8">

    <meta content="IE=edge,chrome=1" http-equiv="X-UA-Compatible">
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    <title>Start a New Zend Framework 1 Project</title>

    <link href="/dashboard/stylesheets/normalize.css" rel="stylesheet" type="text/css" /><link href="/dashboard/stylesheets/all.css" rel="stylesheet" type="text/css" />
    <link href="//cdnjs.cloudflare.com/ajax/libs/font-awesome/3.1.0/css/font-awesome.min.css" rel="stylesheet" type="text/css" />

    <link href="/dashboard/images/favicon.png" rel="icon" type="image/png" />

Apache Friends

              Menu

Applications

FAQs

HOW-TO Guides

PHPInfo

phpMyAdmin

Documentation

          Download PDF
          create-framework-project-zf1.pdf

Start a New Zend Framework 1 Project

XAMPP makes it easy to start developing with PHP, and Zend Framework is one of the most popular PHP development frameworks. This guide walks you through the process of initializing a new Zend Framework 1 project with XAMPP.

This guide assumes that the new Zend Framework application will be accessible at the URL http://localhost/myapp/.

Open a new terminal and ensure you are logged in as an administrator.

Within your XAMPP installation directory (usually /Applications/XAMPP/xamppfiles/), create a new directory named apps/ (if it doesn’t already exist). Then, within this new apps/ directory, create a directory to hold your Zend Framework application and its related XAMPP configuration files. In this case, call the directory myapp/.

cd /Applications/XAMPP/xamppfiles/
mkdir apps
mkdir apps/myapp

Download the latest version of the Zend Framework 1 minimal package as a ZIP or TGZ archive.

Extract the contents of the archive to the myapp\ directory. This will produce a ZendFramework-[x.y]-minimal.zip\ subdirectory in the myapp\ directory. Rename this newly-created subdirectory to htdocs.

cd /Applications/XAMPP/xamppfiles/apps/myapp
tar -xzf /tmp/ZendFramework*.tar.gz
mv ZendFramework* htdocs

This new htdocs directory will be the main working directory for your Zend Framework project.

Next, within the myapp/ directory, create a new conf/ subdirectory.

cd /Applications/XAMPP/xamppfiles/apps/myapp
mkdir conf

Within the new conf/ subdirectory, use your text editor to create and populate a file named httpd-prefix.conf with the following content:

Alias /myapp/ "/Applications/XAMPP/xamppfiles/apps/myapp/htdocs/public/"
Alias /myapp "/Applications/XAMPP/xamppfiles/apps/myapp/htdocs/public"
Include "/Applications/XAMPP/xamppfiles/apps/myapp/conf/httpd-app.conf"

Within the conf/ subdirectory, also create and populate a file named httpd-app.conf with the following content:

<Directory /Applications/XAMPP/xamppfiles/apps/myapp/htdocs/public>
   Options +FollowSymLinks
   AllowOverride All
   Require all granted
</Directory>

Edit the httpd-xampp.conf file in the etc/extra/ subdirectory of your XAMPP installation directory and add the following line at the end to include the httpd-prefix.conf created earlier.

Include "/Applications/XAMPP/xamppfiles/apps/myapp/conf/httpd-prefix.conf"

Remember to update the above file and directory paths so that they’re valid for your system.

Change to the myapp/htdocs/ directory and run the following commands to create a new stub project.

/Applications/XAMPP/bin/php bin/zf.php create project .

Check that you have a directory structure like this:

Restart the Apache server using the XAMPP control panel.

You should be able to access the Zend Framework skeleton application by browsing to http://localhost/myapp. Here’s what the default welcome page looks like:

You can now begin developing your Zend Framework application by modifying the skeleton application code. For more information, refer to the Zend Framework documentation.

Follow us on Twitter

Like us on Facebook

Add us to your G+ Circles

Blog

Privacy Policy

                    CDN provided by

Copyright (c) 2017, Apache Friends


text:
package rocks.bottery.bot;

import java.util.List;
import java.util.Locale;

import rocks.bottery.bot.i18n.ILocalizer;
import rocks.bottery.bot.interceptors.IInterceptor;
import rocks.bottery.bot.recognizers.IRecognizer;
import rocks.bottery.messaging.IMessagingConfig;

/**
 * Bot global config and context (shared between all bots)
 *
 * @author Harald Kuhn
 */
public interface IBotConfig extends IMessagingConfig {

	/**
	 * get the active localizer
	 *
	 * @return
	 */
	ILocalizer getLocalizer();

	/**
	 * get all recognizers
	 *
	 * @return
	 */
	List<IRecognizer> getRecognizers();

	/**
	 * get the active variable resolver
	 *
	 * @return
	 */
	IVariableResolver getResolver();

	/**
	 * get the session store
	 *
	 * @return
	 */
	ISessionStore getSessionStore();

	/**
	 * get the activity archive
	 *
	 * @return
	 */
	IActivityArchive getArchive();

	/**
	 * set the localizer
	 *
	 * @param localizer
	 */
	void setLocalizer(ILocalizer localizer);

	/**
	 * set the recognizers
	 *
	 * @param recognizer
	 */
	void setRecognizers(List<IRecognizer> recognizer);

	/**
	 * set the variable resolver
	 *
	 * @param resolver
	 */
	void setResolver(IVariableResolver resolver);

	/**
	 * set the session store
	 *
	 * @param sessionStore
	 */
	void setSessionStore(ISessionStore sessionStore);

	/**
	 * set the activity archive
	 *
	 * @param archive
	 */
	void setArchive(IActivityArchive archive);
	// add dev config

	// add secruity config

	/**
	 * Get the List of in interceptors, to add an interceptor, add it to the list
	 *
	 * @return the List of in interceptors
	 */
	List<IInterceptor> getInInterceptors();

	/**
	 * Get the List of out interceptors, to add an interceptor, add it to the list
	 *
	 * @return the List of out interceptors
	 */
	List<IInterceptor> getOutInterceptors();

	Locale getDefaultLocale();

}


text:
package embedding;

import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.Point;

import java.io.*;
import java.util.*;

/**
 * Parse taxi trip files.
 *
 * There are two types of raw taxi trips.
 *      Type 1: 2013-[month]
 *      Type 2: Chicago Verifone xxxx
 */
public class TaxiTrip {
    public enum TAXITYPE { Type1, Type2, Type3 };

    public static int badTrip = 0;
    public static TAXITYPE tripFormat;
    public static final String tripFilePath = "../data/ChicagoTaxi";
    public static GeometryFactory pointsBuilder = new GeometryFactory();

    ShortDate startDate;
    ShortDate endDate;
    Point startLoc;
    Point endLoc;
    int duration;   // in seconds

    public TaxiTrip() {
        // empty
    }

    /**
     * Parse taxi trips from one input line.
     * @param line
     */
    public TaxiTrip(String line) throws Exception {
        if (tripFormat ==  TAXITYPE.Type1) {
            String[] ls = line.split("\t+");
            if (ls.length != 13) {
                badTrip ++;
                throw new Exception("Taxi trip T1 has missing information!");
            }
            this.startDate = new ShortDate(ls[7]);
            this.endDate = new ShortDate(ls[8]);
            this.startLoc = parseGPSType1(ls[9]);
            this.endLoc = parseGPSType1(ls[10]);
            this.duration = Integer.parseInt(ls[2]);
        } else if (tripFormat == TAXITYPE.Type2) {
            String[] ls = line.split("\t");
            if (ls.length != 17) {
                badTrip ++;
                throw new Exception("Taxi trip T2 has missing information!");
            }
            this.startDate = new ShortDate(ls[0], ls[1]);
            this.endDate = new ShortDate(ls[2]);
            this.startLoc = parseGPSType2(ls[9], ls[10]);
            this.endLoc = parseGPSType2(ls[11], ls[12]);
            this.duration = Integer.parseInt(ls[15]);
        } else if (tripFormat == TAXITYPE.Type3) {
            String[] ls = line.split(",");
            if (ls.length != 21) {
                badTrip ++;
                throw new Exception("Taxi trip T3 has missing information!");
            }
            String[] startDates = ls[0].split(" ", 2);
            this.startDate = new ShortDate(startDates[0], startDates[1]);
            String[] endDates = ls[1].split(" ", 2);
            this.endDate = new ShortDate(endDates[0], endDates[1]);
            this.startLoc = parseGPSType2(ls[16], ls[15]);
            this.endLoc = parseGPSType2(ls[19], ls[18]);
            this.duration = Integer.parseInt(ls[2]);
        } else {
            System.err.println("Wrong trip format is given.");
        }
    }

    /**
     * Parse the gps string in type1 taxi file.
     * @param gps GPS string has format "41.9737,-87.8681", the quotations are included.
     * @return a Point object (lon, lat)
     */
    Point parseGPSType1(String gps) {
        String g = gps.substring(1, gps.length() - 1);
        String[] gs = g.split(",");
        Coordinate coord = new Coordinate(Double.parseDouble(gs[1]), Double.parseDouble(gs[0]));
        return pointsBuilder.createPoint(coord);
    }

    Point parseGPSType2(String x, String y) {
        Coordinate coord = new Coordinate(Double.parseDouble(x), Double.parseDouble(y));
        return pointsBuilder.createPoint(coord);
    }

    public static List<TaxiTrip> parseTaxiFiles() {
        File taxiDir = new File(tripFilePath);
        List<TaxiTrip> trips = new LinkedList<>();
        long t1 = System.currentTimeMillis();

        tripFormat = TAXITYPE.Type1;
        parseTaxiFilesHelper(taxiDir, (file, s) -> s.matches("201[34]-.*"), trips);
        long t2 = System.currentTimeMillis();
        System.out.format("Parse all Type_1 taxi files finished in %d milliseconds.\n", (t2-t1));
        System.out.format("#totalTrip: %d\n#badTrip: %d\n", trips.size(), badTrip);

        tripFormat = TAXITYPE.Type2;
        parseTaxiFilesHelper(taxiDir, (file, s) -> s.startsWith("Chicago Verifone"), trips);
        long t3 = System.currentTimeMillis();
        System.out.format("Parse all Type_2 taxi files finished in %d milliseconds.\n", (t3-t2));
        System.out.format("#totalTrip: %d\n#badTrip: %d\n", trips.size(), badTrip);

        tripFormat = TAXITYPE.Type3;
        parseTaxiFilesHelper(taxiDir, (file, s) -> s.matches("201[34]\\d+\\.csv"), trips);
        long t4 = System.currentTimeMillis();
        System.out.format("Parse all Type_3 taxi files finished in %d milliseconds.\n", (t4-t3));
        System.out.format("#totalTrip: %d\n#badTrip: %d\n", trips.size(), badTrip);

        return trips;
    }

    public static void parseTaxiFilesHelper(File taxiDir, FilenameFilter flt, List<TaxiTrip> trips) {
        String[] files = taxiDir.list(flt);
        try {
            for (String fn : files) {
                BufferedReader fin = new BufferedReader(new FileReader(tripFilePath + File.separator + fn));
                String l = fin.readLine();  // header
                while ((l = fin.readLine()) != null) {
                    TaxiTrip t;
                    try {
                        t = new TaxiTrip(l);
                    } catch (Exception e) {
                        continue;
                    }
                    trips.add(t);
                }
                fin.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void splitType3TaxiFile() {
        long t1 = System.currentTimeMillis();
        System.out.println("Split type 3 taxi file by months...");
        try {
            Map<String, BufferedWriter> fouts = new HashMap<>();
            BufferedReader fin = new BufferedReader(new FileReader("../data/chicago-taxi.csv"));
            fin.readLine();
            String l;
            while ((l = fin.readLine()) != null) {
                String[] ls = l.split(",");
                String nl = String.join(",", Arrays.copyOfRange(ls, 2, ls.length));
                String[] startDate = ls[2].split("[/ :]");
                String monthKey = startDate[2] + startDate[0];  // month as yyyyMM
                if (fouts.containsKey(monthKey)) {
                    fouts.get(monthKey).write(nl + "\n");
                } else {
                    System.out.format("create file for %s\n", monthKey);
                    fouts.put(monthKey, new BufferedWriter(new FileWriter(String.format("../data/ChicagoTaxi/%s.csv", monthKey))));
                    fouts.get(monthKey).write(nl + "\n");
                }
            }
            for (BufferedWriter fo : fouts.values())
                fo.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        long t2 = System.currentTimeMillis();
        System.out.format("Split finished in %d seconds.\n", (t2-t1)/1000);
    }

    public static void main(String[] args) {
        parseTaxiFiles();
//        splitType3TaxiFile();
    }
}

class ShortDate {
    byte month;
    byte day;
    byte hour;
    byte minute;

    public ShortDate(int m, int d, int h, int min) {
        this.month = (byte) m;
        this.day = (byte) d;
        this.hour = (byte) h;
        this.minute = (byte) min;
    }

    /**
     * Parse the date in Type1 taxi data.
     * @param s datetime string, e.g. "11/30/13 20:07", "12/1/13 2:31"
     */
    public ShortDate(String s) {
        String[] fields = s.split("[/ :]");
        this.month = Byte.parseByte(fields[0]);
        this.day = Byte.parseByte(fields[1]);
        this.hour = Byte.parseByte(fields[3]);
        this.minute = Byte.parseByte(fields[4]);
    }

    /**
     * Parse the date in Type2 and Type3 taxi "STARTDATE and STATETIME"
     * @param date datetime string, e.g. "6/10/2013 0:00" or "5/6/2013", without quotations.
     * @param time time sting, e.g. "12:00:00 AM", without quotations.
     * */
    public ShortDate(String date, String time) {
        String[] dates = date.split("/");
        this.month = Byte.parseByte(dates[0]);
        this.day = Byte.parseByte(dates[1]);
        String[] times = time.split("[ :]");
        if (times[3].equals("PM")) {
            this.hour = (byte) (Byte.parseByte(times[0]) % 12 + 12);
        } else {
            this.hour = (byte) (Byte.parseByte(times[0]) % 12);
        }
        this.minute = Byte.parseByte(times[1]);
    }
}


text:
using System.Collections.Generic;
using TexasHoldEmEngine.Interfaces;

namespace TexasHoldEmEngine
{
    internal class HandNullObject : BestPossibleHand
    {
        public HandNullObject() : base(HandName.NoHand, new List<ICard>(), new List<CardValue>())
        {
        }
    }
}


text:
<?php
/**
 *
 * This file is part of the Aura project for PHP.
 *
 * @package Aura.Http
 *
 * @license http://opensource.org/licenses/bsd-license.php BSD
 *
 */
namespace Aura\Http\Exception;

use Aura\Http\Exception;

/**
 *
 * The request adapter type is unknown.
 *
 * @package Aura.Http
 *
 */
class UnknownAdapterType extends Exception
{
}


text:
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */

/**
 * Short File Description
 *
 * PHP version 5
 *
 * @category   aCategory
 * @package    aPackage
 * @subpackage aSubPackage
 * @author     anAuthor
 * @copyright  2014 a Copyright
 * @license    a License
 * @link       http://www.aLink.com
 */
namespace Blockchain\Explorer;

/**
 * Short Class Description
 *
 * PHP version 5
 *
 * @category   aCategory
 * @package    aPackage
 * @subpackage aSubPackage
 * @author     anAuthor
 * @copyright  2014 a Copyright
 * @license    a License
 * @link       http://www.aLink.com
 */
class SimpleBlock
{
    /**
     * Properties
     */
    public $height;                     // int
    public $hash;                       // string
    public $time;                       // int
    public $main_chain;                 // bool

    /**
     * Methods
     */
    public function __construct($json) {
        if(array_key_exists('height', $json))
            $this->height = $json['height'];
        if(array_key_exists('hash', $json))
            $this->hash = $json['hash'];
        if(array_key_exists('time', $json))
            $this->time = $json['time'];
        if(array_key_exists('main_chain', $json))
            $this->main_chain = $json['main_chain'];
    }
}


text:
package org.springframework.security.web.authentication.preauth.websphere;

import java.util.List;

/**
 * Provides indirection between classes using websphere and the actual container
 * interaction, allowing for easier unit testing.
 * <p>
 * Only for internal use.
 *
 * @author Luke Taylor
 * @since 3.0.0
 */
interface WASUsernameAndGroupsExtractor {

	List<String> getGroupsForCurrentUser();

	String getCurrentUserName();
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>whois-core</artifactId>
        <groupId>whois.core</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>whois-api</artifactId>

    <dependencies>
        <dependency>
            <groupId>whois.core</groupId>
            <artifactId>command-api</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
    </dependencies>
</project>


text:
Manage your work - [Demo]

Steps to install:-
1. git clone https://github.com/prasad8mhatre/kanban-board
2. npm install - download project dependency
3. nodemon - start this application on port localhost:3000
4. Create new account & start using it.
5. change your server URL in frontend app/app/app.js to http://localhost:3000/ for running it locally.
5. Run testcase:- npm test

Project structure:-
.
├── app
├── config
├── controllers
├── models
├── public
├── routes
├── test
├── uploads
└── views

1. /app/app --frontend project
2. /config - passport config
3. /controller - node.js backend controller
4. /models - mongoose model
5. /routes - express routes
6. /test - Supertest, chai, sinon test cases
7. /views - server side jade(pug) view

Special Thanks to sahat for awesome boilerplate for Node.js web applications-   [hackathon-starter]

 [Demo]: https://pure-tor-16517.herokuapp.com/
 [hackathon-starter]: https://github.com/sahat/hackathon-starter


text:
namespace rocksdb {

// A RangeDelAggregator aggregates range deletion tombstones as they are
// encountered in memtables/SST files. It provides methods that check whether a
// key is covered by range tombstones or write the relevant tombstones to a new
// SST file.
class RangeDelAggregator {
 public:
  // @param snapshots These are used to organize the tombstones into snapshot
  //    stripes, which is the seqnum range between consecutive snapshots,
  //    including the higher snapshot and excluding the lower one. Currently,
  //    this is used by ShouldDelete() to prevent deletion of keys that are
  //    covered by range tombstones in other snapshot stripes. This constructor
  //    is used for writes (flush/compaction). All DB snapshots are provided
  //    such that no keys are removed that are uncovered according to any DB
  //    snapshot.
  // Note this overload does not lazily initialize Rep.
  RangeDelAggregator(const InternalKeyComparator& icmp,
                     const std::vector<SequenceNumber>& snapshots,
                     bool collapse_deletions = true);

  // @param upper_bound Similar to snapshots above, except with a single
  //    snapshot, which allows us to store the snapshot on the stack and defer
  //    initialization of heap-allocating members (in Rep) until the first range
  //    deletion is encountered. This constructor is used in case of reads (get/
  //    iterator), for which only the user snapshot (upper_bound) is provided
  //    such that the seqnum space is divided into two stripes. Only the older
  //    stripe will be used by ShouldDelete().
  RangeDelAggregator(const InternalKeyComparator& icmp,
                     SequenceNumber upper_bound,
                     bool collapse_deletions = false);

  // We maintain position in the tombstone map across calls to ShouldDelete. The
  // caller may wish to specify a mode to optimize positioning the iterator
  // during the next call to ShouldDelete. The non-kFullScan modes are only
  // available when deletion collapsing is enabled.
  //
  // For example, if we invoke Next() on an iterator, kForwardTraversal should
  // be specified to advance one-by-one through deletions until one is found
  // with its interval containing the key. This will typically be faster than
  // doing a full binary search (kBinarySearch).
  enum RangePositioningMode {
    kFullScan,  // used iff collapse_deletions_ == false
    kForwardTraversal,
    kBackwardTraversal,
    kBinarySearch,
  };

  // Returns whether the key should be deleted, which is the case when it is
  // covered by a range tombstone residing in the same snapshot stripe.
  // @param mode If collapse_deletions_ is true, this dictates how we will find
  //             the deletion whose interval contains this key. Otherwise, its
  //             value must be kFullScan indicating linear scan from beginning..
  bool ShouldDelete(const ParsedInternalKey& parsed,
                    RangePositioningMode mode = kFullScan);
  bool ShouldDelete(const Slice& internal_key,
                    RangePositioningMode mode = kFullScan);
  bool ShouldAddTombstones(bool bottommost_level = false);

  // Adds tombstones to the tombstone aggregation structure maintained by this
  // object.
  // @return non-OK status if any of the tombstone keys are corrupted.
  Status AddTombstones(std::unique_ptr<InternalIterator> input);

  // Resets iterators maintained across calls to ShouldDelete(). This may be
  // called when the tombstones change, or the owner may call explicitly, e.g.,
  // if it's an iterator that just seeked to an arbitrary position. The effect
  // of invalidation is that the following call to ShouldDelete() will binary
  // search for its tombstone.
  void InvalidateTombstoneMapPositions();

  // Writes tombstones covering a range to a table builder.
  // @param extend_before_min_key If true, the range of tombstones to be added
  //    to the TableBuilder starts from the beginning of the key-range;
  //    otherwise, it starts from meta->smallest.
  // @param lower_bound/upper_bound Any range deletion with [start_key, end_key)
  //    that overlaps the target range [*lower_bound, *upper_bound) is added to
  //    the builder. If lower_bound is nullptr, the target range extends
  //    infinitely to the left. If upper_bound is nullptr, the target range
  //    extends infinitely to the right. If both are nullptr, the target range
  //    extends infinitely in both directions, i.e., all range deletions are
  //    added to the builder.
  // @param meta The file's metadata. We modify the begin and end keys according
  //    to the range tombstones added to this file such that the read path does
  //    not miss range tombstones that cover gaps before/after/between files in
  //    a level. lower_bound/upper_bound above constrain how far file boundaries
  //    can be extended.
  // @param bottommost_level If true, we will filter out any tombstones
  //    belonging to the oldest snapshot stripe, because all keys potentially
  //    covered by this tombstone are guaranteed to have been deleted by
  //    compaction.
  void AddToBuilder(TableBuilder* builder, const Slice* lower_bound,
                    const Slice* upper_bound, FileMetaData* meta,
                    CompactionIterationStats* range_del_out_stats = nullptr,
                    bool bottommost_level = false);
  bool IsEmpty();

 private:
  // Maps tombstone user start key -> tombstone object
  typedef std::multimap<Slice, RangeTombstone, stl_wrappers::LessOfComparator>
      TombstoneMap;
  // Also maintains position in TombstoneMap last seen by ShouldDelete(). The
  // end iterator indicates invalidation (e.g., if AddTombstones() changes the
  // underlying map). End iterator cannot be invalidated.
  struct PositionalTombstoneMap {
    explicit PositionalTombstoneMap(TombstoneMap _raw_map)
        : raw_map(std::move(_raw_map)), iter(raw_map.end()) {}
    PositionalTombstoneMap(const PositionalTombstoneMap&) = delete;
    PositionalTombstoneMap(PositionalTombstoneMap&& other)
        : raw_map(std::move(other.raw_map)), iter(raw_map.end()) {}

    TombstoneMap raw_map;
    TombstoneMap::const_iterator iter;
  };

  // Maps snapshot seqnum -> map of tombstones that fall in that stripe, i.e.,
  // their seqnums are greater than the next smaller snapshot's seqnum.
  typedef std::map<SequenceNumber, PositionalTombstoneMap> StripeMap;

  struct Rep {
    StripeMap stripe_map_;
    PinnedIteratorsManager pinned_iters_mgr_;
  };
  // Initializes rep_ lazily. This aggregator object is constructed for every
  // read, so expensive members should only be created when necessary, i.e.,
  // once the first range deletion is encountered.
  void InitRep(const std::vector<SequenceNumber>& snapshots);

  PositionalTombstoneMap& GetPositionalTombstoneMap(SequenceNumber seq);
  Status AddTombstone(RangeTombstone tombstone);

  SequenceNumber upper_bound_;
  std::unique_ptr<Rep> rep_;
  const InternalKeyComparator& icmp_;
  // collapse range deletions so they're binary searchable
  const bool collapse_deletions_;
};

}  // namespace rocksdb


text:
module TodoList
  class TaskList < Array

    SEPARATOR = " _;_ "

    def self.load(file_name)
      todolist = TaskList.new

      if File.exists?(file_name)
        File.foreach(file_name) do |line|
          description, done = line.chomp.split(SEPARATOR)

          todolist << Task.new(description, done.to_b)
        end
      end

      todolist
    end

    def save(file_name)
      File.open(file_name, "w") do |file|
        self.each { |e| file.puts("#{e.description}#{SEPARATOR}#{e.done?}") }
      end
    end

  end
end


text:
using System;

namespace Microsoft.Zelig.Test
{
    public class StringBuilderTests : TestBase, ITestInterface
    {
        [SetUp]
        public InitializeResult Initialize()
        {
            return InitializeResult.ReadyToGo;
        }

        [TearDown]
        public void CleanUp()
        {
        }

        #region Fields

        System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder();

        #endregion

        public override TestResult Run( string[] args )
        {
            TestResult result = TestResult.Pass;

            string testName = "Test_0_AppendTest_";
            result |= Assert.CheckFailed(Test_0_AppendTest_0(), testName, 0);

            testName = "Test_1_RemoveTest_";
            result |= Assert.CheckFailed(Test_1_RemoveTest_0(), testName, 0);

            testName = "Test_2_InsertTest_";
            //result |= Assert.CheckFailed(Test_2_InsertTest_0(), testName, 0); // https://github.com/NETMF/llilum/issues/109, https://github.com/NETMF/llilum/issues/108

            testName = "Test_3_ReplaceTest_";
            result |= Assert.CheckFailed(Test_3_ReplaceTest_0(), testName, 0);
            result |= Assert.CheckFailed(Test_3_ReplaceTest_1(), testName, 1);
            result |= Assert.CheckFailed(Test_3_ReplaceTest_2(), testName, 2);
            result |= Assert.CheckFailed(Test_3_ReplaceTest_3(), testName, 3);
            result |= Assert.CheckFailed(Test_3_ReplaceTest_4(), testName, 4);
            result |= Assert.CheckFailed(Test_3_ReplaceTest_5(), testName, 5);
            result |= Assert.CheckFailed(Test_3_ReplaceTest_6(), testName, 6);
            result |= Assert.CheckFailed(Test_3_ReplaceTest_7(), testName, 7);

            testName = "Test_4_CapacityTest_";
            result |= Assert.CheckFailed(Test_4_CapacityTest_0(), testName, 0);

            return result;
        }

        #region Append Tests

        [TestMethod]
        public TestResult Test_0_AppendTest_0()
        {

            bool result = false;

            stringBuilder.Append(true);

            result = stringBuilder.ToString() == Boolean.TrueString;

            if (!result)
            {
                return TestResult.Fail;
            }

            stringBuilder.Append(false);

            result = stringBuilder.ToString() == string.Concat(Boolean.TrueString, Boolean.FalseString);

            if (!result)
            {
                return TestResult.Fail;
            }

            stringBuilder.Append(byte.MinValue);

            result = stringBuilder.ToString() == string.Concat(Boolean.TrueString, Boolean.FalseString, byte.MinValue);

            if (!result)
            {
                return TestResult.Fail;
            }

            stringBuilder.Append(new char[] { 'x', 'a' });

            result = stringBuilder.ToString() == string.Concat(Boolean.TrueString, Boolean.FalseString, byte.MinValue, char.MinValue, "xa");

            if (!result)
            {
                return TestResult.Fail;
            }

            stringBuilder.Append(double.Epsilon);

            result = stringBuilder.ToString() == string.Concat(Boolean.TrueString, Boolean.FalseString, byte.MinValue, char.MinValue, "xa", double.Epsilon.ToString());

            if (!result)
            {
                return TestResult.Fail;
            }

            stringBuilder.Append(float.Epsilon);

            result = stringBuilder.ToString() == string.Concat(Boolean.TrueString, Boolean.FalseString, byte.MinValue, char.MinValue, "xa", double.Epsilon.ToString(), float.Epsilon.ToString());

            if (!result)
            {
                return TestResult.Fail;
            }

            stringBuilder.Append(int.MaxValue);

            result = stringBuilder.ToString() == string.Concat(Boolean.TrueString, Boolean.FalseString, byte.MinValue, char.MinValue, "xa", double.Epsilon.ToString(), float.Epsilon.ToString(), int.MaxValue);

            if (!result)
            {
                return TestResult.Fail;
            }

            stringBuilder.Append(long.MaxValue);

            result = stringBuilder.ToString() == string.Concat(Boolean.TrueString, Boolean.FalseString, byte.MinValue, char.MinValue, "xa", double.Epsilon.ToString(), float.Epsilon.ToString(), int.MaxValue, long.MaxValue);

            if (!result)
            {
                return TestResult.Fail;
            }

            stringBuilder.Append((object)"string");

            result = stringBuilder.ToString() == string.Concat(Boolean.TrueString, Boolean.FalseString, byte.MinValue, char.MinValue, "xa", double.Epsilon.ToString(), float.Epsilon.ToString(), int.MaxValue, long.MaxValue, "string");

            if (!result)
            {
                return TestResult.Fail;
            }

            return (result == true) ? TestResult.Pass : TestResult.Fail;
        }

        #endregion

        #region Remove Tests

        [TestMethod]
        public TestResult Test_1_RemoveTest_0()
        {

            bool result = false;

            result = stringBuilder.Clear().ToString() == string.Empty;

            if (!result)
            {
                return TestResult.Fail;
            }

            string testString = "0123456789";

            stringBuilder.Append(testString);

            stringBuilder.Remove(0, 1);

            result = stringBuilder.ToString() == "123456789";

            if (!result)
            {
                return TestResult.Fail;
            }

            stringBuilder.Remove(stringBuilder.Length - 1, 1);

            result = stringBuilder.ToString() == "12345678";

            if (!result)
            {
                return TestResult.Fail;
            }

            return (result == true) ? TestResult.Pass : TestResult.Fail;
        }

        #endregion

        #region Insert Tests

        [TestMethod]
        public TestResult Test_2_InsertTest_0()
        {
            stringBuilder.Clear();

            bool result = false;

            string testString = "0000";

            stringBuilder.Append(testString);

            stringBuilder.Insert(0, "x", 2);

            result = stringBuilder.ToString() == "xx0000";

            if (!result) return TestResult.Fail;

            stringBuilder.Insert(stringBuilder.Length, "x", 2);

            result = stringBuilder.ToString() == "xx0000xx";

            return (result == false) ? TestResult.Fail : TestResult.Pass;

        }

        #endregion

        #region Replace Tests

        [TestMethod]
        public TestResult Test_3_ReplaceTest_0()
        {

            stringBuilder.Clear();

            bool result = false;

            string testString = "0000";

            stringBuilder.Append(testString);

            stringBuilder.Append("_");

            stringBuilder.Append(testString);

            stringBuilder.Replace(testString, "xx");

            result = stringBuilder.ToString() == "xx_xx";

            return (result == false) ? TestResult.Fail : TestResult.Pass;

        }

        [TestMethod]
        public TestResult Test_3_ReplaceTest_1()
        {

            stringBuilder.Clear();

            bool result = false;

            string testString = "BEGIN";

            //stringBuilder.Append("BEGIN_MID_END");

            stringBuilder.Append('B');
            stringBuilder.Append('E');
            stringBuilder.Append('G');
            stringBuilder.Append('I');
            stringBuilder.Append('N');
            stringBuilder.Append('_');
            stringBuilder.Append('M');
            stringBuilder.Append('I');
            stringBuilder.Append('D');
            stringBuilder.Append('_');
            stringBuilder.Append('E');
            stringBuilder.Append('N');
            stringBuilder.Append('D');

            stringBuilder.Replace(testString, "xx");

            result = stringBuilder.ToString() == "xx_MID_END";

            return (result == false) ? TestResult.Fail : TestResult.Pass;

        }

        [TestMethod]
        public TestResult Test_3_ReplaceTest_2()
        {

            bool result = false;

            string testString = "MID";

            stringBuilder.Replace(testString, "xx");

            result = stringBuilder.ToString() == "xx_xx_END";

            return (result == false) ? TestResult.Fail : TestResult.Pass;

        }

        [TestMethod]
        public TestResult Test_3_ReplaceTest_3()
        {

            bool result = false;

            string testString = "END";

            stringBuilder.Replace(testString, "xx");

            result = stringBuilder.ToString() == "xx_xx_xx";

            return (result == false) ? TestResult.Fail : TestResult.Pass;

        }

        [TestMethod]
        public TestResult Test_3_ReplaceTest_4()
        {
            string testString = "The quick br!wn d#g jumps #ver the lazy cat.";
            bool result = false;
            stringBuilder = new System.Text.StringBuilder(testString);

            stringBuilder.Replace('#', '!', 15, 29);        // Some '#' -> '!'

            result = stringBuilder.ToString() == "The quick br!wn d!g jumps !ver the lazy cat.";
            if (!result) return TestResult.Fail;

            stringBuilder.Replace('!', 'o');                // All '!' -> 'o'
            result = stringBuilder.ToString() == "The quick brown dog jumps over the lazy cat.";
            if (!result) return TestResult.Fail;

            stringBuilder.Replace("cat", "dog");            // All "cat" -> "dog"
            result = stringBuilder.ToString() == "The quick brown dog jumps over the lazy dog.";
            if (!result) return TestResult.Fail;

            stringBuilder.Replace("dog", "fox", 15, 20);    // Some "dog" -> "fox"
            result = stringBuilder.ToString() == "The quick brown fox jumps over the lazy dog.";
            if (!result) return TestResult.Fail;

            return TestResult.Pass;
        }

        [TestMethod]
        public TestResult Test_3_ReplaceTest_5()
        {
            stringBuilder.Clear();

            stringBuilder.Append("12345");
            stringBuilder.Replace("45", "def");
            return stringBuilder.ToString() == "123def" ? TestResult.Pass : TestResult.Fail;
        }

        [TestMethod]
        public TestResult Test_3_ReplaceTest_6()
        {
            stringBuilder.Clear();

            stringBuilder.Append("[{1234}]Test}]");
            stringBuilder.Replace("}]", "}]example");
            return stringBuilder.ToString() == "[{1234}]exampleTest}]example" ? TestResult.Pass : TestResult.Fail;
        }

        [TestMethod]
        public TestResult Test_3_ReplaceTest_7()
        {
            var random = new Random();
            for (int i = 0; i < 1000; i++)
            {
                string sRaw, sFind, sReplace;
                GenerateFuzzyParameters(out sRaw, out sFind, out sReplace, random);

                stringBuilder.Clear();
                stringBuilder.Append(sRaw);
                stringBuilder.Replace(sFind, sReplace);
                string sMFOutput = stringBuilder.ToString();

                string sNativeOutput = NativeReplace(sRaw, sFind, sReplace);

                if (sMFOutput != sNativeOutput)
                {
                    Log.Comment("StringBuilder(\"" + sRaw + "\").Replace(\"" + sFind + "\", \"" + sReplace + "\") returns \"" + sMFOutput + "\"");
                    return TestResult.Fail;
                }
            }

            return TestResult.Pass;
        }

        void GenerateFuzzyParameters(out string sRaw, out string sFind, out string sReplace, Random random)
        {
            int cFind = random.Next(1, 4);
            sFind = RandomString(random, 2, 6);
            sReplace = RandomString(random, 4, 10);

            sRaw = string.Empty;
            for (int i = 0; i < cFind; i++)
            {
                if (i > 0 || random.Next() % 5 > 0)
                {
                    sRaw += RandomString(random, 2, 6);
                }

                sRaw += sFind;
            }

            if (random.Next() % 5 > 0)
            {
                sRaw += RandomString(random, 2, 6);
            }
        }

        string RandomString(Random random, int iLenMin, int iLenMax)
        {
            string sChars = "abcdefghijklmnopqrstuvwxyz0123456789{}[]-=+()";
            int length = random.Next(iLenMin, iLenMax);

            string sOutput = string.Empty;
            for (int i = 0; i < length; i++)
            {
                sOutput += sChars[random.Next(0, sChars.Length - 1)];
            }

            return sOutput;
        }

        string NativeReplace(string sRaw, string sFind, string sReplace)
        {
            string sOutput = sRaw;
            int i = 0;

            while (i < sOutput.Length)
            {
                int p = sOutput.IndexOf(sFind, i);
                if (p < 0)
                {
                    break;
                }

                sOutput = sOutput.Substring(0, p) + sReplace + sOutput.Substring(p + sFind.Length);
                i = p + sReplace.Length;
            }

            return sOutput;
        }

        #endregion

        #region Capacity Tests

        [TestMethod]
        public TestResult Test_4_CapacityTest_0()
        {

            stringBuilder.Length = 0;

            stringBuilder.Capacity = 5;

            bool result = false;

            result = stringBuilder.ToString() == string.Empty;

            if (!result)
            {
                return TestResult.Fail;
            }

            string testString = "0000";

            stringBuilder.Append(string.Empty);

            stringBuilder.Append(testString);

            stringBuilder.Append(string.Empty);

            //should allocate here

            stringBuilder.Append("_");
            stringBuilder.Append("_");

            //result is true if capacity is > 5

            result = stringBuilder.Capacity > 5;

            if (!result)
            {
                return TestResult.Fail;
            }

            return (result == false) ? TestResult.Fail : TestResult.Pass;

        }

        #endregion
    }

    static class RandomExtension
    {
        static public int Next(this Random random, int iMin, int iMax)
        {
            return random.Next(iMax - iMin) + iMin;
        }
    }
}


text:
package com.linecorp.armeria.common;

import static java.util.Objects.requireNonNull;

import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ScheduledExecutorService;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;

import javax.net.ssl.SSLSession;

import org.slf4j.Logger;

import com.google.errorprone.annotations.MustBeClosed;

import com.linecorp.armeria.client.ClientRequestContext;
import com.linecorp.armeria.common.annotation.Nullable;
import com.linecorp.armeria.common.annotation.UnstableApi;
import com.linecorp.armeria.common.logging.RequestLog;
import com.linecorp.armeria.common.logging.RequestLogAccess;
import com.linecorp.armeria.common.logging.RequestLogBuilder;
import com.linecorp.armeria.common.util.SafeCloseable;
import com.linecorp.armeria.common.util.Unwrappable;
import com.linecorp.armeria.internal.common.JavaVersionSpecific;
import com.linecorp.armeria.internal.common.RequestContextUtil;
import com.linecorp.armeria.server.ServiceRequestContext;

import io.micrometer.core.instrument.MeterRegistry;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.EventLoop;
import io.netty.util.AttributeKey;

/**
 * Provides information about a {@link Request}, its {@link Response} and related utilities.
 * A server-side {@link Request} has a {@link ServiceRequestContext} and
 * a client-side {@link Request} has a {@link ClientRequestContext}.
 */
public interface RequestContext extends Unwrappable {

    /**
     * Returns the context of the {@link Request} that is being handled in the current thread.
     *
     * @throws IllegalStateException if the context is unavailable in the current thread
     */
    static <T extends RequestContext> T current() {
        final T ctx = currentOrNull();
        if (ctx == null) {
            throw new IllegalStateException(RequestContext.class.getSimpleName() + " unavailable");
        }
        return ctx;
    }

    /**
     * Returns the context of the {@link Request} that is being handled in the current thread.
     *
     * @return the {@link RequestContext} available in the current thread, or {@code null} if unavailable.
     */
    @Nullable
    static <T extends RequestContext> T currentOrNull() {
        return RequestContextUtil.get();
    }

    /**
     * Returns an {@link ExecutorService} that will execute callbacks in the given {@code executor}, propagating
     * the caller's {@link RequestContext} (if any) into the callback execution.
     * If this executor service is only used from a single request then it's better to use
     * {@link #makeContextAware(ExecutorService)}
     */
    static ExecutorService makeContextPropagating(ExecutorService executor) {
        return new PropagatingContextAwareExecutorService(executor);
    }

    /**
     * Returns a {@link ScheduledExecutorService} that will execute callbacks in the given {@code executor},
     * propagating the caller's {@link RequestContext} (if any) into the callback execution.
     * If this executor service is only used from a single request then it's better to use
     * {@link #makeContextAware(ScheduledExecutorService)}
     */
    static ScheduledExecutorService makeContextPropagating(ScheduledExecutorService executor) {
        return new PropagatingContextAwareScheduledExecutorService(executor);
    }

    /**
     * Maps the context of the {@link Request} that is being handled in the current thread.
     *
     * @param mapper the {@link Function} that maps the {@link RequestContext}
     * @param defaultValueSupplier the {@link Supplier} that provides the value when the context is unavailable
     *                             in the current thread. If {@code null}, the {@code null} will be returned
     *                             when the context is unavailable in the current thread.
     */
    @Nullable
    static <T> T mapCurrent(
            Function<? super RequestContext, T> mapper,
            @Nullable Supplier<@Nullable T> defaultValueSupplier) {

        final RequestContext ctx = currentOrNull();
        if (ctx != null) {
            return mapper.apply(ctx);
        }

        if (defaultValueSupplier != null) {
            return defaultValueSupplier.get();
        }

        return null;
    }

    /**
     * Returns the root {@link ServiceRequestContext} of this context.
     *
     * @return the root {@link ServiceRequestContext}, or {@code null} if this context was not created
     *         in the context of a server request.
     */
    @Nullable
    ServiceRequestContext root();

    /**
     * Returns the value associated with the given {@link AttributeKey} or {@code null} if there's no value
     * set by {@link #setAttr(AttributeKey, Object)}.
     *
     *
Searching for attributes in a root context

     *
     *
Note: This section applies only to a {@link ClientRequestContext}. A {@link ServiceRequestContext}
     * always has itself as a {@link #root()}.

     *
     *
If the value does not exist in this context but only in {@link #root()},
     * this method will return the value from the {@link #root()}.
     *
{@code
     * ClientRequestContext ctx = ...;
     * assert ctx.root().attr(KEY).equals("root");
     * assert ctx.attr(KEY).equals("root");
     * assert ctx.ownAttr(KEY) == null;
     * }

     * If the value exists both in this context and {@link #root()},
     * this method will return the value from this context.
     *
{@code
     * ClientRequestContext ctx = ...;
     * assert ctx.root().attr(KEY).equals("root");
     * assert ctx.ownAttr(KEY).equals("child");
     * assert ctx.attr(KEY).equals("child");
     * }

     *
     * @see #ownAttr(AttributeKey)
     */
    @Nullable
    <V> V attr(AttributeKey<V> key);

    /**
     * Returns the value associated with the given {@link AttributeKey} or {@code null} if there's no value
     * set by {@link #setAttr(AttributeKey, Object)}.
     *
     *
Unlike {@link #attr(AttributeKey)}, this does not search in {@link #root()}.

     *
     * @see #attr(AttributeKey)
     */
    @Nullable
    <V> V ownAttr(AttributeKey<V> key);

    /**
     * Returns {@code true} if and only if the value associated with the specified {@link AttributeKey} is
     * not {@code null}.
     *
     * @see #hasOwnAttr(AttributeKey)
     */
    default boolean hasAttr(AttributeKey<?> key) {
        return attr(key) != null;
    }

    /**
     * Returns {@code true} if and only if the value associated with the specified {@link AttributeKey} is
     * not {@code null}.
     *
     *
Unlike {@link #hasAttr(AttributeKey)}, this does not search in {@link #root()}.

     *
     * @see #hasAttr(AttributeKey)
     */
    default boolean hasOwnAttr(AttributeKey<?> key) {
        return ownAttr(key) != null;
    }

    /**
     * Returns the {@link Iterator} of all {@link Entry}s this context contains.
     *
     *
Searching for attributes in a root context

     *
     *
Note: This section applies only to a {@link ClientRequestContext}. A {@link ServiceRequestContext}
     * always has itself as a {@link #root()}.

     *
     *
The {@link Iterator} returned by this method will also yield the {@link Entry}s from the
     * {@link #root()} except those whose {@link AttributeKey} exist already in this context, e.g.
     *
{@code
     * ClientRequestContext ctx = ...;
     * assert ctx.ownAttr(KEY_A).equals("child_a");
     * assert ctx.root().attr(KEY_A).equals("root_a");
     * assert ctx.root().attr(KEY_B).equals("root_b");
     *
     * Iterator<Entry<AttributeKey<?>, Object>> attrs = ctx.attrs();
     * assert attrs.next().getValue().equals("child_a"); // KEY_A
     * // Skip KEY_A in the root.
     * assert attrs.next().getValue().equals("root_b"); // KEY_B
     * assert attrs.hasNext() == false;
     * }

     * Please note that any changes made to the {@link Entry} returned by {@link Iterator#next()} never
     * affects the {@link Entry} owned by {@link #root()}. For example:
     *
{@code
     * ClientRequestContext ctx = ...;
     * assert ctx.root().attr(KEY).equals("root");
     * assert ctx.ownAttr(KEY) == null;
     *
     * Iterator<Entry<AttributeKey<?>, Object>> attrs = ctx.attrs();
     * Entry<AttributeKey<?>, Object> next = attrs.next();
     * assert next.getKey() == KEY;
     * // Overriding the root entry creates the client context's own entry.
     * next.setValue("child");
     * assert ctx.attr(KEY).equals("child");
     * assert ctx.ownAttr(KEY).equals("child");
     * // root attribute remains unaffected.
     * assert ctx.root().attr(KEY).equals("root");
     * }

     * If you want to change the value from the root while iterating, please call
     * {@link #attrs()} from {@link #root()}.
     *
{@code
     * ClientRequestContext ctx = ...;
     * assert ctx.root().attr(KEY).equals("root");
     * assert ctx.ownAttr(KEY) == null;
     *
     * // Call attrs() from the root to set a value directly while iterating.
     * Iterator<Entry<AttributeKey<?>, Object>> attrs = ctx.root().attrs();
     * Entry<AttributeKey<?>, Object> next = attrs.next();
     * assert next.getKey() == KEY;
     * next.setValue("another_root");
     * // The ctx does not have its own attribute.
     * assert ctx.ownAttr(KEY) == null;
     * assert ctx.attr(KEY).equals("another_root");
     * }

     *
     * @see #ownAttrs()
     */
    Iterator<Entry<AttributeKey<?>, Object>> attrs();

    /**
     * Returns the {@link Iterator} of all {@link Entry}s this context contains.
     *
     *
Unlike {@link #attrs()}, this does not iterate {@link #root()}.

     *
     * @see #attrs()
     */
    Iterator<Entry<AttributeKey<?>, Object>> ownAttrs();

    /**
     * Associates the specified value with the given {@link AttributeKey} in this context.
     * If this context previously contained a mapping for the {@link AttributeKey}, the old value is replaced
     * by the specified value. Set {@code null} not to iterate the mapping from {@link #attrs()}.
     *
     * @return the old value that has been replaced if there's a mapping for the specified key in this context
     *         or its {@link #root()}, or {@code null} otherwise.
     */
    @Nullable
    <V> V setAttr(AttributeKey<V> key, @Nullable V value);

    /**
     * Returns the {@link HttpRequest} associated with this context, or {@code null} if there's no
     * {@link HttpRequest} associated with this context yet.
     */
    @Nullable
    HttpRequest request();

    /**
     * Returns the {@link RpcRequest} associated with this context, or {@code null} if there's no
     * {@link RpcRequest} associated with this context.
     */
    @Nullable
    RpcRequest rpcRequest();

    /**
     * Replaces the {@link HttpRequest} associated with this context with the specified one.
     * This method is useful to a decorator that manipulates HTTP request headers.
     *
     *
Note that it is a bad idea to change the values of the pseudo headers ({@code ":method"},
     * {@code ":path"}, {@code ":scheme"} and {@code ":authority"}) when replacing an {@link HttpRequest},
     * because the properties of this context, such as {@link #path()}, are unaffected by such an attempt.

     *
     * @see HttpRequest#withHeaders(RequestHeaders)
     * @see HttpRequest#withHeaders(RequestHeadersBuilder)
     */
    void updateRequest(HttpRequest req);

    /**
     * Replaces the {@link RpcRequest} associated with this context with the specified one.
     * This method is useful to a decorator that manipulates an RPC call.
     */
    void updateRpcRequest(RpcRequest rpcReq);

    /**
     * Returns the {@link SessionProtocol} of the current {@link Request}.
     */
    SessionProtocol sessionProtocol();

    /**
     * Returns the remote address of this request, or {@code null} if the connection is not established yet.
     */
    @Nullable
     A remoteAddress();

    /**
     * Returns the local address of this request, or {@code null} if the connection is not established yet.
     */
    @Nullable
     A localAddress();

    /**
     * The {@link SSLSession} for this request if the connection is made over TLS, or {@code null} if
     * the connection is not established yet or the connection is not a TLS connection.
     */
    @Nullable
    SSLSession sslSession();

    /**
     * Returns the {@link RequestId} of the current {@link Request} and {@link Response} pair.
     */
    RequestId id();

    /**
     * Returns the HTTP method of the current {@link Request}.
     */
    HttpMethod method();

    /**
     * Returns the absolute path part of the current {@link Request} URI, excluding the query part,
     * as defined in RFC3986.
     */
    String path();

    /**
     * Returns the absolute path part of the current {@link Request} URI, excluding the query part,
     * decoded in UTF-8.
     */
    String decodedPath();

    /**
     * Returns the query part of the current {@link Request} URI, without the leading {@code '?'},
     * as defined in RFC3986.
     */
    @Nullable
    String query();

    /**
     * Returns the {@link RequestLogAccess} that provides the access to the {@link RequestLog}, which
     * contains the information collected while processing the current {@link Request}.
     */
    RequestLogAccess log();

    /**
     * Returns the {@link RequestLogBuilder} that collects the information about the current {@link Request}.
     */
    RequestLogBuilder logBuilder();

    /**
     * Returns the {@link MeterRegistry} that collects various stats.
     */
    MeterRegistry meterRegistry();

    /**
     * Cancels the current {@link Request} with a {@link Throwable}.
     */
    void cancel(Throwable cause);

    /**
     * Cancels the current {@link Request}.
     */
    void cancel();

    /**
     * Times out the current {@link Request}.
     */
    void timeoutNow();

    /**
     * Returns the cause of cancellation, {@code null} if the request has not been cancelled.
     */
    @Nullable
    Throwable cancellationCause();

    /**
     * Returns whether this {@link RequestContext} has been cancelled.
     */
    default boolean isCancelled() {
        return cancellationCause() != null;
    }

    /**
     * Returns whether this {@link RequestContext} has been timed-out, that is the cancellation cause is an
     * instance of {@link TimeoutException}.
     */
    default boolean isTimedOut() {
        return cancellationCause() instanceof TimeoutException;
    }

    /**
     * Returns the {@link ContextAwareEventLoop} that is handling the current {@link Request}.
     * The {@link ContextAwareEventLoop} sets this {@link RequestContext} as the current context
     * before executing any submitted tasks. If you want to use {@link EventLoop} without setting this context,
     * call {@link ContextAwareEventLoop#withoutContext()} and use the returned {@link EventLoop}.
     */
    ContextAwareEventLoop eventLoop();

    /**
     * Returns the {@link ByteBufAllocator} for this {@link RequestContext}. Any buffers created by this
     * {@link ByteBufAllocator} must be
     * reference-counted. If you don't know
     * what this means, you should probably use {@code byte[]} or {@link ByteBuffer} directly instead
     * of calling this method.
     */
    default ByteBufAllocator alloc() {
        throw new UnsupportedOperationException("No ByteBufAllocator available for this RequestContext.");
    }

    /**
     * Returns the {@link ExchangeType} that determines whether to stream an {@link HttpRequest} or
     * {@link HttpResponse}.
     */
    @UnstableApi
    ExchangeType exchangeType();

    /**
     * Pushes the specified context to the thread-local stack. To pop the context from the stack, call
     * {@link SafeCloseable#close()}, which can be done using a {@code try-with-resources} block:
     *
{@code
     * try (SafeCloseable ignored = ctx.push()) {
     *     ...
     * }
     * }

     *
     *
This method may throw an {@link IllegalStateException} according to the status of the current
     * thread-local. Please see {@link ServiceRequestContext#push()} and
     * {@link ClientRequestContext#push()} to find out the satisfying conditions.
     */
    @MustBeClosed
    SafeCloseable push();

    @Override
    default RequestContext unwrap() {
        return (RequestContext) Unwrappable.super.unwrap();
    }

    @Override
    default RequestContext unwrapAll() {
        return (RequestContext) Unwrappable.super.unwrapAll();
    }

    /**
     * Immediately run a given {@link Runnable} with this context.
     */
    default void run(Runnable runnable) {
        requireNonNull(runnable, "runnable");
        try (SafeCloseable ignored = push()) {
            runnable.run();
        }
    }

    /**
     * Immediately call a given {@link Callable} with this context.
     */
    default <T> T run(Callable<T> callable) throws Exception {
        requireNonNull(callable, "callable");
        try (SafeCloseable ignored = push()) {
            return callable.call();
        }
    }

    /**
     * Replaces the current {@link RequestContext} in the thread-local with this context without any validation.
     * This method also does not run any callbacks.
     *
     *
Note: Do not use this if you don't know what you are doing. This method does not
     * prevent the situation where a wrong {@link RequestContext} is pushed into the thread-local.
     * Use {@link #push()} instead.
     *
     * @see ClientRequestContext#push()
     * @see ServiceRequestContext#push()
     */
    @MustBeClosed
    default SafeCloseable replace() {
        final RequestContext oldCtx = RequestContextUtil.getAndSet(this);
        return () -> RequestContextUtil.pop(this, oldCtx);
    }

    /**
     * Returns an {@link Executor} that will execute callbacks in the given {@code executor}, making sure to
     * propagate the current {@link RequestContext} into the callback execution. It is generally preferred to
     * use {@link #eventLoop()} to ensure the callback stays on the same thread as well.
     */
    default Executor makeContextAware(Executor executor) {
        requireNonNull(executor, "executor");
        return runnable -> executor.execute(makeContextAware(runnable));
    }

    /**
     * Returns an {@link ExecutorService} that will execute callbacks in the given {@code executor}, making
     * sure to propagate this {@link RequestContext} into the callback execution.
     * If this executor service will be used for callbacks from several different requests, use
     * {@link #makeContextPropagating(ExecutorService)} instead.
     */
    default ExecutorService makeContextAware(ExecutorService executor) {
        return ContextAwareExecutorService.of(this, executor);
    }

    /**
     * Returns a {@link ScheduledExecutorService} that will execute callbacks in the given {@code executor},
     * making sure to propagate this {@link RequestContext} into the callback execution.
     * If this executor service will be used for callbacks from several different requests, use
     * {@link #makeContextPropagating(ScheduledExecutorService)} instead.
     */
    default ScheduledExecutorService makeContextAware(ScheduledExecutorService executor) {
        return ContextAwareScheduledExecutorService.of(this, executor);
    }

    /**
     * Returns a {@link Callable} that makes sure the current {@link RequestContext} is set and then invokes
     * the input {@code callable}.
     */
    default <T> Callable<T> makeContextAware(Callable<T> callable) {
        requireNonNull(callable, "callable");
        return () -> {
            try (SafeCloseable ignored = push()) {
                return callable.call();
            }
        };
    }

    /**
     * Returns a {@link Runnable} that makes sure the current {@link RequestContext} is set and then invokes
     * the input {@code runnable}.
     */
    default Runnable makeContextAware(Runnable runnable) {
        requireNonNull(runnable, "runnable");
        return () -> {
            try (SafeCloseable ignored = push()) {
                runnable.run();
            }
        };
    }

    /**
     * Returns a {@link Function} that makes sure the current {@link RequestContext} is set and then invokes
     * the input {@code function}.
     */
    default <T, R> Function<T, R> makeContextAware(Function<T, R> function) {
        requireNonNull(function, "function");
        return t -> {
            try (SafeCloseable ignored = push()) {
                return function.apply(t);
            }
        };
    }

    /**
     * Returns a {@link BiFunction} that makes sure the current {@link RequestContext} is set and then invokes
     * the input {@code function}.
     */
    default <T, U, V> BiFunction<T, U, V> makeContextAware(BiFunction<T, U, V> function) {
        requireNonNull(function, "function");
        return (t, u) -> {
            try (SafeCloseable ignored = push()) {
                return function.apply(t, u);
            }
        };
    }

    /**
     * Returns a {@link Consumer} that makes sure the current {@link RequestContext} is set and then invokes
     * the input {@code action}.
     */
    default <T> Consumer<T> makeContextAware(Consumer<T> action) {
        requireNonNull(action, "action");
        return t -> {
            try (SafeCloseable ignored = push()) {
                action.accept(t);
            }
        };
    }

    /**
     * Returns a {@link BiConsumer} that makes sure the current {@link RequestContext} is set and then invokes
     * the input {@code action}.
     */
    default <T, U> BiConsumer<T, U> makeContextAware(BiConsumer<T, U> action) {
        requireNonNull(action, "action");
        return (t, u) -> {
            try (SafeCloseable ignored = push()) {
                action.accept(t, u);
            }
        };
    }

    /**
     * Returns a {@link CompletionStage} that makes sure the current {@link RequestContext} is set and
     * then invokes the input {@code stage}.
     */
    default <T> CompletionStage<T> makeContextAware(CompletionStage<T> stage) {
        requireNonNull(stage, "stage");
        if (stage instanceof ContextHolder) {
            final RequestContext context = ((ContextHolder) stage).context();
            if (this == context) {
                return stage;
            }
            if (root() != context.root()) {
                throw new IllegalArgumentException(
                        "cannot create a context aware future using " + stage);
            }
        }
        final CompletableFuture<T> future = JavaVersionSpecific.get().newContextAwareFuture(this);
        stage.handle((result, cause) -> {
            try (SafeCloseable ignored = push()) {
                if (cause != null) {
                    future.completeExceptionally(cause);
                } else {
                    future.complete(result);
                }
            } catch (Throwable t) {
                future.completeExceptionally(t);
            }
            return null;
        });
        return future;
    }

    /**
     * Returns a {@link CompletableFuture} that makes sure the current {@link RequestContext} is set and
     * then invokes the input {@code future}.
     */
    default <T> CompletableFuture<T> makeContextAware(CompletableFuture<T> future) {
        requireNonNull(future, "future");
        return makeContextAware((CompletionStage<T>) future).toCompletableFuture();
    }

    /**
     * Returns a {@link Logger} which prepends this {@link RequestContext} to the log message.
     *
     * @param logger the {@link Logger} to decorate.
     */
    default Logger makeContextAware(Logger logger) {
        return ContextAwareLogger.of(this, logger);
    }
}


text:
'use strict'
const path = require('path')
const falafel = require('falafel')
const pathExists = require('path-exists')
const detectConflict = require('detect-conflict')
const Conflicter = require('yeoman-generator/lib/util/conflicter')

const Util = module.exports = {

  /**
   * Monkey-patch to support index.js file updating without confirmation
   */
  patchConflicter () {
    Conflicter.prototype.collision = function (file, cb) {
      const rfilepath = path.relative(process.cwd(), file.path)
      if (!pathExists.sync(file.path)) {
        this.adapter.log.create(rfilepath)
        cb('create')
        return
      }
      else if (/index.js$/.test(file.path)) {
        this.adapter.log.force(rfilepath)
        cb('force')
        return
      }

      if (this.force) {
        this.adapter.log.force(rfilepath)
        cb('force')
        return
      }
      if (detectConflict(file.path, file.contents)) {
        this.adapter.log.conflict(rfilepath)
        this._ask(file, cb)
      }
      else {
        this.adapter.log.identical(rfilepath)
        cb('identical')
      }
    }
  },

  isRequire (node) {
    return node.type === 'CallExpression' &&
      node.callee.type === 'Identifier' &&
      node.callee.name === 'require'
  },

  hasRequireStatement (fileName, fileContents) {
    let exists = false

    falafel(fileContents, node => {
      if (Util.isRequire(node)) {
        if (node.arguments[0].value == `./${fileName}`) {
          exists = true
        }
      }
    })

    return exists
  },

  getRequireStatement (fileName) {
    return `exports.${fileName} = require('./${fileName}')\n`
  },

  getUpdatedIndexFile (fileName, fileContents) {
    const requireStatement = Util.getRequireStatement(fileName)
    const newFileContents = falafel(fileContents, node => {
      const src = node.source()
      if (node.type === 'Program' && !node.parent) {
        if (!src) {
          node.update(requireStatement)
        }
        else {
          node.update(src + requireStatement)
        }
      }
    })

    return newFileContents.toString()
  }
}


text:
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2016. All Rights Reserved.                             */
/* Open Source Software - may be modified and shared by FRC teams. The code   */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project.                                                               */
/*----------------------------------------------------------------------------*/

#include "HAL/cpp/priority_mutex.h"

void priority_recursive_mutex::lock() {
  pthread_mutex_lock(&m_mutex);
}

void priority_recursive_mutex::unlock() {
  pthread_mutex_unlock(&m_mutex);
}

bool priority_recursive_mutex::try_lock() noexcept {
  return !pthread_mutex_trylock(&m_mutex);
}

pthread_mutex_t* priority_recursive_mutex::native_handle() {
  return &m_mutex;
}

void priority_mutex::lock() {
  pthread_mutex_lock(&m_mutex);
}

void priority_mutex::unlock() {
  pthread_mutex_unlock(&m_mutex);
}

bool priority_mutex::try_lock() noexcept {
  return !pthread_mutex_trylock(&m_mutex);
}

pthread_mutex_t* priority_mutex::native_handle() {
  return &m_mutex;
}