text:
static const int host_bigendian = 0;

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef _WIN32
    #include "stdint_win.h"
#else
    #include <stdint.h>
#endif

#include "alac.h"

#define _Swap32(v) do { \
                   v = (((v) & 0x000000FF) << 0x18) | \
                       (((v) & 0x0000FF00) << 0x08) | \
                       (((v) & 0x00FF0000) >> 0x08) | \
                       (((v) & 0xFF000000) >> 0x18); } while(0)

#define _Swap16(v) do { \
                   v = (((v) & 0x00FF) << 0x08) | \
                       (((v) & 0xFF00) >> 0x08); } while (0)

struct {signed int x:24;} se_struct_24;
#define SignExtend24(val) (se_struct_24.x = val)

void allocate_buffers(alac_file *alac)
{
    alac->predicterror_buffer_a = malloc(alac->setinfo_max_samples_per_frame * 4);
    alac->predicterror_buffer_b = malloc(alac->setinfo_max_samples_per_frame * 4);

    alac->outputsamples_buffer_a = malloc(alac->setinfo_max_samples_per_frame * 4);
    alac->outputsamples_buffer_b = malloc(alac->setinfo_max_samples_per_frame * 4);

    alac->uncompressed_bytes_buffer_a = malloc(alac->setinfo_max_samples_per_frame * 4);
    alac->uncompressed_bytes_buffer_b = malloc(alac->setinfo_max_samples_per_frame * 4);
}

void deallocate_buffers(alac_file *alac)
{
    free(alac->predicterror_buffer_a);
    free(alac->predicterror_buffer_b);

    free(alac->outputsamples_buffer_a);
    free(alac->outputsamples_buffer_b);

    free(alac->uncompressed_bytes_buffer_a);
    free(alac->uncompressed_bytes_buffer_b);
}

void alac_set_info(alac_file *alac, char *inputbuffer)
{
  char *ptr = inputbuffer;
  ptr += 4; /* size */
  ptr += 4; /* frma */
  ptr += 4; /* alac */
  ptr += 4; /* size */
  ptr += 4; /* alac */

  ptr += 4; /* 0 ? */

  alac->setinfo_max_samples_per_frame = *(uint32_t*)ptr; /* buffer size / 2 ? */
  if (!host_bigendian)
      _Swap32(alac->setinfo_max_samples_per_frame);
  ptr += 4;
  alac->setinfo_7a = *(uint8_t*)ptr;
  ptr += 1;
  alac->setinfo_sample_size = *(uint8_t*)ptr;
  ptr += 1;
  alac->setinfo_rice_historymult = *(uint8_t*)ptr;
  ptr += 1;
  alac->setinfo_rice_initialhistory = *(uint8_t*)ptr;
  ptr += 1;
  alac->setinfo_rice_kmodifier = *(uint8_t*)ptr;
  ptr += 1;
  alac->setinfo_7f = *(uint8_t*)ptr;
  ptr += 1;
  alac->setinfo_80 = *(uint16_t*)ptr;
  if (!host_bigendian)
      _Swap16(alac->setinfo_80);
  ptr += 2;
  alac->setinfo_82 = *(uint32_t*)ptr;
  if (!host_bigendian)
      _Swap32(alac->setinfo_82);
  ptr += 4;
  alac->setinfo_86 = *(uint32_t*)ptr;
  if (!host_bigendian)
      _Swap32(alac->setinfo_86);
  ptr += 4;
  alac->setinfo_8a_rate = *(uint32_t*)ptr;
  if (!host_bigendian)
      _Swap32(alac->setinfo_8a_rate);
  ptr += 4;

  allocate_buffers(alac);

}

/* stream reading */

/* supports reading 1 to 16 bits, in big endian format */
static uint32_t readbits_16(alac_file *alac, int bits)
{
    uint32_t result;
    int new_accumulator;

    result = (alac->input_buffer[0] << 16) |
             (alac->input_buffer[1] << 8) |
             (alac->input_buffer[2]);

    /* shift left by the number of bits we've already read,
     * so that the top 'n' bits of the 24 bits we read will
     * be the return bits */
    result = result << alac->input_buffer_bitaccumulator;

    result = result & 0x00ffffff;

    /* and then only want the top 'n' bits from that, where
     * n is 'bits' */
    result = result >> (24 - bits);

    new_accumulator = (alac->input_buffer_bitaccumulator + bits);

    /* increase the buffer pointer if we've read over n bytes. */
    alac->input_buffer += (new_accumulator >> 3);

    /* and the remainder goes back into the bit accumulator */
    alac->input_buffer_bitaccumulator = (new_accumulator & 7);

    return result;
}

/* supports reading 1 to 32 bits, in big endian format */
static uint32_t readbits(alac_file *alac, int bits)
{
    int32_t result = 0;

    if (bits > 16)
    {
        bits -= 16;
        result = readbits_16(alac, 16) << bits;
    }

    result |= readbits_16(alac, bits);

    return result;
}

/* reads a single bit */
static int readbit(alac_file *alac)
{
    int result;
    int new_accumulator;

    result = alac->input_buffer[0];

    result = result << alac->input_buffer_bitaccumulator;

    result = result >> 7 & 1;

    new_accumulator = (alac->input_buffer_bitaccumulator + 1);

    alac->input_buffer += (new_accumulator / 8);

    alac->input_buffer_bitaccumulator = (new_accumulator % 8);

    return result;
}

static void unreadbits(alac_file *alac, int bits)
{
    int new_accumulator = (alac->input_buffer_bitaccumulator - bits);

    alac->input_buffer += (new_accumulator >> 3);

    alac->input_buffer_bitaccumulator = (new_accumulator & 7);
    if (alac->input_buffer_bitaccumulator < 0)
        alac->input_buffer_bitaccumulator *= -1;
}

/* various implementations of count_leading_zero:
 * the first one is the original one, the simplest and most
 * obvious for what it's doing. never use this.
 * then there are the asm ones. fill in as necessary
 * and finally an unrolled and optimised c version
 * to fall back to
 */
#if 0
/* hideously inefficient. could use a bitmask search,
 * alternatively bsr on x86,
 */
static int count_leading_zeros(int32_t input)
{
    int i = 0;
    while (!(0x80000000 & input) && i < 32)
    {
        i++;
        input = input << 1;
    }
    return i;
}
#elif defined(__GNUC__)
/* for some reason the unrolled version (below) is
 * actually faster than this. yay intel!
 */
static int count_leading_zeros(int input)
{
    return __builtin_clz(input);
}
#elif defined(_MSC_VER) && defined(_M_IX86)
static int count_leading_zeros(int input)
{
    int output = 0;
    if (!input) return 32;
    __asm
    {
        mov eax, input;
        mov edx, 0x1f;
        bsr ecx, eax;
        sub edx, ecx;
        mov output, edx;
    }
    return output;
}
#else
#warning using generic count leading zeroes. You may wish to write one for your CPU / compiler
static int count_leading_zeros(int input)
{
    int output = 0;
    int curbyte = 0;

    curbyte = input >> 24;
    if (curbyte) goto found;
    output += 8;

    curbyte = input >> 16;
    if (curbyte & 0xff) goto found;
    output += 8;

    curbyte = input >> 8;
    if (curbyte & 0xff) goto found;
    output += 8;

    curbyte = input;
    if (curbyte & 0xff) goto found;
    output += 8;

    return output;

found:
    if (!(curbyte & 0xf0))
    {
        output += 4;
    }
    else
        curbyte >>= 4;

    if (curbyte & 0x8)
        return output;
    if (curbyte & 0x4)
        return output + 1;
    if (curbyte & 0x2)
        return output + 2;
    if (curbyte & 0x1)
        return output + 3;

    /* shouldn't get here: */
    return output + 4;
}
#endif

#define RICE_THRESHOLD 8 // maximum number of bits for a rice prefix.

int32_t entropy_decode_value(alac_file* alac,
                             int readSampleSize,
                             int k,
                             int rice_kmodifier_mask)
{
    int32_t x = 0; // decoded value

    // read x, number of 1s before 0 represent the rice value.
    while (x <= RICE_THRESHOLD && readbit(alac))
    {
        x++;
    }

    if (x > RICE_THRESHOLD)
    {
        // read the number from the bit stream (raw value)
        int32_t value;

        value = readbits(alac, readSampleSize);

        // mask value
        value &= (((uint32_t)0xffffffff) >> (32 - readSampleSize));

        x = value;
    }
    else
    {
        if (k != 1)
        {
            int extraBits = readbits(alac, k);

            // x = x * (2^k - 1)
            x *= (((1 << k) - 1) & rice_kmodifier_mask);

            if (extraBits > 1)
                x += extraBits - 1;
            else
                unreadbits(alac, 1);
        }
    }

    return x;
}

void entropy_rice_decode(alac_file* alac,
                         int32_t* outputBuffer,
                         int outputSize,
                         int readSampleSize,
                         int rice_initialhistory,
                         int rice_kmodifier,
                         int rice_historymult,
                         int rice_kmodifier_mask)
{
    int             outputCount;
    int             history = rice_initialhistory;
    int             signModifier = 0;

    for (outputCount = 0; outputCount < outputSize; outputCount++)
    {
        int32_t     decodedValue;
        int32_t     finalValue;
        int32_t     k;

        k = 31 - rice_kmodifier - count_leading_zeros((history >> 9) + 3);

        if (k < 0) k += rice_kmodifier;
        else k = rice_kmodifier;

        // note: don't use rice_kmodifier_mask here (set mask to 0xFFFFFFFF)
        decodedValue = entropy_decode_value(alac, readSampleSize, k, 0xFFFFFFFF);

        decodedValue += signModifier;
        finalValue = (decodedValue + 1) / 2; // inc by 1 and shift out sign bit
        if (decodedValue & 1) // the sign is stored in the low bit
            finalValue *= -1;

        outputBuffer[outputCount] = finalValue;

        signModifier = 0;

        // update history
        history += (decodedValue * rice_historymult)
                - ((history * rice_historymult) >> 9);

        if (decodedValue > 0xFFFF)
            history = 0xFFFF;

        // special case, for compressed blocks of 0
        if ((history < 128) && (outputCount + 1 < outputSize))
        {
            int32_t     blockSize;

            signModifier = 1;

            k = count_leading_zeros(history) + ((history + 16) / 64) - 24;

            // note: blockSize is always 16bit
            blockSize = entropy_decode_value(alac, 16, k, rice_kmodifier_mask);

            // got blockSize 0s
            if (blockSize > 0)
            {
                memset(&outputBuffer[outputCount + 1], 0, blockSize * sizeof(*outputBuffer));
                outputCount += blockSize;
            }

            if (blockSize > 0xFFFF)
                signModifier = 0;

            history = 0;
        }
    }
}

#define SIGN_EXTENDED32(val, bits) ((val << (32 - bits)) >> (32 - bits))

#define SIGN_ONLY(v) \
                     ((v < 0) ? (-1) : \
                                ((v > 0) ? (1) : \
                                           (0)))

static void predictor_decompress_fir_adapt(int32_t *error_buffer,
                                           int32_t *buffer_out,
                                           int output_size,
                                           int readsamplesize,
                                           int16_t *predictor_coef_table,
                                           int predictor_coef_num,
                                           int predictor_quantitization)
{
    int i;

    /* first sample always copies */
    *buffer_out = *error_buffer;

    if (!predictor_coef_num)
    {
        if (output_size <= 1) return;
        memcpy(buffer_out+1, error_buffer+1, (output_size-1) * 4);
        return;
    }

    if (predictor_coef_num == 0x1f) /* 11111 - max value of predictor_coef_num */
    { /* second-best case scenario for fir decompression,
       * error describes a small difference from the previous sample only
       */
        if (output_size <= 1) return;
        for (i = 0; i < output_size - 1; i++)
        {
            int32_t prev_value;
            int32_t error_value;

            prev_value = buffer_out[i];
            error_value = error_buffer[i+1];
            buffer_out[i+1] = SIGN_EXTENDED32((prev_value + error_value), readsamplesize);
        }
        return;
    }

    /* read warm-up samples */
    if (predictor_coef_num > 0)
    {
        int i;
        for (i = 0; i < predictor_coef_num; i++)
        {
            int32_t val;

            val = buffer_out[i] + error_buffer[i+1];

            val = SIGN_EXTENDED32(val, readsamplesize);

            buffer_out[i+1] = val;
        }
    }

#if 0
    /* 4 and 8 are very common cases (the only ones i've seen). these
     * should be unrolled and optimised
     */
    if (predictor_coef_num == 4)
    {
        /* FIXME: optimised general case */
        return;
    }

    if (predictor_coef_table == 8)
    {
        /* FIXME: optimised general case */
        return;
    }
#endif

    /* general case */
    if (predictor_coef_num > 0)
    {
        for (i = predictor_coef_num + 1;
             i < output_size;
             i++)
        {
            int j;
            int sum = 0;
            int outval;
            int error_val = error_buffer[i];

            for (j = 0; j < predictor_coef_num; j++)
            {
                sum += (buffer_out[predictor_coef_num-j] - buffer_out[0]) *
                       predictor_coef_table[j];
            }

            outval = (1 << (predictor_quantitization-1)) + sum;
            outval = outval >> predictor_quantitization;
            outval = outval + buffer_out[0] + error_val;
            outval = SIGN_EXTENDED32(outval, readsamplesize);

            buffer_out[predictor_coef_num+1] = outval;

            if (error_val > 0)
            {
                int predictor_num = predictor_coef_num - 1;

                while (predictor_num >= 0 && error_val > 0)
                {
                    int val = buffer_out[0] - buffer_out[predictor_coef_num - predictor_num];
                    int sign = SIGN_ONLY(val);

                    predictor_coef_table[predictor_num] -= sign;

                    val *= sign; /* absolute value */

                    error_val -= ((val >> predictor_quantitization) *
                                  (predictor_coef_num - predictor_num));

                    predictor_num--;
                }
            }
            else if (error_val < 0)
            {
                int predictor_num = predictor_coef_num - 1;

                while (predictor_num >= 0 && error_val < 0)
                {
                    int val = buffer_out[0] - buffer_out[predictor_coef_num - predictor_num];
                    int sign = - SIGN_ONLY(val);

                    predictor_coef_table[predictor_num] -= sign;

                    val *= sign; /* neg value */

                    error_val -= ((val >> predictor_quantitization) *
                                  (predictor_coef_num - predictor_num));

                    predictor_num--;
                }
            }

            buffer_out++;
        }
    }
}

void deinterlace_16(int32_t *buffer_a, int32_t *buffer_b,
                    int16_t *buffer_out,
                    int numchannels, int numsamples,
                    uint8_t interlacing_shift,
                    uint8_t interlacing_leftweight)
{
    int i;
    if (numsamples <= 0) return;

    /* weighted interlacing */
    if (interlacing_leftweight)
    {
        for (i = 0; i < numsamples; i++)
        {
            int32_t difference, midright;
            int16_t left;
            int16_t right;

            midright = buffer_a[i];
            difference = buffer_b[i];

            right = midright - ((difference * interlacing_leftweight) >> interlacing_shift);
            left = right + difference;

            /* output is always little endian */
            if (host_bigendian)
            {
                _Swap16(left);
                _Swap16(right);
            }

            buffer_out[i*numchannels] = left;
            buffer_out[i*numchannels + 1] = right;
        }

        return;
    }

    /* otherwise basic interlacing took place */
    for (i = 0; i < numsamples; i++)
    {
        int16_t left, right;

        left = buffer_a[i];
        right = buffer_b[i];

        /* output is always little endian */
        if (host_bigendian)
        {
            _Swap16(left);
            _Swap16(right);
        }

        buffer_out[i*numchannels] = left;
        buffer_out[i*numchannels + 1] = right;
    }
}

void deinterlace_24(int32_t *buffer_a, int32_t *buffer_b,
                    int uncompressed_bytes,
                    int32_t *uncompressed_bytes_buffer_a, int32_t *uncompressed_bytes_buffer_b,
                    void *buffer_out,
                    int numchannels, int numsamples,
                    uint8_t interlacing_shift,
                    uint8_t interlacing_leftweight)
{
    int i;
    if (numsamples <= 0) return;

    /* weighted interlacing */
    if (interlacing_leftweight)
    {
        for (i = 0; i < numsamples; i++)
        {
            int32_t difference, midright;
            int32_t left;
            int32_t right;

            midright = buffer_a[i];
            difference = buffer_b[i];

            right = midright - ((difference * interlacing_leftweight) >> interlacing_shift);
            left = right + difference;

            if (uncompressed_bytes)
            {
                uint32_t mask = ~(0xFFFFFFFF << (uncompressed_bytes * 8));
                left <<= (uncompressed_bytes * 8);
                right <<= (uncompressed_bytes * 8);

                left |= uncompressed_bytes_buffer_a[i] & mask;
                right |= uncompressed_bytes_buffer_b[i] & mask;
            }

            ((uint8_t*)buffer_out)[i * numchannels * 3] = (left) & 0xFF;
            ((uint8_t*)buffer_out)[i * numchannels * 3 + 1] = (left >> 8) & 0xFF;
            ((uint8_t*)buffer_out)[i * numchannels * 3 + 2] = (left >> 16) & 0xFF;

            ((uint8_t*)buffer_out)[i * numchannels * 3 + 3] = (right) & 0xFF;
            ((uint8_t*)buffer_out)[i * numchannels * 3 + 4] = (right >> 8) & 0xFF;
            ((uint8_t*)buffer_out)[i * numchannels * 3 + 5] = (right >> 16) & 0xFF;
        }

        return;
    }

    /* otherwise basic interlacing took place */
    for (i = 0; i < numsamples; i++)
    {
        int32_t left, right;

        left = buffer_a[i];
        right = buffer_b[i];

        if (uncompressed_bytes)
        {
            uint32_t mask = ~(0xFFFFFFFF << (uncompressed_bytes * 8));
            left <<= (uncompressed_bytes * 8);
            right <<= (uncompressed_bytes * 8);

            left |= uncompressed_bytes_buffer_a[i] & mask;
            right |= uncompressed_bytes_buffer_b[i] & mask;
        }

        ((uint8_t*)buffer_out)[i * numchannels * 3] = (left) & 0xFF;
        ((uint8_t*)buffer_out)[i * numchannels * 3 + 1] = (left >> 8) & 0xFF;
        ((uint8_t*)buffer_out)[i * numchannels * 3 + 2] = (left >> 16) & 0xFF;

        ((uint8_t*)buffer_out)[i * numchannels * 3 + 3] = (right) & 0xFF;
        ((uint8_t*)buffer_out)[i * numchannels * 3 + 4] = (right >> 8) & 0xFF;
        ((uint8_t*)buffer_out)[i * numchannels * 3 + 5] = (right >> 16) & 0xFF;

    }

}

void decode_frame(alac_file *alac,
                  unsigned char *inbuffer,
                  void *outbuffer, int *outputsize)
{
    int channels;
    int32_t outputsamples = alac->setinfo_max_samples_per_frame;

    /* setup the stream */
    alac->input_buffer = inbuffer;
    alac->input_buffer_bitaccumulator = 0;

    channels = readbits(alac, 3);

    *outputsize = outputsamples * alac->bytespersample;

    switch(channels)
    {
    case 0: /* 1 channel */
    {
        int hassize;
        int isnotcompressed;
        int readsamplesize;

        int uncompressed_bytes;
        int ricemodifier;

        /* 2^result = something to do with output waiting.
         * perhaps matters if we read > 1 frame in a pass?
         */
        readbits(alac, 4);

        readbits(alac, 12); /* unknown, skip 12 bits */

        hassize = readbits(alac, 1); /* the output sample size is stored soon */

        uncompressed_bytes = readbits(alac, 2); /* number of bytes in the (compressed) stream that are not compressed */

        isnotcompressed = readbits(alac, 1); /* whether the frame is compressed */

        if (hassize)
        {
            /* now read the number of samples,
             * as a 32bit integer */
            outputsamples = readbits(alac, 32);
            *outputsize = outputsamples * alac->bytespersample;
        }

        readsamplesize = alac->setinfo_sample_size - (uncompressed_bytes * 8);

        if (!isnotcompressed)
        { /* so it is compressed */
            int16_t predictor_coef_table[32];
            int predictor_coef_num;
            int prediction_type;
            int prediction_quantitization;
            int i;

            /* skip 16 bits, not sure what they are. seem to be used in
             * two channel case */
            readbits(alac, 8);
            readbits(alac, 8);

            prediction_type = readbits(alac, 4);
            prediction_quantitization = readbits(alac, 4);

            ricemodifier = readbits(alac, 3);
            predictor_coef_num = readbits(alac, 5);

            /* read the predictor table */
            for (i = 0; i < predictor_coef_num; i++)
            {
                predictor_coef_table[i] = (int16_t)readbits(alac, 16);
            }

            if (uncompressed_bytes)
            {
                int i;
                for (i = 0; i < outputsamples; i++)
                {
                    alac->uncompressed_bytes_buffer_a[i] = readbits(alac, uncompressed_bytes * 8);
                }
            }

            entropy_rice_decode(alac,
                                alac->predicterror_buffer_a,
                                outputsamples,
                                readsamplesize,
                                alac->setinfo_rice_initialhistory,
                                alac->setinfo_rice_kmodifier,
                                ricemodifier * alac->setinfo_rice_historymult / 4,
                                (1 << alac->setinfo_rice_kmodifier) - 1);

            if (prediction_type == 0)
            { /* adaptive fir */
                predictor_decompress_fir_adapt(alac->predicterror_buffer_a,
                                               alac->outputsamples_buffer_a,
                                               outputsamples,
                                               readsamplesize,
                                               predictor_coef_table,
                                               predictor_coef_num,
                                               prediction_quantitization);
            }
            else
            {
                xprintf("FIXME: unhandled predicition type: %i\n", prediction_type);
                /* i think the only other prediction type (or perhaps this is just a
                 * boolean?) runs adaptive fir twice.. like:
                 * predictor_decompress_fir_adapt(predictor_error, tempout, ...)
                 * predictor_decompress_fir_adapt(predictor_error, outputsamples ...)
                 * little strange..
                 */
            }

        }
        else
        { /* not compressed, easy case */
            if (alac->setinfo_sample_size <= 16)
            {
                int i;
                for (i = 0; i < outputsamples; i++)
                {
                    int32_t audiobits = readbits(alac, alac->setinfo_sample_size);

                    audiobits = SIGN_EXTENDED32(audiobits, alac->setinfo_sample_size);

                    alac->outputsamples_buffer_a[i] = audiobits;
                }
            }
            else
            {
                int i;
                for (i = 0; i < outputsamples; i++)
                {
                    int32_t audiobits;

                    audiobits = readbits(alac, 16);
                    /* special case of sign extension..
                     * as we'll be ORing the low 16bits into this */
                    audiobits = audiobits << (alac->setinfo_sample_size - 16);
                    audiobits |= readbits(alac, alac->setinfo_sample_size - 16);
                    audiobits = SignExtend24(audiobits);

                    alac->outputsamples_buffer_a[i] = audiobits;
                }
            }
            uncompressed_bytes = 0; // always 0 for uncompressed
        }

        switch(alac->setinfo_sample_size)
        {
        case 16:
        {
            int i;
            for (i = 0; i < outputsamples; i++)
            {
                int16_t sample = alac->outputsamples_buffer_a[i];
                if (host_bigendian)
                    _Swap16(sample);
                ((int16_t*)outbuffer)[i * alac->numchannels] = sample;
            }
            break;
        }
        case 24:
        {
            int i;
            for (i = 0; i < outputsamples; i++)
            {
                int32_t sample = alac->outputsamples_buffer_a[i];

                if (uncompressed_bytes)
                {
                    uint32_t mask;
                    sample = sample << (uncompressed_bytes * 8);
                    mask = ~(0xFFFFFFFF << (uncompressed_bytes * 8));
                    sample |= alac->uncompressed_bytes_buffer_a[i] & mask;
                }

                ((uint8_t*)outbuffer)[i * alac->numchannels * 3] = (sample) & 0xFF;
                ((uint8_t*)outbuffer)[i * alac->numchannels * 3 + 1] = (sample >> 8) & 0xFF;
                ((uint8_t*)outbuffer)[i * alac->numchannels * 3 + 2] = (sample >> 16) & 0xFF;
            }
            break;
        }
        case 20:
        case 32:
            xprintf("FIXME: unimplemented sample size %i\n", alac->setinfo_sample_size);
            break;
        default:
            break;
        }
        break;
    }
    case 1: /* 2 channels */
    {
        int hassize;
        int isnotcompressed;
        int readsamplesize;

        int uncompressed_bytes;

        uint8_t interlacing_shift;
        uint8_t interlacing_leftweight;

        /* 2^result = something to do with output waiting.
         * perhaps matters if we read > 1 frame in a pass?
         */
        readbits(alac, 4);

        readbits(alac, 12); /* unknown, skip 12 bits */

        hassize = readbits(alac, 1); /* the output sample size is stored soon */

        uncompressed_bytes = readbits(alac, 2); /* the number of bytes in the (compressed) stream that are not compressed */

        isnotcompressed = readbits(alac, 1); /* whether the frame is compressed */

        if (hassize)
        {
            /* now read the number of samples,
             * as a 32bit integer */
            outputsamples = readbits(alac, 32);
            *outputsize = outputsamples * alac->bytespersample;
        }

        readsamplesize = alac->setinfo_sample_size - (uncompressed_bytes * 8) + 1;

        if (!isnotcompressed)
        { /* compressed */
            int16_t predictor_coef_table_a[32];
            int predictor_coef_num_a;
            int prediction_type_a;
            int prediction_quantitization_a;
            int ricemodifier_a;

            int16_t predictor_coef_table_b[32];
            int predictor_coef_num_b;
            int prediction_type_b;
            int prediction_quantitization_b;
            int ricemodifier_b;

            int i;

            interlacing_shift = readbits(alac, 8);
            interlacing_leftweight = readbits(alac, 8);

            /******** channel 1 ***********/
            prediction_type_a = readbits(alac, 4);
            prediction_quantitization_a = readbits(alac, 4);

            ricemodifier_a = readbits(alac, 3);
            predictor_coef_num_a = readbits(alac, 5);

            /* read the predictor table */
            for (i = 0; i < predictor_coef_num_a; i++)
            {
                predictor_coef_table_a[i] = (int16_t)readbits(alac, 16);
            }

            /******** channel 2 *********/
            prediction_type_b = readbits(alac, 4);
            prediction_quantitization_b = readbits(alac, 4);

            ricemodifier_b = readbits(alac, 3);
            predictor_coef_num_b = readbits(alac, 5);

            /* read the predictor table */
            for (i = 0; i < predictor_coef_num_b; i++)
            {
                predictor_coef_table_b[i] = (int16_t)readbits(alac, 16);
            }

            /*********************/
            if (uncompressed_bytes)
            { /* see mono case */
                int i;
                for (i = 0; i < outputsamples; i++)
                {
                    alac->uncompressed_bytes_buffer_a[i] = readbits(alac, uncompressed_bytes * 8);
                    alac->uncompressed_bytes_buffer_b[i] = readbits(alac, uncompressed_bytes * 8);
                }
            }

            /* channel 1 */
            entropy_rice_decode(alac,
                                alac->predicterror_buffer_a,
                                outputsamples,
                                readsamplesize,
                                alac->setinfo_rice_initialhistory,
                                alac->setinfo_rice_kmodifier,
                                ricemodifier_a * alac->setinfo_rice_historymult / 4,
                                (1 << alac->setinfo_rice_kmodifier) - 1);

            if (prediction_type_a == 0)
            { /* adaptive fir */
                predictor_decompress_fir_adapt(alac->predicterror_buffer_a,
                                               alac->outputsamples_buffer_a,
                                               outputsamples,
                                               readsamplesize,
                                               predictor_coef_table_a,
                                               predictor_coef_num_a,
                                               prediction_quantitization_a);
            }
            else
            { /* see mono case */
                xprintf("FIXME: unhandled predicition type: %i\n", prediction_type_a);
            }

            /* channel 2 */
            entropy_rice_decode(alac,
                                alac->predicterror_buffer_b,
                                outputsamples,
                                readsamplesize,
                                alac->setinfo_rice_initialhistory,
                                alac->setinfo_rice_kmodifier,
                                ricemodifier_b * alac->setinfo_rice_historymult / 4,
                                (1 << alac->setinfo_rice_kmodifier) - 1);

            if (prediction_type_b == 0)
            { /* adaptive fir */
                predictor_decompress_fir_adapt(alac->predicterror_buffer_b,
                                               alac->outputsamples_buffer_b,
                                               outputsamples,
                                               readsamplesize,
                                               predictor_coef_table_b,
                                               predictor_coef_num_b,
                                               prediction_quantitization_b);
            }
            else
            {
                xprintf("FIXME: unhandled predicition type: %i\n", prediction_type_b);
            }
        }
        else
        { /* not compressed, easy case */
            if (alac->setinfo_sample_size <= 16)
            {
                int i;
                for (i = 0; i < outputsamples; i++)
                {
                    int32_t audiobits_a, audiobits_b;

                    audiobits_a = readbits(alac, alac->setinfo_sample_size);
                    audiobits_b = readbits(alac, alac->setinfo_sample_size);

                    audiobits_a = SIGN_EXTENDED32(audiobits_a, alac->setinfo_sample_size);
                    audiobits_b = SIGN_EXTENDED32(audiobits_b, alac->setinfo_sample_size);

                    alac->outputsamples_buffer_a[i] = audiobits_a;
                    alac->outputsamples_buffer_b[i] = audiobits_b;
                }
            }
            else
            {
                int i;
                for (i = 0; i < outputsamples; i++)
                {
                    int32_t audiobits_a, audiobits_b;

                    audiobits_a = readbits(alac, 16);
                    audiobits_a = audiobits_a << (alac->setinfo_sample_size - 16);
                    audiobits_a |= readbits(alac, alac->setinfo_sample_size - 16);
                    audiobits_a = SignExtend24(audiobits_a);

                    audiobits_b = readbits(alac, 16);
                    audiobits_b = audiobits_b << (alac->setinfo_sample_size - 16);
                    audiobits_b |= readbits(alac, alac->setinfo_sample_size - 16);
                    audiobits_b = SignExtend24(audiobits_b);

                    alac->outputsamples_buffer_a[i] = audiobits_a;
                    alac->outputsamples_buffer_b[i] = audiobits_b;
                }
            }
            uncompressed_bytes = 0; // always 0 for uncompressed
            interlacing_shift = 0;
            interlacing_leftweight = 0;
        }

        switch(alac->setinfo_sample_size)
        {
        case 16:
        {
            deinterlace_16(alac->outputsamples_buffer_a,
                           alac->outputsamples_buffer_b,
                           (int16_t*)outbuffer,
                           alac->numchannels,
                           outputsamples,
                           interlacing_shift,
                           interlacing_leftweight);
            break;
        }
        case 24:
        {
            deinterlace_24(alac->outputsamples_buffer_a,
                           alac->outputsamples_buffer_b,
                           uncompressed_bytes,
                           alac->uncompressed_bytes_buffer_a,
                           alac->uncompressed_bytes_buffer_b,
                           (int16_t*)outbuffer,
                           alac->numchannels,
                           outputsamples,
                           interlacing_shift,
                           interlacing_leftweight);
            break;
        }
        case 20:
        case 32:
            xprintf("FIXME: unimplemented sample size %i\n", alac->setinfo_sample_size);
            break;
        default:
            break;
        }

        break;
    }
    }
}

alac_file *create_alac(int samplesize, int numchannels)
{
    alac_file *newfile = malloc(sizeof(alac_file));

    newfile->samplesize = samplesize;
    newfile->numchannels = numchannels;
    newfile->bytespersample = (samplesize / 8) * numchannels;

    return newfile;
}

void delete_alac(alac_file* f)
{
    free(f);
}


text:
{

  const LOG = require('../../config/logging').getLogger();

  const errorService = require('./advice/errorService')();

  var express = require('express'),
    api = express.Router();

  var authService = require('./authService')(),
    gamesService = require('./gamesService')(),
    Permissions = require('../enum/permissions'),
    Event = require('../models/event'),
    Game = require('../models/game');

  api.get('/', function(req, res) {
    var pOptions = [{
      path: 'event',
      select: 'venue td date',
      populate: [{
        path: 'venue',
        select: 'name day'
      }, {
        path: 'td',
        select: 'name user',
        populate: {
          path: 'user',
          model: 'User',
          select: 'username'
        }
      }]
    }];
    Game
      .find({
        statusId: 1
      })
      .populate(pOptions)
      .select('-statusId')
      .exec(function(err, games) {
        if (err) {
          LOG.error(err);
          return errorService.handleError(res, err);
        }
        return res.send(games);
      });
  });

  api.get('/date', function(req, res) {
    gamesService.byDate(req.query.startDate, req.query.endDate).then(function(games) {
      res.send(games);
    }, (err) => errorService.handleError(res, err));
  });

  api.get('/:id', function(req, res) {
    var pOptions = [{
      path: 'event',
      populate: [{
        path: 'venue',
        select: 'name day numberOfGames'
      }, {
        path: 'td',
        select: 'name user',
        populate: {
          path: 'user',
          model: 'User',
          select: 'username'
        }
      }, {
        path: 'games',
        select: 'event number'
      }]
    }, {
      path: 'players',
      populate: {
        path: 'player',
        select: 'name isTd'
      }
    }];
    Game
      .find({
        _id: req.params.id,
        statusId: 1
      })
      .populate(pOptions)
      .select('-statusId')
      .exec(function(err, games) {
        if (err) {
          LOG.error(err);
          return errorService.handleError(res, err);
        }
        return res.send(games[0]);
      });
  });

  api.get('/count', function(req, res) {
    Game
      .count({
        statusId: 1,
        completed: true
      })
      .exec(function(err, count) {
        if (err) {
          LOG.error(err);
          return errorService.handleError(res, err);
        }
        return res.send({
          count: count
        });
      });
  });

  api.post('/',
    (req, res, next) => authService.checkPermissions(req, res, next, [Permissions.PLAY_GAME]),
    function(req, res) {
      if (req.body._id) {
        var pOptions = [{
          path: 'event',
          populate: [{
            path: 'venue',
            select: 'name day numberOfGames'
          }, {
            path: 'td',
            select: 'name user',
            populate: {
              path: 'user',
              model: 'User',
              select: 'username'
            }
          }, {
            path: 'games',
            select: 'event number'
          }]
        }, {
          path: 'players',
          populate: {
            path: 'player',
            select: 'name isTd'
          }
        }];
        Game
          .findOneAndUpdate({
            _id: req.body._id,
            completed: false
          }, req.body, {
            'new': true
          })
          .populate(pOptions)
          .select('-statusId')
          .exec(function(err, game) {
            if (err) {
              LOG.error(err);
              return errorService.handleError(res, err);
            }
            return res.send(game);
          });
      } else {
        Game.create(req.body, function(err, game) {
          if (err) {
            LOG.error(err);
            return errorService.handleError(res, err);
          }
          Event
            .findOne({
              _id: game['event']
            })
            .exec(function(err, e) {
              if (err) {
                LOG.error(err);
                return errorService.handleError(res, err);
              }
              e.games.push(game._id);
              e.save();
              return res.send(game);
            });
        });
      }
    });

  api.put('/', (req, res, next) => authService.checkPermissions(req, res, next, [Permissions.MODIFY_FINISHED_GAME]),
    function(req, res) {
      Game
        .findOneAndUpdate({
          _id: req.body._id
        }, req.body, {
          'new': true
        })
        .exec(function(err, game) {
          if (err) {
            LOG.error(err);
            return errorService.handleError(res, err);
          }
          return res.send(game);
        });
    });

  api.delete('/:id', (req, res, next) => authService.checkPermissions(req, res, next, [Permissions.DELETE_GAME]),
    function(req, res) {
      req.body.statusId = 2;
      Game
        .findByIdAndUpdate(req.params.id, req.body)
        .exec(function(err) {
          if (err) {
            LOG.error(err);
            return errorService.handleError(res, err);
          }
          return res.send();
        });
    });

  module.exports = api;
}

redpajama_set_name: RedPajamaGithub


text:
import {ElementHandle} from 'puppeteer';
import {expectNotType, expectType} from 'tsd';

declare const handle: ElementHandle;

{
  {
    {
      expectType<ElementHandle<HTMLAnchorElement> | null>(await handle.$('a'));
      expectNotType<ElementHandle<Element> | null>(await handle.$('a'));
    }
    {
      expectType<ElementHandle<HTMLAnchorElement> | null>(
        await handle.$('a#id')
      );
      expectNotType<ElementHandle<Element> | null>(await handle.$('a#id'));
    }
    {
      expectType<ElementHandle<HTMLAnchorElement> | null>(
        await handle.$('a.class')
      );
      expectNotType<ElementHandle<Element> | null>(await handle.$('a.class'));
    }
    {
      expectType<ElementHandle<HTMLAnchorElement> | null>(
        await handle.$('a[attr=value]')
      );
      expectNotType<ElementHandle<Element> | null>(
        await handle.$('a[attr=value]')
      );
    }
    {
      expectType<ElementHandle<HTMLAnchorElement> | null>(
        await handle.$('a:psuedo-class')
      );
      expectNotType<ElementHandle<Element> | null>(
        await handle.$('a:pseudo-class')
      );
    }
    {
      expectType<ElementHandle<HTMLAnchorElement> | null>(
        await handle.$('a:func(arg)')
      );
      expectNotType<ElementHandle<Element> | null>(
        await handle.$('a:func(arg)')
      );
    }
  }
  {
    {
      expectType<ElementHandle<HTMLDivElement> | null>(await handle.$('div'));
      expectNotType<ElementHandle<Element> | null>(await handle.$('div'));
    }
    {
      expectType<ElementHandle<HTMLDivElement> | null>(
        await handle.$('div#id')
      );
      expectNotType<ElementHandle<Element> | null>(await handle.$('div#id'));
    }
    {
      expectType<ElementHandle<HTMLDivElement> | null>(
        await handle.$('div.class')
      );
      expectNotType<ElementHandle<Element> | null>(await handle.$('div.class'));
    }
    {
      expectType<ElementHandle<HTMLDivElement> | null>(
        await handle.$('div[attr=value]')
      );
      expectNotType<ElementHandle<Element> | null>(
        await handle.$('div[attr=value]')
      );
    }
    {
      expectType<ElementHandle<HTMLDivElement> | null>(
        await handle.$('div:psuedo-class')
      );
      expectNotType<ElementHandle<Element> | null>(
        await handle.$('div:pseudo-class')
      );
    }
    {
      expectType<ElementHandle<HTMLDivElement> | null>(
        await handle.$('div:func(arg)')
      );
      expectNotType<ElementHandle<Element> | null>(
        await handle.$('div:func(arg)')
      );
    }
  }
  {
    {
      expectType<ElementHandle<Element> | null>(await handle.$('some-custom'));
    }
    {
      expectType<ElementHandle<Element> | null>(
        await handle.$('some-custom#id')
      );
    }
    {
      expectType<ElementHandle<Element> | null>(
        await handle.$('some-custom.class')
      );
    }
    {
      expectType<ElementHandle<Element> | null>(
        await handle.$('some-custom[attr=value]')
      );
    }
    {
      expectType<ElementHandle<Element> | null>(
        await handle.$('some-custom:pseudo-class')
      );
    }
    {
      expectType<ElementHandle<Element> | null>(
        await handle.$('some-custom:func(arg)')
      );
    }
  }
  {
    {
      expectType<ElementHandle<Element> | null>(await handle.$(''));
    }
    {
      expectType<ElementHandle<Element> | null>(await handle.$('#id'));
    }
    {
      expectType<ElementHandle<Element> | null>(await handle.$('.class'));
    }
    {
      expectType<ElementHandle<Element> | null>(await handle.$('[attr=value]'));
    }
    {
      expectType<ElementHandle<Element> | null>(
        await handle.$(':pseudo-class')
      );
    }
    {
      expectType<ElementHandle<Element> | null>(await handle.$(':func(arg)'));
    }
  }
  {
    {
      expectType<ElementHandle<HTMLAnchorElement> | null>(
        await handle.$('div > a')
      );
      expectNotType<ElementHandle<Element> | null>(await handle.$('div > a'));
    }
    {
      expectType<ElementHandle<HTMLAnchorElement> | null>(
        await handle.$('div > a#id')
      );
      expectNotType<ElementHandle<Element> | null>(
        await handle.$('div > a#id')
      );
    }
    {
      expectType<ElementHandle<HTMLAnchorElement> | null>(
        await handle.$('div > a.class')
      );
      expectNotType<ElementHandle<Element> | null>(
        await handle.$('div > a.class')
      );
    }
    {
      expectType<ElementHandle<HTMLAnchorElement> | null>(
        await handle.$('div > a[attr=value]')
      );
      expectNotType<ElementHandle<Element> | null>(
        await handle.$('div > a[attr=value]')
      );
    }
    {
      expectType<ElementHandle<HTMLAnchorElement> | null>(
        await handle.$('div > a:psuedo-class')
      );
      expectNotType<ElementHandle<Element> | null>(
        await handle.$('div > a:pseudo-class')
      );
    }
    {
      expectType<ElementHandle<HTMLAnchorElement> | null>(
        await handle.$('div > a:func(arg)')
      );
      expectNotType<ElementHandle<Element> | null>(
        await handle.$('div > a:func(arg)')
      );
    }
  }
  {
    {
      expectType<ElementHandle<HTMLDivElement> | null>(
        await handle.$('div > div')
      );
      expectNotType<ElementHandle<Element> | null>(await handle.$('div > div'));
    }
    {
      expectType<ElementHandle<HTMLDivElement> | null>(
        await handle.$('div > div#id')
      );
      expectNotType<ElementHandle<Element> | null>(
        await handle.$('div > div#id')
      );
    }
    {
      expectType<ElementHandle<HTMLDivElement> | null>(
        await handle.$('div > div.class')
      );
      expectNotType<ElementHandle<Element> | null>(
        await handle.$('div > div.class')
      );
    }
    {
      expectType<ElementHandle<HTMLDivElement> | null>(
        await handle.$('div > div[attr=value]')
      );
      expectNotType<ElementHandle<Element> | null>(
        await handle.$('div > div[attr=value]')
      );
    }
    {
      expectType<ElementHandle<HTMLDivElement> | null>(
        await handle.$('div > div:psuedo-class')
      );
      expectNotType<ElementHandle<Element> | null>(
        await handle.$('div > div:pseudo-class')
      );
    }
    {
      expectType<ElementHandle<HTMLDivElement> | null>(
        await handle.$('div > div:func(arg)')
      );
      expectNotType<ElementHandle<Element> | null>(
        await handle.$('div > div:func(arg)')
      );
    }
  }
  {
    {
      expectType<ElementHandle<Element> | null>(
        await handle.$('div > some-custom')
      );
    }
    {
      expectType<ElementHandle<Element> | null>(
        await handle.$('div > some-custom#id')
      );
    }
    {
      expectType<ElementHandle<Element> | null>(
        await handle.$('div > some-custom.class')
      );
    }
    {
      expectType<ElementHandle<Element> | null>(
        await handle.$('div > some-custom[attr=value]')
      );
    }
    {
      expectType<ElementHandle<Element> | null>(
        await handle.$('div > some-custom:pseudo-class')
      );
    }
    {
      expectType<ElementHandle<Element> | null>(
        await handle.$('div > some-custom:func(arg)')
      );
    }
  }
  {
    {
      expectType<ElementHandle<Element> | null>(await handle.$('div > #id'));
    }
    {
      expectType<ElementHandle<Element> | null>(await handle.$('div > .class'));
    }
    {
      expectType<ElementHandle<Element> | null>(
        await handle.$('div > [attr=value]')
      );
    }
    {
      expectType<ElementHandle<Element> | null>(
        await handle.$('div > :pseudo-class')
      );
    }
    {
      expectType<ElementHandle<Element> | null>(
        await handle.$('div > :func(arg)')
      );
    }
  }
  {
    {
      expectType<ElementHandle<HTMLAnchorElement> | null>(
        await handle.$('div > a')
      );
      expectNotType<ElementHandle<Element> | null>(await handle.$('div > a'));
    }
    {
      expectType<ElementHandle<HTMLAnchorElement> | null>(
        await handle.$('div > a#id')
      );
      expectNotType<ElementHandle<Element> | null>(
        await handle.$('div > a#id')
      );
    }
    {
      expectType<ElementHandle<HTMLAnchorElement> | null>(
        await handle.$('div > a.class')
      );
      expectNotType<ElementHandle<Element> | null>(
        await handle.$('div > a.class')
      );
    }
    {
      expectType<ElementHandle<HTMLAnchorElement> | null>(
        await handle.$('div > a[attr=value]')
      );
      expectNotType<ElementHandle<Element> | null>(
        await handle.$('div > a[attr=value]')
      );
    }
    {
      expectType<ElementHandle<HTMLAnchorElement> | null>(
        await handle.$('div > a:psuedo-class')
      );
      expectNotType<ElementHandle<Element> | null>(
        await handle.$('div > a:pseudo-class')
      );
    }
    {
      expectType<ElementHandle<HTMLAnchorElement> | null>(
        await handle.$('div > a:func(arg)')
      );
      expectNotType<ElementHandle<Element> | null>(
        await handle.$('div > a:func(arg)')
      );
    }
  }
  {
    {
      expectType<ElementHandle<HTMLDivElement> | null>(
        await handle.$('div > div')
      );
      expectNotType<ElementHandle<Element> | null>(await handle.$('div > div'));
    }
    {
      expectType<ElementHandle<HTMLDivElement> | null>(
        await handle.$('div > div#id')
      );
      expectNotType<ElementHandle<Element> | null>(
        await handle.$('div > div#id')
      );
    }
    {
      expectType<ElementHandle<HTMLDivElement> | null>(
        await handle.$('div > div.class')
      );
      expectNotType<ElementHandle<Element> | null>(
        await handle.$('div > div.class')
      );
    }
    {
      expectType<ElementHandle<HTMLDivElement> | null>(
        await handle.$('div > div[attr=value]')
      );
      expectNotType<ElementHandle<Element> | null>(
        await handle.$('div > div[attr=value]')
      );
    }
    {
      expectType<ElementHandle<HTMLDivElement> | null>(
        await handle.$('div > div:psuedo-class')
      );
      expectNotType<ElementHandle<Element> | null>(
        await handle.$('div > div:pseudo-class')
      );
    }
    {
      expectType<ElementHandle<HTMLDivElement> | null>(
        await handle.$('div > div:func(arg)')
      );
      expectNotType<ElementHandle<Element> | null>(
        await handle.$('div > div:func(arg)')
      );
    }
  }
  {
    {
      expectType<ElementHandle<Element> | null>(
        await handle.$('div > some-custom')
      );
    }
    {
      expectType<ElementHandle<Element> | null>(
        await handle.$('div > some-custom#id')
      );
    }
    {
      expectType<ElementHandle<Element> | null>(
        await handle.$('div > some-custom.class')
      );
    }
    {
      expectType<ElementHandle<Element> | null>(
        await handle.$('div > some-custom[attr=value]')
      );
    }
    {
      expectType<ElementHandle<Element> | null>(
        await handle.$('div > some-custom:pseudo-class')
      );
    }
    {
      expectType<ElementHandle<Element> | null>(
        await handle.$('div > some-custom:func(arg)')
      );
    }
  }
  {
    {
      expectType<ElementHandle<Element> | null>(await handle.$('div > #id'));
    }
    {
      expectType<ElementHandle<Element> | null>(await handle.$('div > .class'));
    }
    {
      expectType<ElementHandle<Element> | null>(
        await handle.$('div > [attr=value]')
      );
    }
    {
      expectType<ElementHandle<Element> | null>(
        await handle.$('div > :pseudo-class')
      );
    }
    {
      expectType<ElementHandle<Element> | null>(
        await handle.$('div > :func(arg)')
      );
    }
  }
}

{
  {
    {
      expectType<Array<ElementHandle<HTMLAnchorElement>>>(await handle.$$('a'));
      expectNotType<Array<ElementHandle<Element>>>(await handle.$$('a'));
    }
    {
      expectType<Array<ElementHandle<HTMLAnchorElement>>>(
        await handle.$$('a#id')
      );
      expectNotType<Array<ElementHandle<Element>>>(await handle.$$('a#id'));
    }
    {
      expectType<Array<ElementHandle<HTMLAnchorElement>>>(
        await handle.$$('a.class')
      );
      expectNotType<Array<ElementHandle<Element>>>(await handle.$$('a.class'));
    }
    {
      expectType<Array<ElementHandle<HTMLAnchorElement>>>(
        await handle.$$('a[attr=value]')
      );
      expectNotType<Array<ElementHandle<Element>>>(
        await handle.$$('a[attr=value]')
      );
    }
    {
      expectType<Array<ElementHandle<HTMLAnchorElement>>>(
        await handle.$$('a:psuedo-class')
      );
      expectNotType<Array<ElementHandle<Element>>>(
        await handle.$$('a:pseudo-class')
      );
    }
    {
      expectType<Array<ElementHandle<HTMLAnchorElement>>>(
        await handle.$$('a:func(arg)')
      );
      expectNotType<Array<ElementHandle<Element>>>(
        await handle.$$('a:func(arg)')
      );
    }
  }
  {
    {
      expectType<Array<ElementHandle<HTMLDivElement>>>(await handle.$$('div'));
      expectNotType<Array<ElementHandle<Element>>>(await handle.$$('div'));
    }
    {
      expectType<Array<ElementHandle<HTMLDivElement>>>(
        await handle.$$('div#id')
      );
      expectNotType<Array<ElementHandle<Element>>>(await handle.$$('div#id'));
    }
    {
      expectType<Array<ElementHandle<HTMLDivElement>>>(
        await handle.$$('div.class')
      );
      expectNotType<Array<ElementHandle<Element>>>(
        await handle.$$('div.class')
      );
    }
    {
      expectType<Array<ElementHandle<HTMLDivElement>>>(
        await handle.$$('div[attr=value]')
      );
      expectNotType<Array<ElementHandle<Element>>>(
        await handle.$$('div[attr=value]')
      );
    }
    {
      expectType<Array<ElementHandle<HTMLDivElement>>>(
        await handle.$$('div:psuedo-class')
      );
      expectNotType<Array<ElementHandle<Element>>>(
        await handle.$$('div:pseudo-class')
      );
    }
    {
      expectType<Array<ElementHandle<HTMLDivElement>>>(
        await handle.$$('div:func(arg)')
      );
      expectNotType<Array<ElementHandle<Element>>>(
        await handle.$$('div:func(arg)')
      );
    }
  }
  {
    {
      expectType<Array<ElementHandle<Element>>>(await handle.$$('some-custom'));
    }
    {
      expectType<Array<ElementHandle<Element>>>(
        await handle.$$('some-custom#id')
      );
    }
    {
      expectType<Array<ElementHandle<Element>>>(
        await handle.$$('some-custom.class')
      );
    }
    {
      expectType<Array<ElementHandle<Element>>>(
        await handle.$$('some-custom[attr=value]')
      );
    }
    {
      expectType<Array<ElementHandle<Element>>>(
        await handle.$$('some-custom:pseudo-class')
      );
    }
    {
      expectType<Array<ElementHandle<Element>>>(
        await handle.$$('some-custom:func(arg)')
      );
    }
  }
  {
    {
      expectType<Array<ElementHandle<Element>>>(await handle.$$(''));
    }
    {
      expectType<Array<ElementHandle<Element>>>(await handle.$$('#id'));
    }
    {
      expectType<Array<ElementHandle<Element>>>(await handle.$$('.class'));
    }
    {
      expectType<Array<ElementHandle<Element>>>(
        await handle.$$('[attr=value]')
      );
    }
    {
      expectType<Array<ElementHandle<Element>>>(
        await handle.$$(':pseudo-class')
      );
    }
    {
      expectType<Array<ElementHandle<Element>>>(await handle.$$(':func(arg)'));
    }
  }
  {
    {
      expectType<Array<ElementHandle<HTMLAnchorElement>>>(
        await handle.$$('div > a')
      );
      expectNotType<Array<ElementHandle<Element>>>(await handle.$$('div > a'));
    }
    {
      expectType<Array<ElementHandle<HTMLAnchorElement>>>(
        await handle.$$('div > a#id')
      );
      expectNotType<Array<ElementHandle<Element>>>(
        await handle.$$('div > a#id')
      );
    }
    {
      expectType<Array<ElementHandle<HTMLAnchorElement>>>(
        await handle.$$('div > a.class')
      );
      expectNotType<Array<ElementHandle<Element>>>(
        await handle.$$('div > a.class')
      );
    }
    {
      expectType<Array<ElementHandle<HTMLAnchorElement>>>(
        await handle.$$('div > a[attr=value]')
      );
      expectNotType<Array<ElementHandle<Element>>>(
        await handle.$$('div > a[attr=value]')
      );
    }
    {
      expectType<Array<ElementHandle<HTMLAnchorElement>>>(
        await handle.$$('div > a:psuedo-class')
      );
      expectNotType<Array<ElementHandle<Element>>>(
        await handle.$$('div > a:pseudo-class')
      );
    }
    {
      expectType<Array<ElementHandle<HTMLAnchorElement>>>(
        await handle.$$('div > a:func(arg)')
      );
      expectNotType<Array<ElementHandle<Element>>>(
        await handle.$$('div > a:func(arg)')
      );
    }
  }
  {
    {
      expectType<Array<ElementHandle<HTMLDivElement>>>(
        await handle.$$('div > div')
      );
      expectNotType<Array<ElementHandle<Element>>>(
        await handle.$$('div > div')
      );
    }
    {
      expectType<Array<ElementHandle<HTMLDivElement>>>(
        await handle.$$('div > div#id')
      );
      expectNotType<Array<ElementHandle<Element>>>(
        await handle.$$('div > div#id')
      );
    }
    {
      expectType<Array<ElementHandle<HTMLDivElement>>>(
        await handle.$$('div > div.class')
      );
      expectNotType<Array<ElementHandle<Element>>>(
        await handle.$$('div > div.class')
      );
    }
    {
      expectType<Array<ElementHandle<HTMLDivElement>>>(
        await handle.$$('div > div[attr=value]')
      );
      expectNotType<Array<ElementHandle<Element>>>(
        await handle.$$('div > div[attr=value]')
      );
    }
    {
      expectType<Array<ElementHandle<HTMLDivElement>>>(
        await handle.$$('div > div:psuedo-class')
      );
      expectNotType<Array<ElementHandle<Element>>>(
        await handle.$$('div > div:pseudo-class')
      );
    }
    {
      expectType<Array<ElementHandle<HTMLDivElement>>>(
        await handle.$$('div > div:func(arg)')
      );
      expectNotType<Array<ElementHandle<Element>>>(
        await handle.$$('div > div:func(arg)')
      );
    }
  }
  {
    {
      expectType<Array<ElementHandle<Element>>>(
        await handle.$$('div > some-custom')
      );
    }
    {
      expectType<Array<ElementHandle<Element>>>(
        await handle.$$('div > some-custom#id')
      );
    }
    {
      expectType<Array<ElementHandle<Element>>>(
        await handle.$$('div > some-custom.class')
      );
    }
    {
      expectType<Array<ElementHandle<Element>>>(
        await handle.$$('div > some-custom[attr=value]')
      );
    }
    {
      expectType<Array<ElementHandle<Element>>>(
        await handle.$$('div > some-custom:pseudo-class')
      );
    }
    {
      expectType<Array<ElementHandle<Element>>>(
        await handle.$$('div > some-custom:func(arg)')
      );
    }
  }
  {
    {
      expectType<Array<ElementHandle<Element>>>(await handle.$$('div > #id'));
    }
    {
      expectType<Array<ElementHandle<Element>>>(
        await handle.$$('div > .class')
      );
    }
    {
      expectType<Array<ElementHandle<Element>>>(
        await handle.$$('div > [attr=value]')
      );
    }
    {
      expectType<Array<ElementHandle<Element>>>(
        await handle.$$('div > :pseudo-class')
      );
    }
    {
      expectType<Array<ElementHandle<Element>>>(
        await handle.$$('div > :func(arg)')
      );
    }
  }
  {
    {
      expectType<Array<ElementHandle<HTMLAnchorElement>>>(
        await handle.$$('div > a')
      );
      expectNotType<Array<ElementHandle<Element>>>(await handle.$$('div > a'));
    }
    {
      expectType<Array<ElementHandle<HTMLAnchorElement>>>(
        await handle.$$('div > a#id')
      );
      expectNotType<Array<ElementHandle<Element>>>(
        await handle.$$('div > a#id')
      );
    }
    {
      expectType<Array<ElementHandle<HTMLAnchorElement>>>(
        await handle.$$('div > a.class')
      );
      expectNotType<Array<ElementHandle<Element>>>(
        await handle.$$('div > a.class')
      );
    }
    {
      expectType<Array<ElementHandle<HTMLAnchorElement>>>(
        await handle.$$('div > a[attr=value]')
      );
      expectNotType<Array<ElementHandle<Element>>>(
        await handle.$$('div > a[attr=value]')
      );
    }
    {
      expectType<Array<ElementHandle<HTMLAnchorElement>>>(
        await handle.$$('div > a:psuedo-class')
      );
      expectNotType<Array<ElementHandle<Element>>>(
        await handle.$$('div > a:pseudo-class')
      );
    }
    {
      expectType<Array<ElementHandle<HTMLAnchorElement>>>(
        await handle.$$('div > a:func(arg)')
      );
      expectNotType<Array<ElementHandle<Element>>>(
        await handle.$$('div > a:func(arg)')
      );
    }
  }
  {
    {
      expectType<Array<ElementHandle<HTMLDivElement>>>(
        await handle.$$('div > div')
      );
      expectNotType<Array<ElementHandle<Element>>>(
        await handle.$$('div > div')
      );
    }
    {
      expectType<Array<ElementHandle<HTMLDivElement>>>(
        await handle.$$('div > div#id')
      );
      expectNotType<Array<ElementHandle<Element>>>(
        await handle.$$('div > div#id')
      );
    }
    {
      expectType<Array<ElementHandle<HTMLDivElement>>>(
        await handle.$$('div > div.class')
      );
      expectNotType<Array<ElementHandle<Element>>>(
        await handle.$$('div > div.class')
      );
    }
    {
      expectType<Array<ElementHandle<HTMLDivElement>>>(
        await handle.$$('div > div[attr=value]')
      );
      expectNotType<Array<ElementHandle<Element>>>(
        await handle.$$('div > div[attr=value]')
      );
    }
    {
      expectType<Array<ElementHandle<HTMLDivElement>>>(
        await handle.$$('div > div:psuedo-class')
      );
      expectNotType<Array<ElementHandle<Element>>>(
        await handle.$$('div > div:pseudo-class')
      );
    }
    {
      expectType<Array<ElementHandle<HTMLDivElement>>>(
        await handle.$$('div > div:func(arg)')
      );
      expectNotType<Array<ElementHandle<Element>>>(
        await handle.$$('div > div:func(arg)')
      );
    }
  }
  {
    {
      expectType<Array<ElementHandle<Element>>>(
        await handle.$$('div > some-custom')
      );
    }
    {
      expectType<Array<ElementHandle<Element>>>(
        await handle.$$('div > some-custom#id')
      );
    }
    {
      expectType<Array<ElementHandle<Element>>>(
        await handle.$$('div > some-custom.class')
      );
    }
    {
      expectType<Array<ElementHandle<Element>>>(
        await handle.$$('div > some-custom[attr=value]')
      );
    }
    {
      expectType<Array<ElementHandle<Element>>>(
        await handle.$$('div > some-custom:pseudo-class')
      );
    }
    {
      expectType<Array<ElementHandle<Element>>>(
        await handle.$$('div > some-custom:func(arg)')
      );
    }
  }
  {
    {
      expectType<Array<ElementHandle<Element>>>(await handle.$$('div > #id'));
    }
    {
      expectType<Array<ElementHandle<Element>>>(
        await handle.$$('div > .class')
      );
    }
    {
      expectType<Array<ElementHandle<Element>>>(
        await handle.$$('div > [attr=value]')
      );
    }
    {
      expectType<Array<ElementHandle<Element>>>(
        await handle.$$('div > :pseudo-class')
      );
    }
    {
      expectType<Array<ElementHandle<Element>>>(
        await handle.$$('div > :func(arg)')
      );
    }
  }
}

{
  expectType<void>(
    await handle.$eval(
      'a',
      (element, int) => {
        expectType<HTMLAnchorElement>(element);
        expectType<number>(int);
      },
      1
    )
  );
  expectType<void>(
    await handle.$eval(
      'div',
      (element, int, str) => {
        expectType<HTMLDivElement>(element);
        expectType<number>(int);
        expectType<string>(str);
      },
      1,
      ''
    )
  );
  expectType<number>(
    await handle.$eval(
      'a',
      (element, value) => {
        expectType<HTMLAnchorElement>(element);
        return value;
      },
      1
    )
  );
  expectType<number>(
    await handle.$eval(
      'some-element',
      (element, value) => {
        expectType<Element>(element);
        return value;
      },
      1
    )
  );
  expectType<HTMLAnchorElement>(
    await handle.$eval('a', element => {
      return element;
    })
  );
  expectType<unknown>(await handle.$eval('a', 'document'));
}

{
  expectType<void>(
    await handle.$$eval(
      'a',
      (elements, int) => {
        expectType<HTMLAnchorElement[]>(elements);
        expectType<number>(int);
      },
      1
    )
  );
  expectType<void>(
    await handle.$$eval(
      'div',
      (elements, int, str) => {
        expectType<HTMLDivElement[]>(elements);
        expectType<number>(int);
        expectType<string>(str);
      },
      1,
      ''
    )
  );
  expectType<number>(
    await handle.$$eval(
      'a',
      (elements, value) => {
        expectType<HTMLAnchorElement[]>(elements);
        return value;
      },
      1
    )
  );
  expectType<number>(
    await handle.$$eval(
      'some-element',
      (elements, value) => {
        expectType<Element[]>(elements);
        return value;
      },
      1
    )
  );
  expectType<HTMLAnchorElement[]>(
    await handle.$$eval('a', elements => {
      return elements;
    })
  );
  expectType<unknown>(await handle.$$eval('a', 'document'));
}

{
  {
    expectType<ElementHandle<HTMLAnchorElement> | null>(
      await handle.waitForSelector('a')
    );
    expectNotType<ElementHandle<Element> | null>(
      await handle.waitForSelector('a')
    );
  }
  {
    expectType<ElementHandle<HTMLDivElement> | null>(
      await handle.waitForSelector('div')
    );
    expectNotType<ElementHandle<Element> | null>(
      await handle.waitForSelector('div')
    );
  }
  {
    expectType<ElementHandle<Element> | null>(
      await handle.waitForSelector('some-custom')
    );
  }
}


text:
FROM       ubuntu:16.04
MAINTAINER Docker

# Installation:
# Import MongoDB public GPG key AND create a MongoDB list file
RUN apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv EA312927
RUN echo "deb http://repo.mongodb.org/apt/ubuntu $(cat /etc/lsb-release | grep DISTRIB_CODENAME | cut -d= -f2)/mongodb-org/3.2 multiverse" | tee /etc/apt/sources.list.d/mongodb-org-3.2.list

# Update apt-get sources AND install MongoDB
RUN apt-get update && apt-get install -y mongodb-org

# Create the MongoDB data directory
RUN mkdir -p /data/db

# Expose port #27017 from the container to the host
EXPOSE 27017

# Set /usr/bin/mongod as the dockerized entry-point application
ENTRYPOINT ["/usr/bin/mongod"]


text:
<template name="sxsw">

Check us out at SXSW 2015!

A San Antonio-based tech startup, Spacecadet.io... is transforming Austin's open space in a creative and "tasty" way. Right smack in the middle of SXSW. SA Live

If the video is not displaying correctly, you can watch it directly on Facebook.

</template>


text:
package cty

import (
	"bytes"
	"encoding/gob"
	"errors"
	"fmt"
	"math/big"

	"github.com/zclconf/go-cty/cty/set"
)

// GobEncode is an implementation of the gob.GobEncoder interface, which
// allows Values to be included in structures encoded with encoding/gob.
//
// Currently it is not possible to represent values of capsule types in gob,
// because the types themselves cannot be represented.
func (val Value) GobEncode() ([]byte, error) {
	if val.IsMarked() {
		return nil, errors.New("value is marked")
	}

	buf := &bytes.Buffer{}
	enc := gob.NewEncoder(buf)

	gv := gobValue{
		Version: 0,
		Ty:      val.ty,
		V:       val.v,
	}

	err := enc.Encode(gv)
	if err != nil {
		return nil, fmt.Errorf("error encoding cty.Value: %s", err)
	}

	return buf.Bytes(), nil
}

// GobDecode is an implementation of the gob.GobDecoder interface, which
// inverts the operation performed by GobEncode. See the documentation of
// GobEncode for considerations when using cty.Value instances with gob.
func (val *Value) GobDecode(buf []byte) error {
	r := bytes.NewReader(buf)
	dec := gob.NewDecoder(r)

	var gv gobValue
	err := dec.Decode(&gv)
	if err != nil {
		return fmt.Errorf("error decoding cty.Value: %s", err)
	}
	if gv.Version != 0 {
		return fmt.Errorf("unsupported cty.Value encoding version %d; only 0 is supported", gv.Version)
	}

	// Because big.Float.GobEncode is implemented with a pointer reciever,
	// gob encoding of an interface{} containing a *big.Float value does not
	// round-trip correctly, emerging instead as a non-pointer big.Float.
	// The rest of cty expects all number values to be represented by
	// *big.Float, so we'll fix that up here.
	gv.V = gobDecodeFixNumberPtr(gv.V, gv.Ty)

	val.ty = gv.Ty
	val.v = gv.V

	return nil
}

// GobEncode is an implementation of the gob.GobEncoder interface, which
// allows Types to be included in structures encoded with encoding/gob.
//
// Currently it is not possible to represent capsule types in gob.
func (t Type) GobEncode() ([]byte, error) {
	buf := &bytes.Buffer{}
	enc := gob.NewEncoder(buf)

	gt := gobType{
		Version: 0,
		Impl:    t.typeImpl,
	}

	err := enc.Encode(gt)
	if err != nil {
		return nil, fmt.Errorf("error encoding cty.Type: %s", err)
	}

	return buf.Bytes(), nil
}

// GobDecode is an implementatino of the gob.GobDecoder interface, which
// reverses the encoding performed by GobEncode to allow types to be recovered
// from gob buffers.
func (t *Type) GobDecode(buf []byte) error {
	r := bytes.NewReader(buf)
	dec := gob.NewDecoder(r)

	var gt gobType
	err := dec.Decode(&gt)
	if err != nil {
		return fmt.Errorf("error decoding cty.Type: %s", err)
	}
	if gt.Version != 0 {
		return fmt.Errorf("unsupported cty.Type encoding version %d; only 0 is supported", gt.Version)
	}

	t.typeImpl = gt.Impl

	return nil
}

// Capsule types cannot currently be gob-encoded, because they rely on pointer
// equality and we have no way to recover the original pointer on decode.
func (t *capsuleType) GobEncode() ([]byte, error) {
	return nil, fmt.Errorf("cannot gob-encode capsule type %q", t.FriendlyName(friendlyTypeName))
}

func (t *capsuleType) GobDecode() ([]byte, error) {
	return nil, fmt.Errorf("cannot gob-decode capsule type %q", t.FriendlyName(friendlyTypeName))
}

type gobValue struct {
	Version int
	Ty      Type
	V       interface{}
}

type gobType struct {
	Version int
	Impl    typeImpl
}

type gobCapsuleTypeImpl struct {
}

// goDecodeFixNumberPtr fixes an unfortunate quirk of round-tripping cty.Number
// values through gob: the big.Float.GobEncode method is implemented on a
// pointer receiver, and so it loses the "pointer-ness" of the value on
// encode, causing the values to emerge the other end as big.Float rather than
// *big.Float as we expect elsewhere in cty.
//
// The implementation of gobDecodeFixNumberPtr mutates the given raw value
// during its work, and may either return the same value mutated or a new
// value. Callers must no longer use whatever value they pass as "raw" after
// this function is called.
func gobDecodeFixNumberPtr(raw interface{}, ty Type) interface{} {
	// Unfortunately we need to work recursively here because number values
	// might be embedded in structural or collection type values.

	switch {
	case ty.Equals(Number):
		if bf, ok := raw.(big.Float); ok {
			return &bf // wrap in pointer
		}
	case ty.IsMapType() && ty.ElementType().Equals(Number):
		if m, ok := raw.(map[string]interface{}); ok {
			for k, v := range m {
				m[k] = gobDecodeFixNumberPtr(v, ty.ElementType())
			}
		}
	case ty.IsListType() && ty.ElementType().Equals(Number):
		if s, ok := raw.([]interface{}); ok {
			for i, v := range s {
				s[i] = gobDecodeFixNumberPtr(v, ty.ElementType())
			}
		}
	case ty.IsSetType() && ty.ElementType().Equals(Number):
		if s, ok := raw.(set.Set); ok {
			newS := set.NewSet(s.Rules())
			for it := s.Iterator(); it.Next(); {
				newV := gobDecodeFixNumberPtr(it.Value(), ty.ElementType())
				newS.Add(newV)
			}
			return newS
		}
	case ty.IsObjectType():
		if m, ok := raw.(map[string]interface{}); ok {
			for k, v := range m {
				aty := ty.AttributeType(k)
				m[k] = gobDecodeFixNumberPtr(v, aty)
			}
		}
	case ty.IsTupleType():
		if s, ok := raw.([]interface{}); ok {
			for i, v := range s {
				ety := ty.TupleElementType(i)
				s[i] = gobDecodeFixNumberPtr(v, ety)
			}
		}
	}

	return raw
}

// gobDecodeFixNumberPtrVal is a helper wrapper around gobDecodeFixNumberPtr
// that works with already-constructed values. This is primarily for testing,
// to fix up intentionally-invalid number values for the parts of the test
// code that need them to be valid, such as calling GoString on them.
func gobDecodeFixNumberPtrVal(v Value) Value {
	raw := gobDecodeFixNumberPtr(v.v, v.ty)
	return Value{
		v:  raw,
		ty: v.ty,
	}
}


text:
<?php

namespace Metinet\Bundle\FacebookBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\Security\Core\User\UserInterface;

/**
 * Quizz
 *
 * @ORM\Table(name="quizz")
 * @ORM\Entity(repositoryClass="Metinet\Bundle\FacebookBundle\Repository\QuizzRepository")
 * @ORM\HasLifecycleCallbacks
 */
class Quizz
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="title", type="string", length=100)
     */
    private $title;

    /**
     * @var string
     *
     * @ORM\Column(name="picture", type="string", length=255)
     */
    private $picture;

    /**
     * @Assert\File(maxSize="6000000")
     */
    public $file;

    /**
     * Variable optionnelle qui contient le nombre de fois que le quizz a été joué.
     * Sert plus de variable de transport de données à la vue TWIG.
     * N'apparait pas en base.
     */
    private $nbTimesPlayed;

    /**
     * @var string
     *
     * @ORM\Column(name="short_desc", type="string", length=255)
     */
    private $shortDesc;

    /**
     * @var string
     *
     * @ORM\Column(name="long_desc", type="text", nullable=true)
     */
    private $longDesc;

    /**
     * @var integer
     *
     * @ORM\Column(name="win_points", type="integer")
     */
    private $winPoints;

    /**
     * @var float
     *
     */
    private $pourcentage;

    /**
     * @var integer
     *
     */
    private $nbParticipation;

    /**
     * @var integer
     *
     */
    private $nbQuestion;

    /**
     * @var integer
     *
     * @ORM\Column(name="average_time", type="integer")
     */
    private $averageTime;

    /**
     * @var string
     *
     * @ORM\Column(name="txt_win_1", type="string", length=255)
     */
    private $txtWin1;

    /**
     * @var string
     *
     * @ORM\Column(name="txt_win_3", type="string", length=255)
     */
    private $txtWin3;

    /**
     * @var string
     *
     * @ORM\Column(name="txt_win_2", type="string", length=255)
     */
    private $txtWin2;

    /**
     * @var string
     *
     * @ORM\Column(name="txt_win_4", type="string", length=255)
     */
    private $txtWin4;

    /**
     * @var string
     *
     * @ORM\Column(name="share_wall_title", type="string", length=255)
     */
    private $shareWallTitle;

    /**
     * @var string
     *
     * @ORM\Column(name="share_wall_desc", type="string", length=255)
     */
    private $shareWallDesc;

    /**
     * @var boolean
     *
     * @ORM\Column(name="is_promoted", type="boolean")
     */
    private $isPromoted;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="created_at", type="datetime")
     */
    private $createdAt;

    /**
     * @var boolean
     *
     * @ORM\Column(name="state", type="boolean")
     */
    private $state;

    /**
     * @ORM\OneToMany(targetEntity="QuizzResult", mappedBy="quizz", cascade={"remove", "persist"})
     */
    protected $quizzResults;

    /**
     * @ORM\OneToMany(targetEntity="Question", mappedBy="quizz", cascade={"remove", "persist"})
     */
    protected $questions;

    /**
     * @ORM\ManyToOne(targetEntity="Theme", inversedBy="quizzes")
     * @ORM\JoinColumn(name="theme_id", referencedColumnName="id")
     */
    protected $theme;

    /**
     * Constructor
     */
    public function __construct()
    {
        $this->quizzResults = new \Doctrine\Common\Collections\ArrayCollection();
        $this->questions = new \Doctrine\Common\Collections\ArrayCollection();
        $this->createdAt = new \DateTime();
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Get quizz
     *
     * @return Quizz
     */
    public function getQuizz()
    {
        return $this->quizz;
    }

    /**
     * Set quizz
     *
     * @param Quizz $quizz
     * @return Quizz
     */
    public function setQuizz($quizz)
    {
        $this->quizz = $quizz;

        return $this;
    }

    /**
     * Set title
     *
     * @param string $title
     * @return Quizz
     */
    public function setTitle($title)
    {
        $this->title = $title;

        return $this;
    }

    /**
     * Get title
     *
     * @return string
     */
    public function getTitle()
    {
        return $this->title;
    }

    /**
     * Set shortDesc
     *
     * @param string $shortDesc
     * @return Quizz
     */
    public function setShortDesc($shortDesc)
    {
        $this->shortDesc = $shortDesc;

        return $this;
    }

    /**
     * Get shortDesc
     *
     * @return string
     */
    public function getShortDesc()
    {
        return $this->shortDesc;
    }

    /**
     * Set longDesc
     *
     * @param string $longDesc
     * @return Quizz
     */
    public function setLongDesc($longDesc)
    {
        $this->longDesc = $longDesc;

        return $this;
    }

    /**
     * Get longDesc
     *
     * @return string
     */
    public function getLongDesc()
    {
        return $this->longDesc;
    }

    /**
     * Set winPoints
     *
     * @param integer $winPoints
     * @return Quizz
     */
    public function setWinPoints($winPoints)
    {
        $this->winPoints = $winPoints;

        return $this;
    }

    /**
     * Get winPoints
     *
     * @return integer
     */
    public function getWinPoints()
    {
        return $this->winPoints;
    }

    /**
     * Set averageTime
     *
     * @param integer $averageTime
     * @return Quizz
     */
    public function setAverageTime($averageTime)
    {
        $this->averageTime = $averageTime;

        return $this;
    }

    /**
     * Get averageTime
     *
     * @return integer
     */
    public function getAverageTime()
    {
        return $this->averageTime;
    }

    /**
     * Fonction qui retourne le texte de fin de quizz en fonction du pourcentage de bonnes réponses.
     * @param FLOAT $average	Le pourcentage (entre 0 et 1) de bonnes réponses au quizz.
     * @return STRING	Le texte de fin de quizz en fonction du pourcentage de bonnes réponses.
     */
    public function getTxtWin($average) {
        $txtWin = "";
        if ($average >= 0 && $average <= 0.25) {
            $txtWin = $this->getTxtWin1();
        } elseif ($average >= 0.26 && $average <= 0.50) {
            $txtWin = $this->getTxtWin2();
        } elseif ($average >= 0.51 && $average <= 0.75) {
            $txtWin = $this->getTxtWin3();
        } elseif ($average >= 0.76 && $average <= 1) {
            $txtWin = $this->getTxtWin4();
        }
        return $txtWin;
    }

    /**
     * Set txtWin1
     *
     * @param string $txtWin1
     * @return Quizz
     */
    public function setTxtWin1($txtWin1)
    {
        $this->txtWin1 = $txtWin1;

        return $this;
    }

    /**
     * Get txtWin1
     *
     * @return string
     */
    public function getTxtWin1()
    {
        return $this->txtWin1;
    }

    /**
     * Set txtWin3
     *
     * @param string $txtWin3
     * @return Quizz
     */
    public function setTxtWin3($txtWin3)
    {
        $this->txtWin3 = $txtWin3;

        return $this;
    }

    /**
     * Get txtWin3
     *
     * @return string
     */
    public function getTxtWin3()
    {
        return $this->txtWin3;
    }

    /**
     * Set txtWin2
     *
     * @param string $txtWin2
     * @return Quizz
     */
    public function setTxtWin2($txtWin2)
    {
        $this->txtWin2 = $txtWin2;

        return $this;
    }

    /**
     * Get txtWin2
     *
     * @return string
     */
    public function getTxtWin2()
    {
        return $this->txtWin2;
    }

    /**
     * Set txtWin4
     *
     * @param string $txtWin4
     * @return Quizz
     */
    public function setTxtWin4($txtWin4)
    {
        $this->txtWin4 = $txtWin4;

        return $this;
    }

    /**
     * Get txtWin4
     *
     * @return string
     */
    public function getTxtWin4()
    {
        return $this->txtWin4;
    }

    /**
     * Set shareWallTitle
     *
     * @param string $shareWallTitle
     * @return Quizz
     */
    public function setShareWallTitle($shareWallTitle)
    {
        $this->shareWallTitle = $shareWallTitle;

        return $this;
    }

    /**
     * Get shareWallTitle
     *
     * @return string
     */
    public function getShareWallTitle()
    {
        return $this->shareWallTitle;
    }

    /**
     * Set shareWallDesc
     *
     * @param string $shareWallDesc
     * @return Quizz
     */
    public function setShareWallDesc($shareWallDesc)
    {
        $this->shareWallDesc = $shareWallDesc;

        return $this;
    }

    /**
     * Get shareWallDesc
     *
     * @return string
     */
    public function getShareWallDesc()
    {
        return $this->shareWallDesc;
    }

    /**
     * Set isPromoted
     *
     * @param boolean $isPromoted
     * @return Quizz
     */
    public function setIsPromoted($isPromoted)
    {
        $this->isPromoted = $isPromoted;

        return $this;
    }

    /**
     * Get isPromoted
     *
     * @return boolean
     */
    public function getIsPromoted()
    {
        return $this->isPromoted;
    }

    /**
     * Set nbParticipation
     *
     * @param integer $nbParticipation
     * @return Quizz
     */
    public function setNbParticipation($nbParticipation)
    {
        $this->nbParticipation = $nbParticipation;

        return $this;
    }

    /**
     * Get nbParticipation
     *
     * @return integer
     */
    public function getnbParticipation()
    {
        return $this->nbParticipation;
    }

    /**
     * Set nbQuestion
     *
     * @param integer $nbQuestion
     * @return Quizz
     */
    public function setNbQuestion($nbQuestion)
    {
        $this->nbQuestion = $nbQuestion;

        return $this;
    }

    /**
     * Get nbQuestion
     *
     * @return integer
     */
    public function getNbQuestion()
    {
        return $this->nbQuestion;
    }

    /**
     * Set nbParticipation
     *
     * @param \DateTime $createdAt
     * @return Quizz
     */
    public function setCreatedAt($createdAt)
    {
        $this->createdAt = $createdAt;

        return $this;
    }

    /**
     * Get createdAt
     *
     * @return \DateTime
     */
    public function getCreatedAt()
    {
        return $this->createdAt;
    }

    /**
     * Set state
     *
     * @param boolean $state
     * @return Quizz
     */
    public function setState($state)
    {
        $this->state = $state;

        return $this;
    }

    /**
     * Get state
     *
     * @return boolean
     */
    public function getState()
    {
        return $this->state;
    }

    /**
     * Add quizzResults
     *
     * @param \Metinet\Bundle\FacebookBundle\Entity\QuizzResult $quizzResults
     * @return Quizz
     */
    public function addQuizzResult(\Metinet\Bundle\FacebookBundle\Entity\QuizzResult $quizzResults)
    {
        $this->quizzResults[] = $quizzResults;

        return $this;
    }

    /**
     * Remove quizzResults
     *
     * @param \Metinet\Bundle\FacebookBundle\Entity\QuizzResult $quizzResults
     */
    public function removeQuizzResult(\Metinet\Bundle\FacebookBundle\Entity\QuizzResult $quizzResults)
    {
        $this->quizzResults->removeElement($quizzResults);
    }

    /**
     * Get quizzResults
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getQuizzResults()
    {
        return $this->quizzResults;
    }

    /**
     * Add questions
     *
     * @param \Metinet\Bundle\FacebookBundle\Entity\Question $questions
     * @return Quizz
     */
    public function addQuestion(\Metinet\Bundle\FacebookBundle\Entity\Question $questions)
    {
        $this->questions[] = $questions;

        return $this;
    }

    /**
     * Remove questions
     *
     * @param \Metinet\Bundle\FacebookBundle\Entity\Question $questions
     */
    public function removeQuestion(\Metinet\Bundle\FacebookBundle\Entity\Question $questions)
    {
        $this->questions->removeElement($questions);
    }

    /**
     * Get questions
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getQuestions()
    {
        return $this->questions;
    }

    /**
     * Set theme
     *
     * @param \Metinet\Bundle\FacebookBundle\Entity\Theme $theme
     * @return Quizz
     */
    public function setTheme(\Metinet\Bundle\FacebookBundle\Entity\Theme $theme = null)
    {
        $this->theme = $theme;

        return $this;
    }

    /**
     * Get theme
     *
     * @return \Metinet\Bundle\FacebookBundle\Entity\Theme
     */
    public function getTheme()
    {
        return $this->theme;
    }

    /**
     * Set picture
     *
     * @param string $picture
     * @return Quizz
     */
    public function setPicture($picture)
    {
        $this->picture = $picture;

        return $this;
    }

    /**
     * Get picture
     *
     * @return string
     */
    public function getPicture()
    {
        return $this->picture;
    }

    /**
     * Retourne le nombre de fois que le quizz a été joué.
     * /!\ Variable opionelle non remplie automatiquement. Sert plus de variable de transport de données à la vue TWIG.
     */
    public function getNbTimesPlayed(){
	return $this->nbTimesPlayed;
    }

    /**
     * Set le nombre de fois que le quizz a été joué.
     * Sert plus de variable de transport de données à la vue TWIG.
     * N'apparait pas en base.
     */
    public function setNbTimesPlayed($nbTimesPlayed){
	$this->nbTimesPlayed = $nbTimesPlayed;
	return $this;
    }

     public function getAbsolutePath()
    {
        return null === $this->picture ? null : $this->getUploadRootDir().'/'.$this->picture;
    }

    public function getWebPath()
    {
        return null === $this->picture ? null : $this->getUploadDir().'/'.$this->picture;
    }

     protected function getUploadRootDir() {
        // le chemin absolu du répertoire où les documents uploadés doivent être sauvegardés
        return __DIR__ . '/../Resources/public/uploads/pictures/' . $this->getUploadDir();
    }

    protected function getUploadDir() {
        // on se débarrasse de « __DIR__ » afin de ne pas avoir de problème lorsqu'on affiche
        // le document/image dans la vue.
        return 'quizz';
    }

    /**
     * @ORM\PrePersist()
     * @ORM\PreUpdate()
     */
    public function preUpload()
    {
         if (null !== $this->file) {
            // faites ce que vous voulez pour générer un nom unique
            $this->picture = sha1(uniqid(mt_rand(), true)).'.'.$this->file->guessExtension();
        }
    }

    /**
     * @ORM\PostPersist()
     * @ORM\PostUpdate()
     */
    public function upload()
    {
     if (null === $this->file) {
            return;
        }

        // s'il y a une erreur lors du déplacement du fichier, une exception
        // va automatiquement être lancée par la méthode move(). Cela va empêcher
        // proprement l'entité d'être persistée dans la base de données si
        // erreur il y a
        $this->file->move($this->getUploadRootDir(), $this->picture);

        unset($this->file);
    }

    /**
     * @ORM\PostRemove()
     */
    public function removeUpload()
    {
         if ($this->file == $this->getAbsolutePath()) {
            unlink($this->file);
        }
    }

    /**
     * Get pourcentage
     *
     * @return float
     */
    public function getPourcentage()
    {
        return $this->pourcentage;
    }

    /**
     * Set pourcentage
     *
     *
     */
    public function setPourcentage($pourcentage){
	$this->pourcentage = $pourcentage;
	return $this;
    }
}


text:
require File.expand_path(File.join(File.dirname(__FILE__), 'test_helper'))

class FlashdanceTest < Test::Unit::TestCase
  include Quirkey::Flashdance

  def setup
    Loader.yml_path = yml_path
  end

  def test_loader_should_load_yml_file
    loader = Loader.new
    assert loader.entries.is_a?(Hash)
    assert loader.entries.has_key?('all_is_good')
  end

  def test_should_get_specific_entry_in_yaml_file_by_string
    text = flashdance('this_failed')
    assert_equal 'This failed', text
  end

  def test_should_get_specific_entry_in_yaml_file_by_symbol
    text = flashdance(:this_failed)
    assert_equal 'This failed', text
  end

  def test_should_raise_error_if_entry_does_not_exist
    assert_raise(Quirkey::Flashdance::NoEntryError) do
      text = flashdance('im_an_entry_that_dont_exist')
    end
  end

  def test_flashdance_should_evaluate_inline_erb_in_current_context
    flash_ahead
    @email = "email@example.com"
    text = flashdance(:using_erb)
    assert_equal "your are an idiot, #{@email}", text
  end

  def test_flashdance_should_get_entry_organized_into_section
    text = flashdance([:controller, :action])
    assert_equal "I'm nested", text
  end

end


text:
<?php
class Razorphyn_Country_IndexController extends Mage_Adminhtml_Controller_Action{
    public function indexAction(){ //seems ok
        $this->loadLayout();

		//Maybe don't retrieve a limited product

		//get first product id
		$collection = Mage::getModel('catalog/product')->getCollection()
														->addAttributeToFilter('status',array('eq' => Mage_Catalog_Model_Product_Status::STATUS_ENABLED));

		foreach($collection as $res){
			$productId=$res->getId();
			break;
		}

		//get first category of the product
		$product = Mage::getModel('catalog/product')->load($productId);
		$categoryCollection = $product->getCategoryCollection();
		$categoryId=array();
		foreach($categoryCollection as $res){
			$categoryId[]=$res->getId();
		}

		//Create links
		$productUrl = Mage::getBaseUrl().'catalog/product/view/category/'.$categoryId[count($categoryId)-1].'/id/'.$productId.'/razorphyn_theme/';
		$categoryUrl = Mage::getBaseUrl().'catalog/category/view/id/'.$categoryId[count($categoryId)-1].'/razorphyn_theme/';

		$theme=Mage::getStoreConfig('design/package/name');
		$ob=unserialize(Mage::getStoreConfig('design/package/ua_regexp'));

		$stored = json_decode(Mage::getStoreConfig('razorphyn/country/buttons'));

		$links=array(array(
						$theme,
						$productUrl.$theme,
						$categoryUrl.$theme,
						isset($stored->$theme->product)? 'Y':'N',
						isset($stored->$theme->category)? 'Y':'N'
					));

		foreach($ob as $key){
			if(empty($key['value']))
				continue;

			$completeProd = isset($stored->$key['value']->product) ? 'Y':'N';
			$completeCat  = isset($stored->$key['value']->category)? 'Y':'N';
			$links[]= array(
								$key['value'],
								$productUrl.$key['value'],
								$categoryUrl.$key['value'],
								$completeProd,
								$completeCat
							);
		}

		$body='

							'.Mage::helper('country')->__("Theme").'
							'.Mage::helper('country')->__("Product").'
							'.Mage::helper('country')->__("Category").'
							'.Mage::helper('country')->__("Complete").'

			  ';
		foreach($links as $link){

			$body.='

							'.$link[0].'
							'.Mage::helper('country')->__("Product Configuration Url").'
							'.Mage::helper('country')->__("Category Configuration Url").'
							'.$link[3].'/'.$link[4].'

					';
		}
		$body.='

';

        $block = $this	->getLayout()
						->createBlock('core/text', 'razorphyn.country.themelink')
						->setText($body);

        $this->_addContent($block);

        $this->renderLayout();
    }
}