text:
/*
 *  PSA AEAD entry points
 */
/*
 *  Copyright The Mbed TLS Contributors
 *  SPDX-License-Identifier: Apache-2.0
 *
 *  Licensed under the Apache License, Version 2.0 (the "License"); you may
 *  not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

#include "common.h"

#if defined(MBEDTLS_PSA_CRYPTO_C)

#include "psa_crypto_aead.h"
#include "psa_crypto_core.h"

#include <string.h>
#include "mbedtls/platform.h"
#if !defined(MBEDTLS_PLATFORM_C)
#define mbedtls_calloc calloc
#define mbedtls_free   free
#endif

#include "mbedtls/ccm.h"
#include "mbedtls/chachapoly.h"
#include "mbedtls/cipher.h"
#include "mbedtls/gcm.h"
#include "mbedtls/error.h"

static psa_status_t psa_aead_setup(
    mbedtls_psa_aead_operation_t *operation,
    const psa_key_attributes_t *attributes,
    const uint8_t *key_buffer,
    size_t key_buffer_size,
    psa_algorithm_t alg )
{
    psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
    size_t key_bits;
    const mbedtls_cipher_info_t *cipher_info;
    mbedtls_cipher_id_t cipher_id;
    size_t full_tag_length = 0;

    ( void ) key_buffer_size;

    key_bits = attributes->core.bits;

    cipher_info = mbedtls_cipher_info_from_psa( alg,
                                                attributes->core.type, key_bits,
                                                &cipher_id );
    if( cipher_info == NULL )
        return( PSA_ERROR_NOT_SUPPORTED );

    switch( PSA_ALG_AEAD_WITH_SHORTENED_TAG( alg, 0 ) )
    {
#if defined(MBEDTLS_PSA_BUILTIN_ALG_CCM)
        case PSA_ALG_AEAD_WITH_SHORTENED_TAG( PSA_ALG_CCM, 0 ):
            operation->alg = PSA_ALG_CCM;
            full_tag_length = 16;
            /* CCM allows the following tag lengths: 4, 6, 8, 10, 12, 14, 16.
             * The call to mbedtls_ccm_encrypt_and_tag or
             * mbedtls_ccm_auth_decrypt will validate the tag length. */
            if( PSA_BLOCK_CIPHER_BLOCK_LENGTH( attributes->core.type ) != 16 )
                return( PSA_ERROR_INVALID_ARGUMENT );

            mbedtls_ccm_init( &operation->ctx.ccm );
            status = mbedtls_to_psa_error(
                mbedtls_ccm_setkey( &operation->ctx.ccm, cipher_id,
                                    key_buffer, (unsigned int) key_bits ) );
            if( status != PSA_SUCCESS )
                return( status );
            break;
#endif /* MBEDTLS_PSA_BUILTIN_ALG_CCM */

#if defined(MBEDTLS_PSA_BUILTIN_ALG_GCM)
        case PSA_ALG_AEAD_WITH_SHORTENED_TAG( PSA_ALG_GCM, 0 ):
            operation->alg = PSA_ALG_GCM;
            full_tag_length = 16;
            /* GCM allows the following tag lengths: 4, 8, 12, 13, 14, 15, 16.
             * The call to mbedtls_gcm_crypt_and_tag or
             * mbedtls_gcm_auth_decrypt will validate the tag length. */
            if( PSA_BLOCK_CIPHER_BLOCK_LENGTH( attributes->core.type ) != 16 )
                return( PSA_ERROR_INVALID_ARGUMENT );

            mbedtls_gcm_init( &operation->ctx.gcm );
            status = mbedtls_to_psa_error(
                mbedtls_gcm_setkey( &operation->ctx.gcm, cipher_id,
                                    key_buffer, (unsigned int) key_bits ) );
            if( status != PSA_SUCCESS )
                return( status );
            break;
#endif /* MBEDTLS_PSA_BUILTIN_ALG_GCM */

#if defined(MBEDTLS_PSA_BUILTIN_ALG_CHACHA20_POLY1305)
        case PSA_ALG_AEAD_WITH_SHORTENED_TAG( PSA_ALG_CHACHA20_POLY1305, 0 ):
            operation->alg = PSA_ALG_CHACHA20_POLY1305;
            full_tag_length = 16;
            /* We only support the default tag length. */
            if( alg != PSA_ALG_CHACHA20_POLY1305 )
                return( PSA_ERROR_NOT_SUPPORTED );

            mbedtls_chachapoly_init( &operation->ctx.chachapoly );
            status = mbedtls_to_psa_error(
                mbedtls_chachapoly_setkey( &operation->ctx.chachapoly,
                                           key_buffer ) );
            if( status != PSA_SUCCESS )
                return( status );
            break;
#endif /* MBEDTLS_PSA_BUILTIN_ALG_CHACHA20_POLY1305 */

        default:
            (void) status;
            (void) key_buffer;
            return( PSA_ERROR_NOT_SUPPORTED );
    }

    if( PSA_AEAD_TAG_LENGTH( attributes->core.type,
                             key_bits, alg )
        > full_tag_length )
        return( PSA_ERROR_INVALID_ARGUMENT );

    operation->key_type = psa_get_key_type( attributes );

    operation->tag_length = PSA_AEAD_TAG_LENGTH( operation->key_type,
                                                 key_bits,
                                                 alg );

    return( PSA_SUCCESS );
}

psa_status_t mbedtls_psa_aead_encrypt(
    const psa_key_attributes_t *attributes,
    const uint8_t *key_buffer, size_t key_buffer_size,
    psa_algorithm_t alg,
    const uint8_t *nonce, size_t nonce_length,
    const uint8_t *additional_data, size_t additional_data_length,
    const uint8_t *plaintext, size_t plaintext_length,
    uint8_t *ciphertext, size_t ciphertext_size, size_t *ciphertext_length )
{
    psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
    mbedtls_psa_aead_operation_t operation = MBEDTLS_PSA_AEAD_OPERATION_INIT;
    uint8_t *tag;

    status = psa_aead_setup( &operation, attributes, key_buffer,
                             key_buffer_size, alg );

    if( status != PSA_SUCCESS )
        goto exit;

    /* For all currently supported modes, the tag is at the end of the
     * ciphertext. */
    if( ciphertext_size < ( plaintext_length + operation.tag_length ) )
    {
        status = PSA_ERROR_BUFFER_TOO_SMALL;
        goto exit;
    }
    tag = ciphertext + plaintext_length;

#if defined(MBEDTLS_PSA_BUILTIN_ALG_CCM)
    if( operation.alg == PSA_ALG_CCM )
    {
        status = mbedtls_to_psa_error(
            mbedtls_ccm_encrypt_and_tag( &operation.ctx.ccm,
                                         plaintext_length,
                                         nonce, nonce_length,
                                         additional_data,
                                         additional_data_length,
                                         plaintext, ciphertext,
                                         tag, operation.tag_length ) );
    }
    else
#endif /* MBEDTLS_PSA_BUILTIN_ALG_CCM */
#if defined(MBEDTLS_PSA_BUILTIN_ALG_GCM)
    if( operation.alg == PSA_ALG_GCM )
    {
        status = mbedtls_to_psa_error(
            mbedtls_gcm_crypt_and_tag( &operation.ctx.gcm,
                                       MBEDTLS_GCM_ENCRYPT,
                                       plaintext_length,
                                       nonce, nonce_length,
                                       additional_data, additional_data_length,
                                       plaintext, ciphertext,
                                       operation.tag_length, tag ) );
    }
    else
#endif /* MBEDTLS_PSA_BUILTIN_ALG_GCM */
#if defined(MBEDTLS_PSA_BUILTIN_ALG_CHACHA20_POLY1305)
    if( operation.alg == PSA_ALG_CHACHA20_POLY1305 )
    {
        if( operation.tag_length != 16 )
        {
            status = PSA_ERROR_NOT_SUPPORTED;
            goto exit;
        }
        status = mbedtls_to_psa_error(
            mbedtls_chachapoly_encrypt_and_tag( &operation.ctx.chachapoly,
                                                plaintext_length,
                                                nonce,
                                                additional_data,
                                                additional_data_length,
                                                plaintext,
                                                ciphertext,
                                                tag ) );
    }
    else
#endif /* MBEDTLS_PSA_BUILTIN_ALG_CHACHA20_POLY1305 */
    {
        (void) tag;
        (void) nonce;
        (void) nonce_length;
        (void) additional_data;
        (void) additional_data_length;
        (void) plaintext;
        return( PSA_ERROR_NOT_SUPPORTED );
    }

    if( status == PSA_SUCCESS )
        *ciphertext_length = plaintext_length + operation.tag_length;

exit:
    mbedtls_psa_aead_abort( &operation );

    return( status );
}

/* Locate the tag in a ciphertext buffer containing the encrypted data
 * followed by the tag. Return the length of the part preceding the tag in
 * *plaintext_length. This is the size of the plaintext in modes where
 * the encrypted data has the same size as the plaintext, such as
 * CCM and GCM. */
static psa_status_t psa_aead_unpadded_locate_tag( size_t tag_length,
                                                  const uint8_t *ciphertext,
                                                  size_t ciphertext_length,
                                                  size_t plaintext_size,
                                                  const uint8_t **p_tag )
{
    size_t payload_length;
    if( tag_length > ciphertext_length )
        return( PSA_ERROR_INVALID_ARGUMENT );
    payload_length = ciphertext_length - tag_length;
    if( payload_length > plaintext_size )
        return( PSA_ERROR_BUFFER_TOO_SMALL );
    *p_tag = ciphertext + payload_length;
    return( PSA_SUCCESS );
}

psa_status_t mbedtls_psa_aead_decrypt(
    const psa_key_attributes_t *attributes,
    const uint8_t *key_buffer, size_t key_buffer_size,
    psa_algorithm_t alg,
    const uint8_t *nonce, size_t nonce_length,
    const uint8_t *additional_data, size_t additional_data_length,
    const uint8_t *ciphertext, size_t ciphertext_length,
    uint8_t *plaintext, size_t plaintext_size, size_t *plaintext_length )
{
    psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
    mbedtls_psa_aead_operation_t operation = MBEDTLS_PSA_AEAD_OPERATION_INIT;
    const uint8_t *tag = NULL;

    status = psa_aead_setup( &operation, attributes, key_buffer,
                             key_buffer_size, alg );

    if( status != PSA_SUCCESS )
        goto exit;

    status = psa_aead_unpadded_locate_tag( operation.tag_length,
                                           ciphertext, ciphertext_length,
                                           plaintext_size, &tag );
    if( status != PSA_SUCCESS )
        goto exit;

#if defined(MBEDTLS_PSA_BUILTIN_ALG_CCM)
    if( operation.alg == PSA_ALG_CCM )
    {
        status = mbedtls_to_psa_error(
            mbedtls_ccm_auth_decrypt( &operation.ctx.ccm,
                                      ciphertext_length - operation.tag_length,
                                      nonce, nonce_length,
                                      additional_data,
                                      additional_data_length,
                                      ciphertext, plaintext,
                                      tag, operation.tag_length ) );
    }
    else
#endif /* MBEDTLS_PSA_BUILTIN_ALG_CCM */
#if defined(MBEDTLS_PSA_BUILTIN_ALG_GCM)
    if( operation.alg == PSA_ALG_GCM )
    {
        status = mbedtls_to_psa_error(
            mbedtls_gcm_auth_decrypt( &operation.ctx.gcm,
                                      ciphertext_length - operation.tag_length,
                                      nonce, nonce_length,
                                      additional_data,
                                      additional_data_length,
                                      tag, operation.tag_length,
                                      ciphertext, plaintext ) );
    }
    else
#endif /* MBEDTLS_PSA_BUILTIN_ALG_GCM */
#if defined(MBEDTLS_PSA_BUILTIN_ALG_CHACHA20_POLY1305)
    if( operation.alg == PSA_ALG_CHACHA20_POLY1305 )
    {
        if( operation.tag_length != 16 )
        {
            status = PSA_ERROR_NOT_SUPPORTED;
            goto exit;
        }
        status = mbedtls_to_psa_error(
            mbedtls_chachapoly_auth_decrypt( &operation.ctx.chachapoly,
                                             ciphertext_length - operation.tag_length,
                                             nonce,
                                             additional_data,
                                             additional_data_length,
                                             tag,
                                             ciphertext,
                                             plaintext ) );
    }
    else
#endif /* MBEDTLS_PSA_BUILTIN_ALG_CHACHA20_POLY1305 */
    {
        (void) nonce;
        (void) nonce_length;
        (void) additional_data;
        (void) additional_data_length;
        (void) plaintext;
        return( PSA_ERROR_NOT_SUPPORTED );
    }

    if( status == PSA_SUCCESS )
        *plaintext_length = ciphertext_length - operation.tag_length;

exit:
    mbedtls_psa_aead_abort( &operation );

    if( status == PSA_SUCCESS )
        *plaintext_length = ciphertext_length - operation.tag_length;
    return( status );
}

/* Set the key and algorithm for a multipart authenticated encryption
 * operation. */
psa_status_t mbedtls_psa_aead_encrypt_setup(
    mbedtls_psa_aead_operation_t *operation,
    const psa_key_attributes_t *attributes,
    const uint8_t *key_buffer,
    size_t key_buffer_size,
    psa_algorithm_t alg )
{
    psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;

    status = psa_aead_setup( operation, attributes, key_buffer,
                             key_buffer_size, alg );

    if( status == PSA_SUCCESS )
        operation->is_encrypt = 1;

    return ( status );
}

/* Set the key and algorithm for a multipart authenticated decryption
 * operation. */
psa_status_t mbedtls_psa_aead_decrypt_setup(
    mbedtls_psa_aead_operation_t *operation,
    const psa_key_attributes_t *attributes,
    const uint8_t *key_buffer,
    size_t key_buffer_size,
    psa_algorithm_t alg )
{
    psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;

    status = psa_aead_setup( operation, attributes, key_buffer,
                             key_buffer_size, alg );

    if( status == PSA_SUCCESS )
        operation->is_encrypt = 0;

    return ( status );
}

/* Set a nonce for the multipart AEAD operation*/
psa_status_t mbedtls_psa_aead_set_nonce(
    mbedtls_psa_aead_operation_t *operation,
    const uint8_t *nonce,
    size_t nonce_length )
{
    psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;

#if defined(MBEDTLS_PSA_BUILTIN_ALG_GCM)
    if( operation->alg == PSA_ALG_GCM )
    {
        status = mbedtls_to_psa_error(
                 mbedtls_gcm_starts( &operation->ctx.gcm,
                                     operation->is_encrypt ?
                                     MBEDTLS_GCM_ENCRYPT : MBEDTLS_GCM_DECRYPT,
                                     nonce,
                                     nonce_length ) );
    }
    else
#endif /* MBEDTLS_PSA_BUILTIN_ALG_GCM */
#if defined(MBEDTLS_PSA_BUILTIN_ALG_CCM)
    if( operation->alg == PSA_ALG_CCM )
    {
        status = mbedtls_to_psa_error(
                   mbedtls_ccm_starts( &operation->ctx.ccm,
                                       operation->is_encrypt ?
                                       MBEDTLS_CCM_ENCRYPT : MBEDTLS_CCM_DECRYPT,
                                       nonce,
                                       nonce_length ) );
    }
    else
#endif /* MBEDTLS_PSA_BUILTIN_ALG_CCM */
#if defined(MBEDTLS_PSA_BUILTIN_ALG_CHACHA20_POLY1305)
    if( operation->alg == PSA_ALG_CHACHA20_POLY1305 )
    {
        /* Note - ChaChaPoly allows an 8 byte nonce, but we would have to
         * allocate a buffer in the operation, copy the nonce to it and pad
         * it, so for now check the nonce is 12 bytes, as
         * mbedtls_chachapoly_starts() assumes it can read 12 bytes from the
         * passed in buffer. */
        if( nonce_length != 12 )
        {
            return( PSA_ERROR_INVALID_ARGUMENT );
        }

        status = mbedtls_to_psa_error(
           mbedtls_chachapoly_starts( &operation->ctx.chachapoly,
                                      nonce,
                                      operation->is_encrypt ?
                                      MBEDTLS_CHACHAPOLY_ENCRYPT :
                                      MBEDTLS_CHACHAPOLY_DECRYPT ) );
    }
    else
#endif /* MBEDTLS_PSA_BUILTIN_ALG_CHACHA20_POLY1305 */
    {
        ( void ) operation;
        ( void ) nonce;
        ( void ) nonce_length;

        return ( PSA_ERROR_NOT_SUPPORTED );
    }

    return( status );
}

 /* Declare the lengths of the message and additional data for AEAD. */
psa_status_t mbedtls_psa_aead_set_lengths(
    mbedtls_psa_aead_operation_t *operation,
    size_t ad_length,
    size_t plaintext_length )
{
#if defined(MBEDTLS_PSA_BUILTIN_ALG_CCM)
    if( operation->alg == PSA_ALG_CCM )
    {
        return( mbedtls_to_psa_error(
                         mbedtls_ccm_set_lengths( &operation->ctx.ccm,
                                                 ad_length,
                                                 plaintext_length,
                                                 operation->tag_length ) ) );

    }
#else /* MBEDTLS_PSA_BUILTIN_ALG_CCM */
    ( void ) operation;
    ( void ) ad_length;
    ( void ) plaintext_length;
#endif /* MBEDTLS_PSA_BUILTIN_ALG_CCM */

    return ( PSA_SUCCESS );
}

/* Pass additional data to an active multipart AEAD operation. */
psa_status_t mbedtls_psa_aead_update_ad(
    mbedtls_psa_aead_operation_t *operation,
    const uint8_t *input,
    size_t input_length )
{
    psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;

#if defined(MBEDTLS_PSA_BUILTIN_ALG_GCM)
    if( operation->alg == PSA_ALG_GCM )
    {
        status = mbedtls_to_psa_error(
            mbedtls_gcm_update_ad( &operation->ctx.gcm, input, input_length ) );
    }
    else
#endif /* MBEDTLS_PSA_BUILTIN_ALG_GCM */
#if defined(MBEDTLS_PSA_BUILTIN_ALG_CCM)
    if( operation->alg == PSA_ALG_CCM )
    {
        status = mbedtls_to_psa_error(
            mbedtls_ccm_update_ad( &operation->ctx.ccm, input, input_length ) );
    }
    else
#endif /* MBEDTLS_PSA_BUILTIN_ALG_CCM */
#if defined(MBEDTLS_PSA_BUILTIN_ALG_CHACHA20_POLY1305)
    if( operation->alg == PSA_ALG_CHACHA20_POLY1305 )
    {
        status = mbedtls_to_psa_error(
           mbedtls_chachapoly_update_aad( &operation->ctx.chachapoly,
                                          input,
                                          input_length ) );
    }
    else
#endif /* MBEDTLS_PSA_BUILTIN_ALG_CHACHA20_POLY1305 */
    {
        ( void ) operation;
        ( void ) input;
        ( void ) input_length;

        return ( PSA_ERROR_NOT_SUPPORTED );
    }

    return ( status );
}

/* Encrypt or decrypt a message fragment in an active multipart AEAD
 * operation.*/
psa_status_t mbedtls_psa_aead_update(
    mbedtls_psa_aead_operation_t *operation,
    const uint8_t *input,
    size_t input_length,
    uint8_t *output,
    size_t output_size,
    size_t *output_length )
{
    size_t update_output_length;
    psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;

    update_output_length = input_length;

#if defined(MBEDTLS_PSA_BUILTIN_ALG_GCM)
    if( operation->alg == PSA_ALG_GCM )
    {
        status =  mbedtls_to_psa_error(
            mbedtls_gcm_update( &operation->ctx.gcm,
                                input, input_length,
                                output, output_size,
                                &update_output_length ) );
    }
    else
#endif /* MBEDTLS_PSA_BUILTIN_ALG_GCM */
#if defined(MBEDTLS_PSA_BUILTIN_ALG_CCM)
    if( operation->alg == PSA_ALG_CCM )
    {
        if( output_size < input_length )
            return( PSA_ERROR_BUFFER_TOO_SMALL );

        status = mbedtls_to_psa_error(
           mbedtls_ccm_update( &operation->ctx.ccm,
                               input, input_length,
                               output, output_size,
                               &update_output_length ) );
    }
    else
#endif /* MBEDTLS_PSA_BUILTIN_ALG_CCM */
#if defined(MBEDTLS_PSA_BUILTIN_ALG_CHACHA20_POLY1305)
    if( operation->alg == PSA_ALG_CHACHA20_POLY1305 )
    {
        if( output_size < input_length )
            return( PSA_ERROR_BUFFER_TOO_SMALL );

        status = mbedtls_to_psa_error(
           mbedtls_chachapoly_update( &operation->ctx.chachapoly,
                                      input_length,
                                      input,
                                      output ) );
    }
    else
#endif /* MBEDTLS_PSA_BUILTIN_ALG_CHACHA20_POLY1305 */
    {
        ( void ) operation;
        ( void ) input;
        ( void ) output;
        ( void ) output_size;

        return ( PSA_ERROR_NOT_SUPPORTED );
    }

    if( status == PSA_SUCCESS )
        *output_length = update_output_length;

    return( status );
}

/* Finish encrypting a message in a multipart AEAD operation. */
psa_status_t mbedtls_psa_aead_finish(
    mbedtls_psa_aead_operation_t *operation,
    uint8_t *ciphertext,
    size_t ciphertext_size,
    size_t *ciphertext_length,
    uint8_t *tag,
    size_t tag_size,
    size_t *tag_length )
{
    psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
    size_t finish_output_size = 0;

    if( tag_size < operation->tag_length )
        return( PSA_ERROR_BUFFER_TOO_SMALL );

#if defined(MBEDTLS_PSA_BUILTIN_ALG_GCM)
    if( operation->alg == PSA_ALG_GCM )
    {
        status =  mbedtls_to_psa_error(
            mbedtls_gcm_finish( &operation->ctx.gcm,
                                ciphertext, ciphertext_size, ciphertext_length,
                                tag, operation->tag_length ) );
    }
    else
#endif /* MBEDTLS_PSA_BUILTIN_ALG_GCM */
#if defined(MBEDTLS_PSA_BUILTIN_ALG_CCM)
    if( operation->alg == PSA_ALG_CCM )
    {
        /* tag must be big enough to store a tag of size passed into set
         * lengths. */
        if( tag_size < operation->tag_length )
            return( PSA_ERROR_BUFFER_TOO_SMALL );

        status = mbedtls_to_psa_error(
                           mbedtls_ccm_finish( &operation->ctx.ccm,
                                               tag, operation->tag_length ) );
    }
    else
#endif /* MBEDTLS_PSA_BUILTIN_ALG_CCM */
#if defined(MBEDTLS_PSA_BUILTIN_ALG_CHACHA20_POLY1305)
    if( operation->alg == PSA_ALG_CHACHA20_POLY1305 )
    {
        /* Belt and braces. Although the above tag_size check should have
         * already done this, if we later start supporting smaller tag sizes
         * for chachapoly, then passing a tag buffer smaller than 16 into here
         * could cause a buffer overflow, so better safe than sorry. */
        if( tag_size < 16 )
            return( PSA_ERROR_BUFFER_TOO_SMALL );

        status = mbedtls_to_psa_error(
            mbedtls_chachapoly_finish( &operation->ctx.chachapoly,
                                       tag ) );
    }
    else
#endif /* MBEDTLS_PSA_BUILTIN_ALG_CHACHA20_POLY1305 */
    {
        ( void ) ciphertext;
        ( void ) ciphertext_size;
        ( void ) ciphertext_length;
        ( void ) tag;
        ( void ) tag_size;
        ( void ) tag_length;

        return ( PSA_ERROR_NOT_SUPPORTED );
    }

    if( status == PSA_SUCCESS )
    {
        /* This will be zero for all supported algorithms currently, but left
         * here for future support. */
        *ciphertext_length = finish_output_size;
        *tag_length = operation->tag_length;
    }

    return ( status );
}

/* Abort an AEAD operation */
psa_status_t mbedtls_psa_aead_abort(
   mbedtls_psa_aead_operation_t *operation )
{
    switch( operation->alg )
    {
#if defined(MBEDTLS_PSA_BUILTIN_ALG_CCM)
        case PSA_ALG_CCM:
            mbedtls_ccm_free( &operation->ctx.ccm );
            break;
#endif /* MBEDTLS_PSA_BUILTIN_ALG_CCM */
#if defined(MBEDTLS_PSA_BUILTIN_ALG_GCM)
        case PSA_ALG_GCM:
            mbedtls_gcm_free( &operation->ctx.gcm );
            break;
#endif /* MBEDTLS_PSA_BUILTIN_ALG_GCM */
#if defined(MBEDTLS_PSA_BUILTIN_ALG_CHACHA20_POLY1305)
        case PSA_ALG_CHACHA20_POLY1305:
            mbedtls_chachapoly_free( &operation->ctx.chachapoly );
            break;
#endif /* MBEDTLS_PSA_BUILTIN_ALG_CHACHA20_POLY1305 */
    }

    operation->is_encrypt = 0;

    return( PSA_SUCCESS );
}

#endif /* MBEDTLS_PSA_CRYPTO_C */


text:
#ifndef SRC_WEBSERVER_HTTP_RESPONSE_INL_H_
#define SRC_WEBSERVER_HTTP_RESPONSE_INL_H_

#include <assert.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>

#include "src/log.h"

static const char *ok_response_header =
    "HTTP/1.0 200 ok\r\n"
    "Server: openDMD-0.01\r\n"
    "Connection: close\r\n"
    "Max-Age: 0\r\n"
    "Expires: 0\r\n"
    "Cache-Control: no-cache\r\n"
    "Cache-Control: private\r\n"
    "Pragma: no-cache\r\n"
    "Content-type: text/html\r\n\r\n";

static const char *bad_request_response =
    "HTTP/1.0 400 Bad Request\r\n"
    "Content-type: text/html\r\n\r\n"
    "\n"
    "\n"
    "
Bad Request
\n"
    "
The server did not understand your request.
\n"
    "\n"
    "\n";

static const char * forbidden_response =
    "HTTP/1.0 403 Forbidden\r\n"
    "Content-type: text/html\r\n\r\n"
    "\n"
    "\n"
    "<title>Forbidden</title>\n"
    ""
    "\n"
    "
Forbidden
\n"
    "
The requested URL was forbidden to access.
\n"
    "\n"
    "\n";

static const char * not_found_response =
    "HTTP/1.0 404 Not Found\r\n"
    "Content-type: text/html\r\n\r\n"
    "\n"
    "\n"
    "<title>Not Found</title>\n"
    "\n"
    "\n"
    "
Not Found
\n"
    "
The requested URL was not found on the server.
\n"
    "\n"
    "\n";

static const char *method_not_implemented_response =
    "HTTP/1.0 501 Method Not Implemented\r\n"
    "Content-type: text/html\r\n\r\n"
    "\n"
    "\n"
    "<title>Method Not Implemented</title>\n"
    "\n"
    "\n"
    "
Method Not Implemented
\n"
    "
The method is not implemented by this server.
\n"
    "\n"
    "\n";

static const char *not_valid_response =
    "HTTP/1.0 404 Not Valid\r\n"
    "Content-type: text/html\r\n\r\n"
    "\n"
    "\n"
    "<title>Not Valid</title>\n"
    "\n"
    "\n"
    "
Not Valid
\n"
    "
The requested URL is not valid.
\n"
    "\n"
    "\n";

static const char *auth_response =
    "HTTP/1.0 401 Authorization Required\r\n"
    "WWW-Authenticate: Basic realm=\"openDMD Security Access\"\r\n";

static const char *response_header =
    "<!DOCTYPE html>\n"
    "\n"
    "\n"
    "<meta http-equiv=\"Content-Type\" content=\"text/html; "
    "charset=UTF-8\" />\n"
    "<title>%s</title>\n"
    "\n";

static const char *response_css =
    "\n";

static const char *response_footer = "";

static inline void send_not_found_response(int client_fd) {
    int not_found_len = strlen(not_found_response);
    int sendlen = send(client_fd, not_found_response, not_found_len, 0);
    assert(sendlen == not_found_len);
    dmd_log(LOG_DEBUG, "send not_found_response to client:\n%s\n",
            not_found_response);
}

static inline void send_bad_request_response(int client_fd) {
    int bad_request_len = strlen(bad_request_response);
    int sendlen = send(client_fd, bad_request_response, bad_request_len, 0);
    assert(sendlen == bad_request_len);
    dmd_log(LOG_DEBUG, "send bad_request_response to client:\n%s\n",
            bad_request_response);
}

static inline void send_ok_response_header(int client_fd) {
    int ok_len = strlen(ok_response_header);
    int sendlen = send(client_fd, ok_response_header, ok_len, 0);
    assert(sendlen == ok_len);
    dmd_log(LOG_DEBUG, "send ok_response_header to client:\n%s\n",
            ok_response_header);
}

static inline void send_forbidden_response(int client_fd) {
    int forbidden_len = strlen(forbidden_response);
    int sendlen = send(client_fd, forbidden_response, forbidden_len, 0);
    assert(sendlen == forbidden_len);
    dmd_log(LOG_DEBUG, "send forbidden_response to client:\n%s\n",
            forbidden_response);
}

static inline void send_not_valid_response(int client_fd) {
    int not_valid_len = strlen(not_valid_response);
    int sendlen = send(client_fd, not_valid_response, not_valid_len, 0);
    assert(sendlen == not_valid_len);
    dmd_log(LOG_DEBUG, "send not_valid_response to client:\n%s\n",
            not_valid_response);
}

static inline void send_method_not_implemented_response(int client_fd) {
    int not_implemented_len = strlen(method_not_implemented_response);
    int sendlen = send(client_fd, method_not_implemented_response,
            not_implemented_len, 0);
    assert(sendlen == not_implemented_len);
    dmd_log(LOG_DEBUG, "send method_not_implemented_response to client:\n%s\n",
            method_not_implemented_response);
}

static void send_authentication(int client_fd) {
    int auth_response_len = strlen(auth_response);
    int sendlen = send(client_fd, auth_response, auth_response_len, 0);
    assert(sendlen == auth_response_len);
    dmd_log(LOG_DEBUG, "send auth_response to client:\n%s\n", auth_response);
}

static inline void send_response_header(int client_fd, const char *title) {
    char header[1024];
    sprintf(header, response_header, title);
    int header_len = strlen(header);
    int sendlen = send(client_fd, header, header_len, 0);
    assert(sendlen == header_len);
    dmd_log(LOG_DEBUG, "send response header to client:\n%s\n",
            header);
}

static inline void send_css(int client_fd) {
    int css_len = strlen(response_css);
    int sendlen = send(client_fd, response_css, css_len, 0);
    assert(sendlen == css_len);
    dmd_log(LOG_DEBUG, "send response css to client:\n%s\n",
            response_css);
}

static inline void send_response_footer(int client_fd) {
    int footer_len = strlen(response_footer);
    int sendlen = send(client_fd, response_footer, footer_len, 0);
    assert(sendlen == footer_len);
    dmd_log(LOG_DEBUG, "send response footer to client:\n%s\n",
            response_footer);
}

#endif  // SRC_WEBSERVER_HTTP_RESPONSE_INL_H_

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.ComponentModel;

using NLua;
using BizHawk.Emulation.Common;
using BizHawk.Emulation.Common.IEmulatorExtensions;
using BizHawk.Common.BufferExtensions;

namespace BizHawk.Client.Common
{
	[Description("These functions behavior identically to the mainmemory functions but the user can set the memory domain to read and write from. The default domain is main memory. Use getcurrentmemorydomain(), and usememorydomain() to control which domain is used. Each core has its own set of valid memory domains. Use getmemorydomainlist() to get a list of memory domains for the current core loaded.")]
	public sealed class MemoryLuaLibrary : LuaMemoryBase
	{
		private MemoryDomain _currentMemoryDomain;

		public MemoryLuaLibrary(Lua lua)
			: base(lua)
		{
		}

		public MemoryLuaLibrary(Lua lua, Action<string> logOutputCallback)
			: base(lua, logOutputCallback)
		{
		}

		public override string Name => "memory";

		protected override MemoryDomain Domain
		{
			get
			{
				if (MemoryDomainCore != null)
				{
					if (_currentMemoryDomain == null)
					{
						_currentMemoryDomain = MemoryDomainCore.HasSystemBus
							? MemoryDomainCore.SystemBus
							: MemoryDomainCore.MainMemory;
					}

					return _currentMemoryDomain;
				}

				var error = $"Error: {Emulator.Attributes().CoreName} does not implement memory domains";
				Log(error);
				throw new NotImplementedException(error);
			}
		}

		#region Unique Library Methods

		[LuaMethodExample("local nlmemget = memory.getmemorydomainlist();")]
		[LuaMethod("getmemorydomainlist", "Returns a string of the memory domains for the loaded platform core. List will be a single string delimited by line feeds")]
		public LuaTable GetMemoryDomainList()
		{
			var table = Lua.NewTable();

			int i = 0;
			foreach (var domain in DomainList)
			{
				table[i] = domain.Name;
				i++;
			}

			return table;
		}

		[LuaMethodExample("local uimemget = memory.getmemorydomainsize( mainmemory.getname( ) );")]
		[LuaMethod("getmemorydomainsize", "Returns the number of bytes of the specified memory domain. If no domain is specified, or the specified domain doesn't exist, returns the current domain size")]
		public uint GetMemoryDomainSize(string name = "")
		{
			if (string.IsNullOrEmpty(name))
			{
				return (uint)Domain.Size;
			}

			return (uint)DomainList[VerifyMemoryDomain(name)].Size;
		}

		[LuaMethodExample("local stmemget = memory.getcurrentmemorydomain( );")]
		[LuaMethod("getcurrentmemorydomain", "Returns a string name of the current memory domain selected by Lua. The default is Main memory")]
		public string GetCurrentMemoryDomain()
		{
			return Domain.Name;
		}

		[LuaMethodExample("local uimemget = memory.getcurrentmemorydomainsize( );")]
		[LuaMethod("getcurrentmemorydomainsize", "Returns the number of bytes of the current memory domain selected by Lua. The default is Main memory")]
		public uint GetCurrentMemoryDomainSize()
		{
			return (uint)Domain.Size;
		}

		[LuaMethodExample("if ( memory.usememorydomain( mainmemory.getname( ) ) ) then\r\n\tconsole.log( \"Attempts to set the current memory domain to the given domain. If the name does not match a valid memory domain, the function returns false, else it returns true\" );\r\nend;")]
		[LuaMethod("usememorydomain", "Attempts to set the current memory domain to the given domain. If the name does not match a valid memory domain, the function returns false, else it returns true")]
		public bool UseMemoryDomain(string domain)
		{
			try
			{
				if (DomainList[domain] != null)
				{
					_currentMemoryDomain = DomainList[domain];
					return true;
				}

				Log($"Unable to find domain: {domain}");
				return false;
			}
			catch // Just in case
			{
				Log($"Unable to find domain: {domain}");
			}

			return false;
		}

		[LuaMethodExample("local stmemhas = memory.hash_region( 0x100, 50, mainmemory.getname( ) );")]
		[LuaMethod("hash_region", "Returns a hash as a string of a region of memory, starting from addr, through count bytes. If the domain is unspecified, it uses the current region.")]
		public string HashRegion(int addr, int count, string domain = null)
		{
			var d = string.IsNullOrEmpty(domain) ? Domain : DomainList[VerifyMemoryDomain(domain)];

			// checks
			if (addr < 0 || addr >= d.Size)
			{
				string error = $"Address {addr} is outside the bounds of domain {d.Name}";
				Log(error);
				throw new ArgumentOutOfRangeException(error);
			}
			if (addr + count > d.Size)
			{
				string error = $"Address {addr} + count {count} is outside the bounds of domain {d.Name}";
				Log(error);
				throw new ArgumentOutOfRangeException(error);
			}

			byte[] data = new byte[count];
			for (int i = 0; i < count; i++)
			{
				data[i] = d.PeekByte(addr + i);
			}

			using (var hasher = System.Security.Cryptography.SHA256.Create())
			{
				return hasher.ComputeHash(data).BytesToHexString();
			}
		}

		#endregion

		#region Common Special and Legacy Methods

		[LuaMethodExample("local uimemrea = memory.readbyte( 0x100, mainmemory.getname( ) );")]
		[LuaMethod("readbyte", "gets the value from the given address as an unsigned byte")]
		public uint ReadByte(int addr, string domain = null)
		{
			return ReadUnsignedByte(addr, domain);
		}

		[LuaMethodExample("memory.writebyte( 0x100, 1000, mainmemory.getname( ) );")]
		[LuaMethod("writebyte", "Writes the given value to the given address as an unsigned byte")]
		public void WriteByte(int addr, uint value, string domain = null)
		{
			WriteUnsignedByte(addr, value, domain);
		}

		[LuaMethodExample("local nlmemrea = memory.readbyterange( 0x100, 30, mainmemory.getname( ) );")]
		[LuaMethod("readbyterange", "Reads the address range that starts from address, and is length long. Returns the result into a table of key value pairs (where the address is the key).")]
		public new LuaTable ReadByteRange(int addr, int length, string domain = null)
		{
			return base.ReadByteRange(addr, length, domain);
		}

		[LuaMethodExample("")]
		[LuaMethod("writebyterange", "Writes the given values to the given addresses as unsigned bytes")]
		public new void WriteByteRange(LuaTable memoryblock, string domain = null)
		{
			base.WriteByteRange(memoryblock, domain);
		}

		[LuaMethodExample("local simemrea = memory.readfloat( 0x100, false, mainmemory.getname( ) );")]
		[LuaMethod("readfloat", "Reads the given address as a 32-bit float value from the main memory domain with th e given endian")]
		public new float ReadFloat(int addr, bool bigendian, string domain = null)
		{
			return base.ReadFloat(addr, bigendian, domain);
		}

		[LuaMethodExample("memory.writefloat( 0x100, 10.0, false, mainmemory.getname( ) );")]
		[LuaMethod("writefloat", "Writes the given 32-bit float value to the given address and endian")]
		public new void WriteFloat(int addr, double value, bool bigendian, string domain = null)
		{
			base.WriteFloat(addr, value, bigendian, domain);
		}

		#endregion

		#region 1 Byte

		[LuaMethodExample("local inmemrea = memory.read_s8( 0x100, mainmemory.getname( ) );")]
		[LuaMethod("read_s8", "read signed byte")]
		public int ReadS8(int addr, string domain = null)
		{
			return (sbyte)ReadUnsignedByte(addr, domain);
		}

		[LuaMethodExample("memory.write_s8( 0x100, 1000, mainmemory.getname( ) );")]
		[LuaMethod("write_s8", "write signed byte")]
		public void WriteS8(int addr, uint value, string domain = null)
		{
			WriteUnsignedByte(addr, value, domain);
		}

		[LuaMethodExample("local uimemrea = memory.read_u8( 0x100, mainmemory.getname( ) );")]
		[LuaMethod("read_u8", "read unsigned byte")]
		public uint ReadU8(int addr, string domain = null)
		{
			return ReadUnsignedByte(addr, domain);
		}

		[LuaMethodExample("memory.write_u8( 0x100, 1000, mainmemory.getname( ) );")]
		[LuaMethod("write_u8", "write unsigned byte")]
		public void WriteU8(int addr, uint value, string domain = null)
		{
			WriteUnsignedByte(addr, value, domain);
		}

		#endregion

		#region 2 Byte

		[LuaMethodExample("local inmemrea = memory.read_s16_le( 0x100, mainmemory.getname( ) );")]
		[LuaMethod("read_s16_le", "read signed 2 byte value, little endian")]
		public int ReadS16Little(int addr, string domain = null)
		{
			return ReadSignedLittleCore(addr, 2, domain);
		}

		[LuaMethodExample("memory.write_s16_le( 0x100, -1000, mainmemory.getname( ) );")]
		[LuaMethod("write_s16_le", "write signed 2 byte value, little endian")]
		public void WriteS16Little(int addr, int value, string domain = null)
		{
			WriteSignedLittle(addr, value, 2, domain);
		}

		[LuaMethodExample("local inmemrea = memory.read_s16_be( 0x100, mainmemory.getname( ) );")]
		[LuaMethod("read_s16_be", "read signed 2 byte value, big endian")]
		public int ReadS16Big(int addr, string domain = null)
		{
			return ReadSignedBig(addr, 2, domain);
		}

		[LuaMethodExample("memory.write_s16_be( 0x100, -1000, mainmemory.getname( ) );")]
		[LuaMethod("write_s16_be", "write signed 2 byte value, big endian")]
		public void WriteS16Big(int addr, int value, string domain = null)
		{
			WriteSignedBig(addr, value, 2, domain);
		}

		[LuaMethodExample("local uimemrea = memory.read_u16_le( 0x100, mainmemory.getname( ) );")]
		[LuaMethod("read_u16_le", "read unsigned 2 byte value, little endian")]
		public uint ReadU16Little(int addr, string domain = null)
		{
			return ReadUnsignedLittle(addr, 2, domain);
		}

		[LuaMethodExample("memory.write_u16_le( 0x100, 1000, mainmemory.getname( ) );")]
		[LuaMethod("write_u16_le", "write unsigned 2 byte value, little endian")]
		public void WriteU16Little(int addr, uint value, string domain = null)
		{
			WriteUnsignedLittle(addr, value, 2, domain);
		}

		[LuaMethodExample("local uimemrea = memory.read_u16_be( 0x100, mainmemory.getname( ) );")]
		[LuaMethod("read_u16_be", "read unsigned 2 byte value, big endian")]
		public uint ReadU16Big(int addr, string domain = null)
		{
			return ReadUnsignedBig(addr, 2, domain);
		}

		[LuaMethodExample("memory.write_u16_be( 0x100, 1000, mainmemory.getname( ) );")]
		[LuaMethod("write_u16_be", "write unsigned 2 byte value, big endian")]
		public void WriteU16Big(int addr, uint value, string domain = null)
		{
			WriteUnsignedBig(addr, value, 2, domain);
		}

		#endregion

		#region 3 Byte

		[LuaMethodExample("local inmemrea = memory.read_s24_le( 0x100, mainmemory.getname( ) );")]
		[LuaMethod("read_s24_le", "read signed 24 bit value, little endian")]
		public int ReadS24Little(int addr, string domain = null)
		{
			return ReadSignedLittleCore(addr, 3, domain);
		}

		[LuaMethodExample("memory.write_s24_le( 0x100, -1000, mainmemory.getname( ) );")]
		[LuaMethod("write_s24_le", "write signed 24 bit value, little endian")]
		public void WriteS24Little(int addr, int value, string domain = null)
		{
			WriteSignedLittle(addr, value, 3, domain);
		}

		[LuaMethodExample("local inmemrea = memory.read_s24_be( 0x100, mainmemory.getname( ) );")]
		[LuaMethod("read_s24_be", "read signed 24 bit value, big endian")]
		public int ReadS24Big(int addr, string domain = null)
		{
			return ReadSignedBig(addr, 3, domain);
		}

		[LuaMethodExample("memory.write_s24_be( 0x100, -1000, mainmemory.getname( ) );")]
		[LuaMethod("write_s24_be", "write signed 24 bit value, big endian")]
		public void WriteS24Big(int addr, int value, string domain = null)
		{
			WriteSignedBig(addr, value, 3, domain);
		}

		[LuaMethodExample("local uimemrea = memory.read_u24_le( 0x100, mainmemory.getname( ) );")]
		[LuaMethod("read_u24_le", "read unsigned 24 bit value, little endian")]
		public uint ReadU24Little(int addr, string domain = null)
		{
			return ReadUnsignedLittle(addr, 3, domain);
		}

		[LuaMethodExample("memory.write_u24_le( 0x100, 1000, mainmemory.getname( ) );")]
		[LuaMethod("write_u24_le", "write unsigned 24 bit value, little endian")]
		public void WriteU24Little(int addr, uint value, string domain = null)
		{
			WriteUnsignedLittle(addr, value, 3, domain);
		}

		[LuaMethodExample("local uimemrea = memory.read_u24_be( 0x100, mainmemory.getname( ) );")]
		[LuaMethod("read_u24_be", "read unsigned 24 bit value, big endian")]
		public uint ReadU24Big(int addr, string domain = null)
		{
			return ReadUnsignedBig(addr, 3, domain);
		}

		[LuaMethodExample("memory.write_u24_be( 0x100, 1000, mainmemory.getname( ) );")]
		[LuaMethod("write_u24_be", "write unsigned 24 bit value, big endian")]
		public void WriteU24Big(int addr, uint value, string domain = null)
		{
			WriteUnsignedBig(addr, value, 3, domain);
		}

		#endregion

		#region 4 Byte

		[LuaMethodExample("local inmemrea = memory.read_s32_le( 0x100, mainmemory.getname( ) );")]
		[LuaMethod("read_s32_le", "read signed 4 byte value, little endian")]
		public int ReadS32Little(int addr, string domain = null)
		{
			return ReadSignedLittleCore(addr, 4, domain);
		}

		[LuaMethodExample("memory.write_s32_le( 0x100, -1000, mainmemory.getname( ) );")]
		[LuaMethod("write_s32_le", "write signed 4 byte value, little endian")]
		public void WriteS32Little(int addr, int value, string domain = null)
		{
			WriteSignedLittle(addr, value, 4, domain);
		}

		[LuaMethodExample("local inmemrea = memory.read_s32_be( 0x100, mainmemory.getname( ) );")]
		[LuaMethod("read_s32_be", "read signed 4 byte value, big endian")]
		public int ReadS32Big(int addr, string domain = null)
		{
			return ReadSignedBig(addr, 4, domain);
		}

		[LuaMethodExample("memory.write_s32_be( 0x100, -1000, mainmemory.getname( ) );")]
		[LuaMethod("write_s32_be", "write signed 4 byte value, big endian")]
		public void WriteS32Big(int addr, int value, string domain = null)
		{
			WriteSignedBig(addr, value, 4, domain);
		}

		[LuaMethodExample("local uimemrea = memory.read_u32_le( 0x100, mainmemory.getname( ) );")]
		[LuaMethod("read_u32_le", "read unsigned 4 byte value, little endian")]
		public uint ReadU32Little(int addr, string domain = null)
		{
			return ReadUnsignedLittle(addr, 4, domain);
		}

		[LuaMethodExample("memory.write_u32_le( 0x100, 1000, mainmemory.getname( ) );")]
		[LuaMethod("write_u32_le", "write unsigned 4 byte value, little endian")]
		public void WriteU32Little(int addr, uint value, string domain = null)
		{
			WriteUnsignedLittle(addr, value, 4, domain);
		}

		[LuaMethodExample("local uimemrea = memory.read_u32_be( 0x100, mainmemory.getname( ) );")]
		[LuaMethod("read_u32_be", "read unsigned 4 byte value, big endian")]
		public uint ReadU32Big(int addr, string domain = null)
		{
			return ReadUnsignedBig(addr, 4, domain);
		}

		[LuaMethodExample("memory.write_u32_be( 0x100, 1000, mainmemory.getname( ) );")]
		[LuaMethod("write_u32_be", "write unsigned 4 byte value, big endian")]
		public void WriteU32Big(int addr, uint value, string domain = null)
		{
			WriteUnsignedBig(addr, value, 4, domain);
		}

		#endregion
	}
}


text:
package org.uberfire.ext.widgets.common.client.ace;

import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.client.JsArray;
import com.google.gwt.dom.client.Element;
import com.google.gwt.user.client.TakesValue;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HasText;
import com.google.gwt.user.client.ui.RequiresResize;

/**
 * A GWT widget for the Ajax.org Code Editor (ACE).
 * @see Ajax.org Code Editor
 */
public class AceEditor extends Composite implements RequiresResize,
                                                    HasText,
                                                    TakesValue<String> {

    // Used to generate unique element ids for Ace widgets.
    private static int nextId = 0;

    private final String elementId;

    private JavaScriptObject editor;

    private JsArray<AceAnnotation> annotations = JavaScriptObject.createArray().cast();

    private Element divElement;

    /**
     * Preferred constructor.
     */
    public AceEditor() {
        elementId = "_aceGWT" + nextId;
        nextId++;
        FlowPanel div = new FlowPanel();
        div.getElement().setId(elementId);
        initWidget(div);
        divElement = div.getElement();
        getElement().setAttribute("data-uf-lock-on-click",
                                  "false");
    }

    /**
     * Do not use this constructor: just use the default constructor.
     */
    @Deprecated
    public AceEditor(boolean unused) {
        this();
    }

    /**
     * Removes all existing completers from the langtools

     * This can be used to disable all completers including local completers, which can be very useful
     * when completers are used on very large files (as the local completer tokenizes every word to put in the selected list).

     * NOTE: This method may be removed, and replaced with another solution. It works at point of check-in, but treat this as unstable for now.
     */
    public native static void removeAllExistingCompleters() /*-{
        var langTools = $wnd.ace.require("ace/ext/language_tools");
        langTools.removeCompleters();
    }-*/;

    /**
     * Add an {@link AceCompletionProvider} to provide
     * custom code completions.
     *

     * Warning: this is an experimental feature of AceGWT.
     * It is possible that the API will change in an incompatible way
     * in future releases.
     * @param provider the {@link AceCompletionProvider}
     */
    public native static void addCompletionProvider(AceCompletionProvider provider) /*-{
        var langTools = $wnd.ace.require("ace/ext/language_tools");
        var completer = {
            getCompletions: function (editor, session, pos, prefix, callback) {
                var callbackWrapper =
                        @org.uberfire.ext.widgets.common.client.ace.AceEditor::wrapCompletionCallback(Lcom/google/gwt/core/client/JavaScriptObject;)(callback);
                var aceEditor = editor._aceGWTAceEditor;
                provider.@org.uberfire.ext.widgets.common.client.ace.AceCompletionProvider::getProposals(Lorg/uberfire/ext/widgets/common/client/ace/AceEditor;Lorg/uberfire/ext/widgets/common/client/ace/AceEditorCursorPosition;Ljava/lang/String;Lorg/uberfire/ext/widgets/common/client/ace/AceCompletionCallback;)(
                        aceEditor,
                        @org.uberfire.ext.widgets.common.client.ace.AceEditorCursorPosition::create(II)(pos.row, pos.column),
                        prefix,
                        callbackWrapper
                );
            }
        };
        langTools.addCompleter(completer);
    }-*/;

    private static AceCompletionCallback wrapCompletionCallback(JavaScriptObject jsCallback) {
        return new AceCompletionCallbackImpl(jsCallback);
    }

    /**
     * Call this method to start the editor.
     * Make sure that the widget has been attached to the DOM tree
     * before calling this method.
     */
    public native void startEditor() /*-{
        var editor = $wnd.ace.edit(this.@org.uberfire.ext.widgets.common.client.ace.AceEditor::divElement);
        editor.getSession().setUseWorker(false);
        this.@org.uberfire.ext.widgets.common.client.ace.AceEditor::editor = editor;

        // Store a reference to the (Java) AceEditor object in the
        // JavaScript editor object.
        editor._aceGWTAceEditor = this;

        // I have been noticing sporadic failures of the editor
        // to display properly and receive key/mouse events.
        // Try to force the editor to resize and display itself fully.  See:
        //    https://groups.google.com/group/ace-discuss/browse_thread/thread/237262b521dcea33
        editor.resize();
        this.@org.uberfire.ext.widgets.common.client.ace.AceEditor::redisplay();
    }-*/;

    /**
     * Call this to force the editor contents to be redisplayed.
     * There seems to be a problem when an AceEditor is embedded in a LayoutPanel:
     * the editor contents don't appear, and it refuses to accept focus
     * and mouse events, until the browser window is resized.
     * Calling this method works around the problem by forcing
     * the underlying editor to redisplay itself fully. (?)
     */
    public native void redisplay() /*-{
        var editor = this.@org.uberfire.ext.widgets.common.client.ace.AceEditor::editor;
        editor.renderer.onResize(true);
        editor.renderer.updateFull();
        editor.resize();
        editor.focus();
    }-*/;

    /**
     * Cleans up the entire editor.
     */
    public native void destroy() /*-{
        var editor = this.@org.uberfire.ext.widgets.common.client.ace.AceEditor::editor;
        editor.destroy();
    }-*/;

    /**
     * Set the theme.
     * @param theme the theme (one of the values in the {@link AceEditorTheme}
     * enumeration)
     */
    public void setTheme(final AceEditorTheme theme) {
        setThemeByName(theme.getName());
    }

    /**
     * Set the theme by name.
     * @param themeName the theme name (e.g., "twilight")
     */
    public native void setThemeByName(String themeName) /*-{
        var editor = this.@org.uberfire.ext.widgets.common.client.ace.AceEditor::editor;
        editor.setTheme("ace/theme/" + themeName);
    }-*/;

    /**
     * Set the mode.
     * @param mode the mode (one of the values in the
     * {@link AceEditorMode} enumeration)
     */
    public void setMode(final AceEditorMode mode) {
        setModeByName(mode.getName());
    }

    /**
     * Set the mode by name.
     * @param shortModeName name of mode (e.g., "eclipse")
     */
    public native void setModeByName(String shortModeName) /*-{
        var editor = this.@org.uberfire.ext.widgets.common.client.ace.AceEditor::editor;
        var modeName = "ace/mode/" + shortModeName;
        var TheMode = $wnd.require(modeName).Mode;
        editor.getSession().setMode(new TheMode());
    }-*/;

    /**
     * Register a handler for change events generated by the editor.
     * @param callback the change event handler
     */
    public native void addOnChangeHandler(AceEditorCallback callback) /*-{
        var editor = this.@org.uberfire.ext.widgets.common.client.ace.AceEditor::editor;
        editor.getSession().on("change", function (e) {
            callback.@org.uberfire.ext.widgets.common.client.ace.AceEditorCallback::invokeAceCallback(Lcom/google/gwt/core/client/JavaScriptObject;)(e);
        });
    }-*/;

    /**
     * Register a handler for cursor position change events generated by the editor.
     * @param callback the cursor position change event handler
     */
    public native void addOnCursorPositionChangeHandler(AceEditorCallback callback) /*-{
        var editor = this.@org.uberfire.ext.widgets.common.client.ace.AceEditor::editor;
        editor.getSession().selection.on("changeCursor", function (e) {
            callback.@org.uberfire.ext.widgets.common.client.ace.AceEditorCallback::invokeAceCallback(Lcom/google/gwt/core/client/JavaScriptObject;)(e);
        });
    }-*/;

    /**
     * Set font size.
     */
    public native void setFontSize(String fontSize) /*-{
        var elementId = this.@org.uberfire.ext.widgets.common.client.ace.AceEditor::elementId;
        var elt = $doc.getElementById(elementId);
        elt.style.fontSize = fontSize;
    }-*/;

    /**
     * Get the complete text in the editor as a String.
     * @return the text in the editor
     */
    public native String getText() /*-{
        var editor = this.@org.uberfire.ext.widgets.common.client.ace.AceEditor::editor;
        return editor.getSession().getValue();
    }-*/;

    /**
     * Set the complete text in the editor from a String.
     * @param text the text to set in the editor
     */
    public native void setText(String text) /*-{
        var editor = this.@org.uberfire.ext.widgets.common.client.ace.AceEditor::editor;
        editor.getSession().setValue(text);
    }-*/;

    /**
     * Get the line of text at the given row number.
     * @param row the row number
     * @return the line of text at that row number
     */
    public native String getLine(int row) /*-{
        var editor = this.@org.uberfire.ext.widgets.common.client.ace.AceEditor::editor;
        return editor.getSession().getDocument().getLine(row);
    }-*/;

    /**
     * Insert given text at the cursor.
     * @param text text to insert at the cursor
     */
    public native void insertAtCursor(String text) /*-{
        var editor = this.@org.uberfire.ext.widgets.common.client.ace.AceEditor::editor;
        editor.insert(text);
    }-*/;

    /**
     * Get the current cursor position.
     * @return the current cursor position
     */
    public native AceEditorCursorPosition getCursorPosition() /*-{
        var editor = this.@org.uberfire.ext.widgets.common.client.ace.AceEditor::editor;
        var pos = editor.getCursorPosition();
        return this.@org.uberfire.ext.widgets.common.client.ace.AceEditor::getCursorPositionImpl(DD)(pos.row, pos.column);
    }-*/;

    private AceEditorCursorPosition getCursorPositionImpl(final double row,
                                                          final double column) {
        return new AceEditorCursorPosition((int) row,
                                           (int) column);
    }

    /**
     * Gets the given document position as a zero-based index.
     * @param position the position to obtain the absolute index of (base zero)
     * @return An index to the current location in the document
     */
    public int getIndexFromPosition(AceEditorCursorPosition position) {
        return getIndexFromPositionImpl(position.toJsObject());
    }

    private native int getIndexFromPositionImpl(JavaScriptObject jsPosition) /*-{
        var editor = this.@org.uberfire.ext.widgets.common.client.ace.AceEditor::editor;
        return editor.getSession().getDocument().positionToIndex(jsPosition);
    }-*/;

    /**
     * Gets a document position from a supplied zero-based index.
     * @param index (base zero)
     * @return A position object showing the row and column of the supplied index in the document
     */
    public native AceEditorCursorPosition getPositionFromIndex(int index) /*-{
        var editor = this.@org.uberfire.ext.widgets.common.client.ace.AceEditor::editor;
        var jsPosition = editor.getSession().getDocument().indexToPosition(index);
        return @org.uberfire.ext.widgets.common.client.ace.AceEditorCursorPosition::create(II)(
                jsPosition.row,
                jsPosition.column
        );
    }-*/;

    /**
     * Set whether or not soft tabs should be used.
     * @param useSoftTabs true if soft tabs should be used, false otherwise
     */
    public native void setUseSoftTabs(boolean useSoftTabs) /*-{
        var editor = this.@org.uberfire.ext.widgets.common.client.ace.AceEditor::editor;
        editor.getSession().setUseSoftTabs(useSoftTabs);
    }-*/;

    /**
     * Set tab size.  (Default is 4.)
     * @param tabSize the tab size to set
     */
    public native void setTabSize(int tabSize) /*-{
        var editor = this.@org.uberfire.ext.widgets.common.client.ace.AceEditor::editor;
        editor.getSession().setTabSize(tabSize);
    }-*/;

    /**
     * Go to given line.
     * @param line the line to go to
     */
    public native void gotoLine(int line) /*-{
        var editor = this.@org.uberfire.ext.widgets.common.client.ace.AceEditor::editor;
        editor.gotoLine(line);
    }-*/;

    /**
     * Go to given line.
     * @param line the line to go to
     */
    public native void scrollToLine(int line) /*-{
        var editor = this.@org.uberfire.ext.widgets.common.client.ace.AceEditor::editor;
        editor.resize(true);

        editor.scrollToLine(line, true, true, function () {
        });
    }-*/;

    /**
     * Set whether or not the horizontal scrollbar is always visible.
     * @param hScrollBarAlwaysVisible true if the horizontal scrollbar is always
     * visible, false if it is hidden when not needed
     */
    public native void setHScrollBarAlwaysVisible(boolean hScrollBarAlwaysVisible) /*-{
        var editor = this.@org.uberfire.ext.widgets.common.client.ace.AceEditor::editor;
        editor.renderer.setHScrollBarAlwaysVisible(hScrollBarAlwaysVisible);
    }-*/;

    /**
     * Set whether or not the gutter is shown.
     * @param showGutter true if the gutter should be shown, false if it should be hidden
     */
    public native void setShowGutter(boolean showGutter) /*-{
        var editor = this.@org.uberfire.ext.widgets.common.client.ace.AceEditor::editor;
        editor.renderer.setShowGutter(showGutter);
    }-*/;

    /**
     * Set or unset read-only mode.
     * @param readOnly true if editor should be set to readonly, false if the
     * editor should be set to read-write
     */
    public native void setReadOnly(boolean readOnly) /*-{
        var editor = this.@org.uberfire.ext.widgets.common.client.ace.AceEditor::editor;
        editor.setReadOnly(readOnly);
    }-*/;

    /**
     * Set or unset highlighting of currently selected word.
     * @param highlightSelectedWord true to highlight currently selected word, false otherwise
     */
    public native void setHighlightSelectedWord(boolean highlightSelectedWord) /*-{
        var editor = this.@org.uberfire.ext.widgets.common.client.ace.AceEditor::editor;
        editor.setHighlightSelectedWord(highlightSelectedWord);
    }-*/;

    /**
     * Set or unset the visibility of the print margin.
     * @param showPrintMargin true if the print margin should be shown, false otherwise
     */
    public native void setShowPrintMargin(boolean showPrintMargin) /*-{
        var editor = this.@org.uberfire.ext.widgets.common.client.ace.AceEditor::editor;
        editor.renderer.setShowPrintMargin(showPrintMargin);
    }-*/;

    /**
     * Add an annotation to a the local annotations JsArray<AceAnnotation>, but does not set it on the editor
     * @param row to which the annotation should be added
     * @param column to which the annotation applies
     * @param text to display as a tooltip with the annotation
     * @param type to be displayed (one of the values in the
     * {@link AceAnnotationType} enumeration)
     */
    public void addAnnotation(final int row,
                              final int column,
                              final String text,
                              final AceAnnotationType type) {
        annotations.push(AceAnnotation.create(row,
                                              column,
                                              text,
                                              type.getName()));
    }

    /**
     * Set any annotations which have been added via addAnnotation on the editor
     */
    public native void setAnnotations() /*-{
        var editor = this.@org.uberfire.ext.widgets.common.client.ace.AceEditor::editor;
        var annotations = this.@org.uberfire.ext.widgets.common.client.ace.AceEditor::annotations;
        editor.getSession().setAnnotations(annotations);
    }-*/;

    /**
     * Clear any annotations from the editor and reset the local annotations JsArray<AceAnnotation>
     */
    public native void clearAnnotations() /*-{
        var editor = this.@org.uberfire.ext.widgets.common.client.ace.AceEditor::editor;
        editor.getSession().clearAnnotations();
        this.@org.uberfire.ext.widgets.common.client.ace.AceEditor::resetAnnotations()();
    }-*/;

    /**
     * Reset any annotations in the local annotations JsArray<AceAnnotation>
     */
    private void resetAnnotations() {
        annotations = JavaScriptObject.createArray().cast();
    }

    /**
     * Remove a command from the editor.
     * @param command the command (one of the values in the
     * {@link AceCommand} enumeration)
     */
    public void removeCommand(final AceCommand command) {
        removeCommandByName(command.getName());
    }

    /**
     * Remove commands, that may not be required, from the editor
     * @param command to be removed, one of
     * "gotoline", "findnext", "findprevious", "find", "replace", "replaceall"
     */
    public native void removeCommandByName(String command) /*-{
        var editor = this.@org.uberfire.ext.widgets.common.client.ace.AceEditor::editor;
        editor.commands.removeCommand(command);
    }-*/;

    /**
     * Set whether to use wrap mode or not
     * @param useWrapMode true if word wrap should be used, false otherwise
     */
    public native void setUseWrapMode(boolean useWrapMode) /*-{
        var editor = this.@org.uberfire.ext.widgets.common.client.ace.AceEditor::editor;
        editor.getSession().setUseWrapMode(useWrapMode);
    }-*/;

    /* (non-Javadoc)
     * @see com.google.gwt.user.client.ui.ResizeComposite#onResize()
     */
    @Override
    public void onResize() {
        redisplay();
    }

    @Override
    public String getValue() {
        return this.getText();
    }

    @Override
    public void setValue(String value) {
        this.setText(value);
    }

    /**
     * Set whether or not autocomplete is enabled.
     * @param b true if autocomplete should be enabled, false if not
     */
    public native void setAutocompleteEnabled(boolean b) /*-{
        // See: https://github.com/ajaxorg/ace/wiki/How-to-enable-Autocomplete-in-the-Ace-editor
        var editor = this.@org.uberfire.ext.widgets.common.client.ace.AceEditor::editor;
        if (b) {
            $wnd.ace.require("ace/ext/language_tools");
            editor.setOptions({enableBasicAutocompletion: true});
        } else {
            editor.setOptions({enableBasicAutocompletion: false});
        }
    }-*/;

    public native void setFocus()  /*-{
        var editor = this.@org.uberfire.ext.widgets.common.client.ace.AceEditor::editor;
        editor.focus();
    }-*/;
}


text:
/**
 * ColumnDefinitions
 *
 * Reference: http://dev.mysql.com/doc/refman/5.7/en/data-type-overview.html
 */
'use strict';

const ColumnDefinition = require('./ColumnDefinition');
const GeometryColumnDefinition = require('./GeometryColumnDefinition');
const NumericColumnDefinition = require('./NumericColumnDefinition');
const TextColumnDefinition = require('./TextColumnDefinition');
const TimestampColumnDefinition = require('./TimestampColumnDefinition');
const UpdatableTimeColumnDefinition = require('./UpdatableTimeColumnDefinition');

const ColumnDefinitions = {
  tinyint(m) {
    return new NumericColumnDefinition('tinyint', m);
  },
  smallint(m) {
    return new NumericColumnDefinition('smallint', m);
  },
  mediumint(m) {
    return new NumericColumnDefinition('mediumint', m);
  },
  int(m) {
    return new NumericColumnDefinition('int', m);
  },
  integer(m) {
    return new NumericColumnDefinition('int', m);
  },
  bigint(m) {
    return new NumericColumnDefinition('bigint', m);
  },
  float(m, d) {
    return new NumericColumnDefinition('float', m, d);
  },
  double(m, d) {
    return new NumericColumnDefinition('double', m, d);
  },
  decimal(m, d) {
    return new NumericColumnDefinition('decimal', m, d);
  },
  dec(m, d) {
    return new NumericColumnDefinition('decimal', m, d);
  },
  numeric(m, d) {
    return new NumericColumnDefinition('decimal', m, d);
  },
  fixed(m, d) {
    return new NumericColumnDefinition('decimal', m, d);
  },
  bit(m) {
    return new ColumnDefinition('bit', m);
  },
  bool() {
    return new NumericColumnDefinition('tinyint', 1);
  },
  boolean() {
    return new NumericColumnDefinition('tinyint', 1);
  },
  date() {
    return new ColumnDefinition('date');
  },
  datetime(m) {
    return new UpdatableTimeColumnDefinition('datetime', m);
  },
  timestamp(m) {
    return new TimestampColumnDefinition(m);
  },
  time(m) {
    return new ColumnDefinition('time', m);
  },
  year() {
    return new ColumnDefinition('year');
  },
  char(m) {
    return new TextColumnDefinition('char', m);
  },
  varchar(m) {
    if (m === undefined) {
      throw new Error('The varchar `m` argument must be specified');
    }
    return new TextColumnDefinition('varchar', m);
  },
  text(m) {
    return new TextColumnDefinition('text', m);
  },
  tinytext() {
    return new TextColumnDefinition('tinytext');
  },
  mediumtext() {
    return new TextColumnDefinition('mediumtext');
  },
  longtext() {
    return new TextColumnDefinition('longtext');
  },
  binary(m) {
    return new ColumnDefinition('binary', m);
  },
  varbinary(m) {
    if (m === undefined) {
      throw new Error('The varbinary `m` argument must be specified');
    }
    return new ColumnDefinition('varbinary', m);
  },
  blob(m) {
    return new ColumnDefinition('blob', m);
  },
  tinyblob() {
    return new ColumnDefinition('tinyblob');
  },
  mediumblob() {
    return new ColumnDefinition('mediumblob');
  },
  longblob() {
    return new ColumnDefinition('longblob');
  },
  enum(...values) {
    if (values.length === 0) {
      throw new Error('At least one enum value must be provided');
    }
    return new TextColumnDefinition('enum', values);
  },
  set(...values) {
    if (values.length === 0) {
      throw new Error('At least one set value must be provided');
    }
    return new TextColumnDefinition('set', values);
  },
  json() {
    return new ColumnDefinition('json');
  },
  geometry() {
    return new GeometryColumnDefinition('geometry');
  },
  point() {
    return new GeometryColumnDefinition('point');
  },
  linestring() {
    return new GeometryColumnDefinition('linestring');
  },
  polygon() {
    return new GeometryColumnDefinition('polygon');
  },
  multipoint() {
    return new GeometryColumnDefinition('multipoint');
  },
  multilinestring() {
    return new GeometryColumnDefinition('multilinestring');
  },
  multipolygon() {
    return new GeometryColumnDefinition('multipolygon');
  },
  geometrycollection() {
    return new GeometryColumnDefinition('geometrycollection');
  },
};

module.exports = ColumnDefinitions;


text:
setup_blue_green = false

remote_file '/usr/local/bin/jb-server' do
  source format(
    node['travis_jupiter_brain']['base_url'],
    node['travis_jupiter_brain']['version']
  )
  checksum node['travis_jupiter_brain']['checksum']
  owner 'root'
  group 'root'
  mode '755'
end

Array(node['travis_jupiter_brain']['instances']).each do |instance|
  setup_blue_green = true if instance['blue_green']

  template "/etc/init/#{instance['service_name']}.conf" do
    source 'upstart.conf.erb'
    owner 'root'
    group 'root'
    mode '644'
    variables instance
  end

  template "/etc/default/#{instance['service_name']}" do
    source 'etc-default.erb'
    owner 'root'
    group 'root'
    mode '644'
    variables instance
  end

  %w(blue green).each do |color|
    file "/etc/default/#{instance['service_name']}-#{color}" do
      content "# Managed by Chef\nexport JUPITER_BRAIN_ADDR='#{instance["#{color}_addr"]}'\n"
      owner 'root'
      group 'root'
      mode '644'
      only_if { instance['blue_green'] && instance["#{color}_addr"] }
    end
  end

  haproxy_lb instance['service_name'] do
    type 'frontend'
    params(
      'maxconn' => 200,
      'bind' => instance['frontend_bind'],
      'default_backend' => "servers-#{instance['service_name']}"
    )

    only_if { instance['blue_green'] && instance['frontend_bind'] }
  end

  backend_servers = %w(blue green).map do |color|
    addr = instance["#{color}_addr"]
    addr = "127.0.0.1#{addr}" if addr =~ /^:/
    "#{color} #{addr} weight 1 maxconn 100 check"
  end

  haproxy_lb "servers-#{instance['service_name']}" do
    type 'backend'
    mode 'http'
    servers backend_servers

    only_if { instance['blue_green'] && instance['blue_addr'] && instance['green_addr'] }
  end
end

include_recipe 'haproxy::default' if setup_blue_green
include_recipe 'haproxy::install_package' if setup_blue_green


text:
'''OpenGL extension ARB.viewport_array

Automatically generated by the get_gl_extensions script, do not edit!
'''
from OpenGL import platform, constants, constant, arrays
from OpenGL import extensions
from OpenGL.GL import glget
import ctypes
EXTENSION_NAME = 'GL_ARB_viewport_array'
_DEPRECATED = False
GL_MAX_VIEWPORTS = constant.Constant( 'GL_MAX_VIEWPORTS', 0x825B )
GL_VIEWPORT_SUBPIXEL_BITS = constant.Constant( 'GL_VIEWPORT_SUBPIXEL_BITS', 0x825C )
GL_VIEWPORT_BOUNDS_RANGE = constant.Constant( 'GL_VIEWPORT_BOUNDS_RANGE', 0x825D )
GL_LAYER_PROVOKING_VERTEX = constant.Constant( 'GL_LAYER_PROVOKING_VERTEX', 0x825E )
GL_VIEWPORT_INDEX_PROVOKING_VERTEX = constant.Constant( 'GL_VIEWPORT_INDEX_PROVOKING_VERTEX', 0x825F )
GL_UNDEFINED_VERTEX = constant.Constant( 'GL_UNDEFINED_VERTEX', 0x8260 )
glViewportArrayv = platform.createExtensionFunction(
'glViewportArrayv',dll=platform.GL,
extension=EXTENSION_NAME,
resultType=None,
argTypes=(constants.GLuint,constants.GLsizei,arrays.GLfloatArray,),
doc='glViewportArrayv(GLuint(first), GLsizei(count), GLfloatArray(v)) -> None',
argNames=('first','count','v',),
deprecated=_DEPRECATED,
)

glViewportIndexedf = platform.createExtensionFunction(
'glViewportIndexedf',dll=platform.GL,
extension=EXTENSION_NAME,
resultType=None,
argTypes=(constants.GLuint,constants.GLfloat,constants.GLfloat,constants.GLfloat,constants.GLfloat,),
doc='glViewportIndexedf(GLuint(index), GLfloat(x), GLfloat(y), GLfloat(w), GLfloat(h)) -> None',
argNames=('index','x','y','w','h',),
deprecated=_DEPRECATED,
)

glViewportIndexedfv = platform.createExtensionFunction(
'glViewportIndexedfv',dll=platform.GL,
extension=EXTENSION_NAME,
resultType=None,
argTypes=(constants.GLuint,arrays.GLfloatArray,),
doc='glViewportIndexedfv(GLuint(index), GLfloatArray(v)) -> None',
argNames=('index','v',),
deprecated=_DEPRECATED,
)

glScissorArrayv = platform.createExtensionFunction(
'glScissorArrayv',dll=platform.GL,
extension=EXTENSION_NAME,
resultType=None,
argTypes=(constants.GLuint,constants.GLsizei,arrays.GLintArray,),
doc='glScissorArrayv(GLuint(first), GLsizei(count), GLintArray(v)) -> None',
argNames=('first','count','v',),
deprecated=_DEPRECATED,
)

glScissorIndexed = platform.createExtensionFunction(
'glScissorIndexed',dll=platform.GL,
extension=EXTENSION_NAME,
resultType=None,
argTypes=(constants.GLuint,constants.GLint,constants.GLint,constants.GLsizei,constants.GLsizei,),
doc='glScissorIndexed(GLuint(index), GLint(left), GLint(bottom), GLsizei(width), GLsizei(height)) -> None',
argNames=('index','left','bottom','width','height',),
deprecated=_DEPRECATED,
)

glScissorIndexedv = platform.createExtensionFunction(
'glScissorIndexedv',dll=platform.GL,
extension=EXTENSION_NAME,
resultType=None,
argTypes=(constants.GLuint,arrays.GLintArray,),
doc='glScissorIndexedv(GLuint(index), GLintArray(v)) -> None',
argNames=('index','v',),
deprecated=_DEPRECATED,
)

glDepthRangeArrayv = platform.createExtensionFunction(
'glDepthRangeArrayv',dll=platform.GL,
extension=EXTENSION_NAME,
resultType=None,
argTypes=(constants.GLuint,constants.GLsizei,ctypes.POINTER(constants.GLclampd),),
doc='glDepthRangeArrayv(GLuint(first), GLsizei(count), POINTER(constants.GLclampd)(v)) -> None',
argNames=('first','count','v',),
deprecated=_DEPRECATED,
)

glDepthRangeIndexed = platform.createExtensionFunction(
'glDepthRangeIndexed',dll=platform.GL,
extension=EXTENSION_NAME,
resultType=None,
argTypes=(constants.GLuint,constants.GLclampd,constants.GLclampd,),
doc='glDepthRangeIndexed(GLuint(index), GLclampd(n), GLclampd(f)) -> None',
argNames=('index','n','f',),
deprecated=_DEPRECATED,
)

glGetFloati_v = platform.createExtensionFunction(
'glGetFloati_v',dll=platform.GL,
extension=EXTENSION_NAME,
resultType=None,
argTypes=(constants.GLenum,constants.GLuint,arrays.GLfloatArray,),
doc='glGetFloati_v(GLenum(target), GLuint(index), GLfloatArray(data)) -> None',
argNames=('target','index','data',),
deprecated=_DEPRECATED,
)

glGetDoublei_v = platform.createExtensionFunction(
'glGetDoublei_v',dll=platform.GL,
extension=EXTENSION_NAME,
resultType=None,
argTypes=(constants.GLenum,constants.GLuint,arrays.GLdoubleArray,),
doc='glGetDoublei_v(GLenum(target), GLuint(index), GLdoubleArray(data)) -> None',
argNames=('target','index','data',),
deprecated=_DEPRECATED,
)

def glInitViewportArrayARB():
    '''Return boolean indicating whether this extension is available'''
    return extensions.hasGLExtension( EXTENSION_NAME )


text:
'use strict';

var url = require('url');
var User = require('./UserService');

module.exports.findUsers = function findUsers (req, res, next) {
  User.findUsers(req.swagger.params, res, next);
};

module.exports.createUser = function createUser (req, res, next) {
  User.createUser(req.swagger.params, res, next);
};

module.exports.authenticateUser = function authenticateUser (req, res, next) {
  User.authenticateUser(req.swagger.params, res, next);
};

module.exports.registerUser = function registerUser (req, res, next) {
  User.registerUser(req.swagger.params, res, next);
};

module.exports.findUserById = function findUserById (req, res, next) {
  User.findUserById(req.swagger.params, res, next);
};

module.exports.countUsers = function countUsers (req, res, next) {
  User.countUsers(req.swagger.params, res, next);
};

module.exports.updateUser = function updateUser (req, res, next) {
  User.updateUser(req.swagger.params, res, next);
};

module.exports.deleteUser = function deleteUser (req, res, next) {
  User.deleteUser(req.swagger.params, res, next);
};

module.exports.getUserBalance = function getUserBalance (req, res, next) {
  User.getUserBalance(req.swagger.params, res, next);
};

module.exports.getUserRights = function getUserRights (req, res, next) {
  User.getUserRights(req.swagger.params, res, next);
};


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

Prompt for Wed Mar 9. Networks.

	<button id="sample">Sample</button>


text:
using System;

namespace JetBrains.Annotations
{
    [AttributeUsage(
        AttributeTargets.Parameter | AttributeTargets.Field |
        AttributeTargets.Property, Inherited = true)]
    internal sealed class HtmlAttributeValueAttribute : Attribute
    {
        #region Ñâîéñòâà

        [NotNull]
        public string Name { get; private set; }

        #endregion

        #region Êîíñòðóêòîð

        public HtmlAttributeValueAttribute([NotNull] string name)
        {
            Name = name;
        }

        #endregion
    }
}


text:
namespace extensions {

using IncognitoManifestKeys = api::incognito::ManifestKeys;

IncognitoInfo::IncognitoInfo(api::incognito::IncognitoMode mode) : mode(mode) {
  DCHECK_NE(api::incognito::INCOGNITO_MODE_NONE, mode);
}

IncognitoInfo::~IncognitoInfo() = default;

// static
bool IncognitoInfo::IsSplitMode(const Extension* extension) {
  IncognitoInfo* info = static_cast<IncognitoInfo*>(
      extension->GetManifestData(IncognitoManifestKeys::kIncognito));
  return info ? info->mode == api::incognito::INCOGNITO_MODE_SPLIT : false;
}

// static
bool IncognitoInfo::IsIncognitoAllowed(const Extension* extension) {
  IncognitoInfo* info = static_cast<IncognitoInfo*>(
      extension->GetManifestData(IncognitoManifestKeys::kIncognito));
  return info ? info->mode != api::incognito::INCOGNITO_MODE_NOT_ALLOWED : true;
}

IncognitoHandler::IncognitoHandler() = default;
IncognitoHandler::~IncognitoHandler() = default;

bool IncognitoHandler::Parse(Extension* extension, std::u16string* error) {
  IncognitoManifestKeys manifest_keys;
  if (!IncognitoManifestKeys::ParseFromDictionary(
          extension->manifest()->available_values().GetDict(), &manifest_keys,
          error)) {
    return false;
  }

  api::incognito::IncognitoMode mode = manifest_keys.incognito;

  // This will be the case if the manifest key was omitted.
  if (mode == api::incognito::INCOGNITO_MODE_NONE) {
    // Extensions and Chrome apps default to spanning mode. Hosted and legacy
    // packaged apps default to split mode.
    mode = extension->is_hosted_app() || extension->is_legacy_packaged_app()
               ? api::incognito::INCOGNITO_MODE_SPLIT
               : api::incognito::INCOGNITO_MODE_SPANNING;
  }

  extension->SetManifestData(IncognitoManifestKeys::kIncognito,
                             std::make_unique<IncognitoInfo>(mode));
  return true;
}

bool IncognitoHandler::AlwaysParseForType(Manifest::Type type) const {
  return true;
}

base::span<const char* const> IncognitoHandler::Keys() const {
  static constexpr const char* kKeys[] = {IncognitoManifestKeys::kIncognito};
  return kKeys;
}

}  // namespace extensions


text:
module Factory
  class Factory
    def self.new(*variables_names, &block)
      obj = Class.new do

        define_method :initialize do |*fields|
          variables_names.each_with_index do |variable_name, index|
            instance_variable_set(:"@#{variable_name}", fields[index])
          end
        end

        variables_names.each { |var_name| attr_reader var_name}

        if block_given?
          class_eval(&block)
        end

        def [](index)
          if index.instance_of? Fixnum
            instance_variable_get(instance_variables[index])
          else
            self.send(index)
          end
        end
      end

      obj
    end
  end
end


text:
"""
{docstring}
"""

{script}

### WebAPI ###

from scrypture import webapi
class WebAPI(webapi.WebAPI):
    input_text = webapi.text_input('Input')
    submit_button = webapi.submit_button('Run')

    def run(self, form_input):
        input_text = form_input['input_text']
        timestamps = form_input['timestamps']
        if type(timestamps) != list:
            timestamps = timestamps.split('\n')
        timestamps = [t.strip() for t in timestamps]

        output = (input_text)

        return {'output_type' : 'simple',
                'output' : output}


text:
<?php

/* SdzBlogBundle:Blog:menu.html.twig */
class __TwigTemplate_cf0462bafa1941d8da4d2d20da7c04e2b335aa1b952e657bcf2da60f29feb404 extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        $this->parent = false;

        $this->blocks = array(
        );
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        // line 2
        echo "
Les derniers articles

  ";
        // line 4
        $context['_parent'] = (array) $context;
        $context['_seq'] = twig_ensure_traversable($this->getContext($context, "liste_articles"));
        foreach ($context['_seq'] as $context["_key"] => $context["article"]) {
            // line 5
            echo "
env, $this->env->getExtension('routing')->getPath("sdzblog_voir", array("id" => $this->getAttribute($this->getContext($context, "article"), "id"))), "html", null, true);
            echo "\">";
            echo twig_escape_filter($this->env, $this->getAttribute($this->getContext($context, "article"), "titre"), "html", null, true);
            echo "

  ";
        }
        $_parent = $context['_parent'];
        unset($context['_seq'], $context['_iterated'], $context['_key'], $context['article'], $context['_parent'], $context['loop']);
        $context = array_intersect_key($context, $_parent) + $_parent;
        // line 7
        echo "

";
    }

    public function getTemplateName()
    {
        return "SdzBlogBundle:Blog:menu.html.twig";
    }

    public function isTraitable()
    {
        return false;
    }

    public function getDebugInfo()
    {
        return array (  38 => 7,  27 => 5,  23 => 4,  19 => 2,  79 => 18,  72 => 16,  64 => 13,  60 => 12,  54 => 11,  51 => 10,  46 => 9,  42 => 7,  39 => 6,  32 => 4,  29 => 3,);
    }
}


text:
<?php

namespace Google\Service\YouTube;

class ChannelStatistics extends \Google\Model
{
  /**
   * @var string
   */
  public $commentCount;
  /**
   * @var bool
   */
  public $hiddenSubscriberCount;
  /**
   * @var string
   */
  public $subscriberCount;
  /**
   * @var string
   */
  public $videoCount;
  /**
   * @var string
   */
  public $viewCount;

  /**
   * @param string
   */
  public function setCommentCount($commentCount)
  {
    $this->commentCount = $commentCount;
  }
  /**
   * @return string
   */
  public function getCommentCount()
  {
    return $this->commentCount;
  }
  /**
   * @param bool
   */
  public function setHiddenSubscriberCount($hiddenSubscriberCount)
  {
    $this->hiddenSubscriberCount = $hiddenSubscriberCount;
  }
  /**
   * @return bool
   */
  public function getHiddenSubscriberCount()
  {
    return $this->hiddenSubscriberCount;
  }
  /**
   * @param string
   */
  public function setSubscriberCount($subscriberCount)
  {
    $this->subscriberCount = $subscriberCount;
  }
  /**
   * @return string
   */
  public function getSubscriberCount()
  {
    return $this->subscriberCount;
  }
  /**
   * @param string
   */
  public function setVideoCount($videoCount)
  {
    $this->videoCount = $videoCount;
  }
  /**
   * @return string
   */
  public function getVideoCount()
  {
    return $this->videoCount;
  }
  /**
   * @param string
   */
  public function setViewCount($viewCount)
  {
    $this->viewCount = $viewCount;
  }
  /**
   * @return string
   */
  public function getViewCount()
  {
    return $this->viewCount;
  }
}

// Adding a class alias for backwards compatibility with the previous class name.
class_alias(ChannelStatistics::class, 'Google_Service_YouTube_ChannelStatistics');


text:
id: concepts-clients
title: Pulsar Clients
sidebar_label: "Clients"
original_id: concepts-clients
---

Pulsar exposes a client API with language bindings for [Java](client-libraries-java.md),  [Go](client-libraries-go.md), [Python](client-libraries-python.md), [C++](client-libraries-cpp.md) and [C#](client-libraries-dotnet). The client API optimizes and encapsulates Pulsar's client-broker communication protocol and exposes a simple and intuitive API for use by applications.

Under the hood, the current official Pulsar client libraries support transparent reconnection and/or connection failover to brokers, queuing of messages until acknowledged by the broker, and heuristics such as connection retries with backoff.

> #### Custom client libraries
> If you'd like to create your own client library, we recommend consulting the documentation on Pulsar's custom [binary protocol](developing-binary-protocol.md)

## Client setup phase

When an application wants to create a producer/consumer, the Pulsar client library will initiate a setup phase that is composed of two steps:

1. The client will attempt to determine the owner of the topic by sending an HTTP lookup request to the broker. The request could reach one of the active brokers which, by looking at the (cached) zookeeper metadata will know who is serving the topic or, in case nobody is serving it, will try to assign it to the least loaded broker.
1. Once the client library has the broker address, it will create a TCP connection (or reuse an existing connection from the pool) and authenticate it. Within this connection, client and broker exchange binary commands from a custom protocol. At this point the client will send a command to create producer/consumer to the broker, which will comply after having validated the authorization policy.

Whenever the TCP connection breaks, the client will immediately re-initiate this setup phase and will keep trying with exponential backoff to re-establish the producer or consumer until the operation succeeds.

## Reader interface

In Pulsar, the "standard" [consumer interface](concepts-messaging.md#consumers) involves using consumers to listen on [topics](reference-terminology.md#topic), process incoming messages, and finally acknowledge those messages when they've been processed.  Whenever a new subscription is created, it is initially positioned at the end of the topic (by default), and consumers associated with that subscription will begin reading with the first message created afterwards.  Whenever a consumer connects to a topic using a pre-existing subscription, it begins reading from the earliest message un-acked within that subscription.  In summary, with the consumer interface, subscription cursors are automatically managed by Pulsar in response to [message acknowledgements](concepts-messaging.md#acknowledgement).

The **reader interface** for Pulsar enables applications to manually manage cursors. When you use a reader to connect to a topic---rather than a consumer---you need to specify *which* message the reader begins reading from when it connects to a topic. When connecting to a topic, the reader interface enables you to begin with:

* The **earliest** available message in the topic
* The **latest** available message in the topic
* Some other message between the earliest and the latest. If you select this option, you'll need to explicitly provide a message ID. Your application will be responsible for "knowing" this message ID in advance, perhaps fetching it from a persistent data store or cache.

The reader interface is helpful for use cases like using Pulsar to provide [effectively-once](https://streaml.io/blog/exactly-once/) processing semantics for a stream processing system. For this use case, it's essential that the stream processing system be able to "rewind" topics to a specific message and begin reading there. The reader interface provides Pulsar clients with the low-level abstraction necessary to "manually position" themselves within a topic.

Internally, the reader interface is implemented as a consumer using an exclusive, non-durable subscription to the topic with a randomly-allocated name.

[ **IMPORTANT** ]

Unlike subscription/consumer, readers are non-durable in nature and will not prevent data in a topic from being deleted, thus it is ***strongly*** advised that [data retention](cookbooks-retention-expiry) be configured.   If data retention for a topic is not configured for an adequate amount of time, messages that the reader has not yet read might be deleted .  This will cause readers to essentially skip messages.  Configuring the data retention for a topic guarantees the reader with have a certain duration to read a message.

Please also note that a reader can have a "backlog", but the metric is just to allow users to know how behind the reader is and is not considered for any backlog quota calculations.

![The Pulsar consumer and reader interfaces](/assets/pulsar-reader-consumer-interfaces.png)

> ### Non-partitioned topics only
> The reader interface for Pulsar cannot currently be used with [partitioned topics](concepts-messaging.md#partitioned-topics).

Here's a Java example that begins reading from the earliest available message on a topic:

```java

import org.apache.pulsar.client.api.Message;
import org.apache.pulsar.client.api.MessageId;
import org.apache.pulsar.client.api.Reader;

// Create a reader on a topic and for a specific message (and onward)
Reader<byte[]> reader = pulsarClient.newReader()
    .topic("reader-api-test")
    .startMessageId(MessageId.earliest)
    .create();

while (true) {
    Message message = reader.readNext();

    // Process the message
}

```

To create a reader that will read from the latest available message:

```java

Reader<byte[]> reader = pulsarClient.newReader()
    .topic(topic)
    .startMessageId(MessageId.latest)
    .create();

```

To create a reader that will read from some message between earliest and latest:

```java

byte[] msgIdBytes = // Some byte array
MessageId id = MessageId.fromByteArray(msgIdBytes);
Reader<byte[]> reader = pulsarClient.newReader()
    .topic(topic)
    .startMessageId(id)
    .create();

```


text:
require File.dirname(__FILE__) + '/../spec_helper'

describe StoriesIndexPresenter, '::VIEWS' do
  it "contains 'iterations' and 'tags" do
    StoriesIndexPresenter::VIEWS == ['iterations', 'tags']
  end
end

describe StoriesIndexPresenter, "#view" do
  describe "when the passed in :view is in the ::VIEWS list" do
    it "returns the passed in view" do
      StoriesIndexPresenter::VIEWS.each do |view|
        StoriesIndexPresenter.new(:view => view).view.should == view
      end
    end
  end

  describe "when the passed in :view is not in the ::VIEWS list" do
    it "returns 'iterations'" do
      ["foo", "baz", "bar"].each do |view|
        StoriesIndexPresenter.new(:view => view).view.should == 'iterations'
      end
    end
  end
end

describe StoriesIndexPresenter, '#iterations?' do
  it "returns true when #view returns 'iterations'" do
    StoriesIndexPresenter.new(:view => 'iterations').iterations?.should be_true
  end

  it "returns false otherwise" do
    StoriesIndexPresenter.new(:view => 'tags').iterations?.should be_false
  end
end

describe StoriesIndexPresenter, '#tags?' do
  it "returns true when #view returns 'tags'" do
    StoriesIndexPresenter.new(:view => 'tags').tags?.should be_true
  end

  it "returns false otherwise" do
    StoriesIndexPresenter.new(:view => 'iterations').tags?.should be_false
  end
end

describe StoriesIndexPresenter, '#iteration' do
  it "defaults to recent" do
    presenter = StoriesIndexPresenter.new
    presenter.iteration.should == "recent"
  end

  it "is set by the search parameter" do
    presenter = StoriesIndexPresenter.new :search => { :iteration => "all" }
    presenter.iteration.should == "all"
  end
end

describe StoriesIndexPresenter, "#stories" do
  before do
    @stories = stub("stories", :search => [])
    @project = stub("project", :stories => @stories)
    @presenter = StoriesIndexPresenter.new :project => @project, :search => { :text => "ruby" }
  end

  it "finds all stories for the search criteria" do
    @project.should_receive(:stories).and_return(@stories)
    @stories.should_receive(:search).with(:iteration => "recent", :text => "ruby").and_return([])
    @presenter.stories
  end
end

describe StoriesIndexPresenter, '#iterations' do
  before do
    @stories = stub("stories", :search => [])
    @project = stub("project", :stories => @stories)
    @presenter = StoriesIndexPresenter.new :project => @project
    IterationsPresenter.stub!(:new)
  end

  it "creates a new IterationsPresenter" do
    IterationsPresenter.should_receive(:new).with(
      :stories => [],
      :project => @project)
    @presenter.iterations
  end

  it "returns the newly created iterations" do
    iterations = stub("iterations presenter")
    IterationsPresenter.stub!(:new).and_return(iterations)
    @presenter.iterations.should == iterations
  end

  it "caches the return value for subsequent calls" do
    IterationsPresenter.should_receive(:new).once.and_return(:foo)
    @presenter.iterations.should == :foo
    @presenter.iterations.should == :foo
  end
end

describe StoriesIndexPresenter, '#tags' do
  before do
    @tags = stub("tags")
    @stories = stub("tagless stories")
    @project = stub("project", :story_tags => @tags)
    @presenter = StoriesIndexPresenter.new :project => @project
    StoryTagsPresenter.stub!(:new)
  end

  it "finds all tags that belong to the project" do
    @project.should_receive(:story_tags).and_return(@tags)
    @presenter.tags
  end

  it "creates a new StoryTagsPresenter" do
    @project.stub!(:story_tags).and_return(@tags)
    StoryTagsPresenter.should_receive(:new).with(
      :tags => @tags,
      :project => @project)
    @presenter.tags
  end

  it "caches the return value for subsequent calls" do
    StoryTagsPresenter.stub!(:new).once.and_return(:foo)
    @presenter.tags.should == :foo
    @presenter.tags.should == :foo
  end

end