text:
/* ssl/s2_pkt.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
 * All rights reserved.
 *
 * This package is an SSL implementation written
 * by Eric Young (eay@cryptsoft.com).
 * The implementation was written so as to conform with Netscapes SSL.
 *
 * This library is free for commercial and non-commercial use as long as
 * the following conditions are aheared to.  The following conditions
 * apply to all code found in this distribution, be it the RC4, RSA,
 * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
 * included with this distribution is covered by the same copyright terms
 * except that the holder is Tim Hudson (tjh@cryptsoft.com).
 *
 * Copyright remains Eric Young's, and as such any Copyright notices in
 * the code are not to be removed.
 * If this package is used in a product, Eric Young should be given attribution
 * as the author of the parts of the library used.
 * This can be in the form of a textual message at program startup or
 * in documentation (online or textual) provided with the package.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *    "This product includes cryptographic software written by
 *     Eric Young (eay@cryptsoft.com)"
 *    The word 'cryptographic' can be left out if the rouines from the library
 *    being used are not cryptographic related :-).
 * 4. If you include any Windows specific code (or a derivative thereof) from
 *    the apps directory (application code) you must include an acknowledgement:
 *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
 *
 * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 * The licence and distribution terms for any publically available version or
 * derivative of this code cannot be changed.  i.e. this code cannot simply be
 * copied and put under another distribution licence
 * [including the GNU Public Licence.]
 */
/* ====================================================================
 * Copyright (c) 1998-2001 The OpenSSL Project.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. All advertising materials mentioning features or use of this
 *    software must display the following acknowledgment:
 *    "This product includes software developed by the OpenSSL Project
 *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
 *
 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
 *    endorse or promote products derived from this software without
 *    prior written permission. For written permission, please contact
 *    openssl-core@openssl.org.
 *
 * 5. Products derived from this software may not be called "OpenSSL"
 *    nor may "OpenSSL" appear in their names without prior written
 *    permission of the OpenSSL Project.
 *
 * 6. Redistributions of any form whatsoever must retain the following
 *    acknowledgment:
 *    "This product includes software developed by the OpenSSL Project
 *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
 *
 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 * ====================================================================
 *
 * This product includes cryptographic software written by Eric Young
 * (eay@cryptsoft.com).  This product includes software written by Tim
 * Hudson (tjh@cryptsoft.com).
 *
 */

#include "ssl_locl.h"
#ifndef OPENSSL_NO_SSL2
# include <stdio.h>
# include <errno.h>
# define USE_SOCKETS

static int read_n(SSL *s, unsigned int n, unsigned int max,
                  unsigned int extend);
static int do_ssl_write(SSL *s, const unsigned char *buf, unsigned int len);
static int write_pending(SSL *s, const unsigned char *buf, unsigned int len);
static int ssl_mt_error(int n);

/*
 * SSL 2.0 imlementation for SSL_read/SSL_peek - This routine will return 0
 * to len bytes, decrypted etc if required.
 */
static int ssl2_read_internal(SSL *s, void *buf, int len, int peek)
{
    int n;
    unsigned char mac[MAX_MAC_SIZE];
    unsigned char *p;
    int i;
    unsigned int mac_size;

 ssl2_read_again:
    if (SSL_in_init(s) && !s->in_handshake) {
        n = s->handshake_func(s);
        if (n < 0)
            return (n);
        if (n == 0) {
            SSLerr(SSL_F_SSL2_READ_INTERNAL, SSL_R_SSL_HANDSHAKE_FAILURE);
            return (-1);
        }
    }

    clear_sys_error();
    s->rwstate = SSL_NOTHING;
    if (len <= 0)
        return (len);

    if (s->s2->ract_data_length != 0) { /* read from buffer */
        if (len > s->s2->ract_data_length)
            n = s->s2->ract_data_length;
        else
            n = len;

        memcpy(buf, s->s2->ract_data, (unsigned int)n);
        if (!peek) {
            s->s2->ract_data_length -= n;
            s->s2->ract_data += n;
            if (s->s2->ract_data_length == 0)
                s->rstate = SSL_ST_READ_HEADER;
        }

        return (n);
    }

    /*
     * s->s2->ract_data_length == 0 Fill the buffer, then goto
     * ssl2_read_again.
     */

    if (s->rstate == SSL_ST_READ_HEADER) {
        if (s->first_packet) {
            n = read_n(s, 5, SSL2_MAX_RECORD_LENGTH_2_BYTE_HEADER + 2, 0);
            if (n <= 0)
                return (n);     /* error or non-blocking */
            s->first_packet = 0;
            p = s->packet;
            if (!((p[0] & 0x80) && ((p[2] == SSL2_MT_CLIENT_HELLO) ||
                                    (p[2] == SSL2_MT_SERVER_HELLO)))) {
                SSLerr(SSL_F_SSL2_READ_INTERNAL,
                       SSL_R_NON_SSLV2_INITIAL_PACKET);
                return (-1);
            }
        } else {
            n = read_n(s, 2, SSL2_MAX_RECORD_LENGTH_2_BYTE_HEADER + 2, 0);
            if (n <= 0)
                return (n);     /* error or non-blocking */
        }
        /* part read stuff */

        s->rstate = SSL_ST_READ_BODY;
        p = s->packet;
        /* Do header */
        /*
         * s->s2->padding=0;
         */
        s->s2->escape = 0;
        s->s2->rlength = (((unsigned int)p[0]) << 8) | ((unsigned int)p[1]);
        if ((p[0] & TWO_BYTE_BIT)) { /* Two byte header? */
            s->s2->three_byte_header = 0;
            s->s2->rlength &= TWO_BYTE_MASK;
        } else {
            s->s2->three_byte_header = 1;
            s->s2->rlength &= THREE_BYTE_MASK;

            /* security >s2->escape */
            s->s2->escape = ((p[0] & SEC_ESC_BIT)) ? 1 : 0;
        }
    }

    if (s->rstate == SSL_ST_READ_BODY) {
        n = s->s2->rlength + 2 + s->s2->three_byte_header;
        if (n > (int)s->packet_length) {
            n -= s->packet_length;
            i = read_n(s, (unsigned int)n, (unsigned int)n, 1);
            if (i <= 0)
                return (i);     /* ERROR */
        }

        p = &(s->packet[2]);
        s->rstate = SSL_ST_READ_HEADER;
        if (s->s2->three_byte_header)
            s->s2->padding = *(p++);
        else
            s->s2->padding = 0;

        /* Data portion */
        if (s->s2->clear_text) {
            mac_size = 0;
            s->s2->mac_data = p;
            s->s2->ract_data = p;
            if (s->s2->padding) {
                SSLerr(SSL_F_SSL2_READ_INTERNAL, SSL_R_ILLEGAL_PADDING);
                return (-1);
            }
        } else {
            mac_size = EVP_MD_size(s->read_hash);
            OPENSSL_assert(mac_size <= MAX_MAC_SIZE);
            s->s2->mac_data = p;
            s->s2->ract_data = &p[mac_size];
            if (s->s2->padding + mac_size > s->s2->rlength) {
                SSLerr(SSL_F_SSL2_READ_INTERNAL, SSL_R_ILLEGAL_PADDING);
                return (-1);
            }
        }

        s->s2->ract_data_length = s->s2->rlength;
        /*
         * added a check for length > max_size in case encryption was not
         * turned on yet due to an error
         */
        if ((!s->s2->clear_text) && (s->s2->rlength >= mac_size)) {
            ssl2_enc(s, 0);
            s->s2->ract_data_length -= mac_size;
            ssl2_mac(s, mac, 0);
            s->s2->ract_data_length -= s->s2->padding;
            if ((CRYPTO_memcmp(mac, s->s2->mac_data, mac_size) != 0) ||
                (s->s2->rlength %
                 EVP_CIPHER_CTX_block_size(s->enc_read_ctx) != 0)) {
                SSLerr(SSL_F_SSL2_READ_INTERNAL, SSL_R_BAD_MAC_DECODE);
                return (-1);
            }
        }
        INC32(s->s2->read_sequence); /* expect next number */
        /* s->s2->ract_data is now available for processing */

        /*
         * Possibly the packet that we just read had 0 actual data bytes.
         * (SSLeay/OpenSSL itself never sends such packets; see ssl2_write.)
         * In this case, returning 0 would be interpreted by the caller as
         * indicating EOF, so it's not a good idea.  Instead, we just
         * continue reading; thus ssl2_read_internal may have to process
         * multiple packets before it can return. [Note that using select()
         * for blocking sockets *never* guarantees that the next SSL_read
         * will not block -- the available data may contain incomplete
         * packets, and except for SSL 2, renegotiation can confuse things
         * even more.]
         */

        goto ssl2_read_again;   /* This should really be "return
                                 * ssl2_read(s,buf,len)", but that would
                                 * allow for denial-of-service attacks if a C
                                 * compiler is used that does not recognize
                                 * end-recursion. */
    } else {
        SSLerr(SSL_F_SSL2_READ_INTERNAL, SSL_R_BAD_STATE);
        return (-1);
    }
}

int ssl2_read(SSL *s, void *buf, int len)
{
    return ssl2_read_internal(s, buf, len, 0);
}

int ssl2_peek(SSL *s, void *buf, int len)
{
    return ssl2_read_internal(s, buf, len, 1);
}

static int read_n(SSL *s, unsigned int n, unsigned int max,
                  unsigned int extend)
{
    int i, off, newb;

    /*
     * if there is stuff still in the buffer from a previous read, and there
     * is more than we want, take some.
     */
    if (s->s2->rbuf_left >= (int)n) {
        if (extend)
            s->packet_length += n;
        else {
            s->packet = &(s->s2->rbuf[s->s2->rbuf_offs]);
            s->packet_length = n;
        }
        s->s2->rbuf_left -= n;
        s->s2->rbuf_offs += n;
        return (n);
    }

    if (!s->read_ahead)
        max = n;
    if (max > (unsigned int)(SSL2_MAX_RECORD_LENGTH_2_BYTE_HEADER + 2))
        max = SSL2_MAX_RECORD_LENGTH_2_BYTE_HEADER + 2;

    /*
     * Else we want more than we have. First, if there is some left or we
     * want to extend
     */
    off = 0;
    if ((s->s2->rbuf_left != 0) || ((s->packet_length != 0) && extend)) {
        newb = s->s2->rbuf_left;
        if (extend) {
            off = s->packet_length;
            if (s->packet != s->s2->rbuf)
                memcpy(s->s2->rbuf, s->packet, (unsigned int)newb + off);
        } else if (s->s2->rbuf_offs != 0) {
            memcpy(s->s2->rbuf, &(s->s2->rbuf[s->s2->rbuf_offs]),
                   (unsigned int)newb);
            s->s2->rbuf_offs = 0;
        }
        s->s2->rbuf_left = 0;
    } else
        newb = 0;

    /*
     * off is the offset to start writing too. r->s2->rbuf_offs is the
     * 'unread data', now 0. newb is the number of new bytes so far
     */
    s->packet = s->s2->rbuf;
    while (newb < (int)n) {
        clear_sys_error();
        if (s->rbio != NULL) {
            s->rwstate = SSL_READING;
            i = BIO_read(s->rbio, (char *)&(s->s2->rbuf[off + newb]),
                         max - newb);
        } else {
            SSLerr(SSL_F_READ_N, SSL_R_READ_BIO_NOT_SET);
            i = -1;
        }
# ifdef PKT_DEBUG
        if (s->debug & 0x01)
            sleep(1);
# endif
        if (i <= 0) {
            s->s2->rbuf_left += newb;
            return (i);
        }
        newb += i;
    }

    /* record unread data */
    if (newb > (int)n) {
        s->s2->rbuf_offs = n + off;
        s->s2->rbuf_left = newb - n;
    } else {
        s->s2->rbuf_offs = 0;
        s->s2->rbuf_left = 0;
    }
    if (extend)
        s->packet_length += n;
    else
        s->packet_length = n;
    s->rwstate = SSL_NOTHING;
    return (n);
}

int ssl2_write(SSL *s, const void *_buf, int len)
{
    const unsigned char *buf = _buf;
    unsigned int n, tot;
    int i;

    if (SSL_in_init(s) && !s->in_handshake) {
        i = s->handshake_func(s);
        if (i < 0)
            return (i);
        if (i == 0) {
            SSLerr(SSL_F_SSL2_WRITE, SSL_R_SSL_HANDSHAKE_FAILURE);
            return (-1);
        }
    }

    if (s->error) {
        ssl2_write_error(s);
        if (s->error)
            return (-1);
    }

    clear_sys_error();
    s->rwstate = SSL_NOTHING;
    if (len <= 0)
        return (len);

    tot = s->s2->wnum;
    s->s2->wnum = 0;

    n = (len - tot);
    for (;;) {
        i = do_ssl_write(s, &(buf[tot]), n);
        if (i <= 0) {
            s->s2->wnum = tot;
            return (i);
        }
        if ((i == (int)n) || (s->mode & SSL_MODE_ENABLE_PARTIAL_WRITE)) {
            return (tot + i);
        }

        n -= i;
        tot += i;
    }
}

static int write_pending(SSL *s, const unsigned char *buf, unsigned int len)
{
    int i;

    /* s->s2->wpend_len != 0 MUST be true. */

    /*
     * check that they have given us the same buffer to write
     */
    if ((s->s2->wpend_tot > (int)len) ||
        ((s->s2->wpend_buf != buf) &&
         !(s->mode & SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER))) {
        SSLerr(SSL_F_WRITE_PENDING, SSL_R_BAD_WRITE_RETRY);
        return (-1);
    }

    for (;;) {
        clear_sys_error();
        if (s->wbio != NULL) {
            s->rwstate = SSL_WRITING;
            i = BIO_write(s->wbio,
                          (char *)&(s->s2->write_ptr[s->s2->wpend_off]),
                          (unsigned int)s->s2->wpend_len);
        } else {
            SSLerr(SSL_F_WRITE_PENDING, SSL_R_WRITE_BIO_NOT_SET);
            i = -1;
        }
# ifdef PKT_DEBUG
        if (s->debug & 0x01)
            sleep(1);
# endif
        if (i == s->s2->wpend_len) {
            s->s2->wpend_len = 0;
            s->rwstate = SSL_NOTHING;
            return (s->s2->wpend_ret);
        } else if (i <= 0)
            return (i);
        s->s2->wpend_off += i;
        s->s2->wpend_len -= i;
    }
}

static int do_ssl_write(SSL *s, const unsigned char *buf, unsigned int len)
{
    unsigned int j, k, olen, p, mac_size, bs;
    register unsigned char *pp;

    olen = len;

    /*
     * first check if there is data from an encryption waiting to be sent -
     * it must be sent because the other end is waiting. This will happen
     * with non-blocking IO.  We print it and then return.
     */
    if (s->s2->wpend_len != 0)
        return (write_pending(s, buf, len));

    /* set mac_size to mac size */
    if (s->s2->clear_text)
        mac_size = 0;
    else
        mac_size = EVP_MD_size(s->write_hash);

    /* lets set the pad p */
    if (s->s2->clear_text) {
        if (len > SSL2_MAX_RECORD_LENGTH_2_BYTE_HEADER)
            len = SSL2_MAX_RECORD_LENGTH_2_BYTE_HEADER;
        p = 0;
        s->s2->three_byte_header = 0;
        /* len=len; */
    } else {
        bs = EVP_CIPHER_CTX_block_size(s->enc_read_ctx);
        j = len + mac_size;
        /*
         * Two-byte headers allow for a larger record length than three-byte
         * headers, but we can't use them if we need padding or if we have to
         * set the escape bit.
         */
        if ((j > SSL2_MAX_RECORD_LENGTH_3_BYTE_HEADER) && (!s->s2->escape)) {
            if (j > SSL2_MAX_RECORD_LENGTH_2_BYTE_HEADER)
                j = SSL2_MAX_RECORD_LENGTH_2_BYTE_HEADER;
            /*
             * set k to the max number of bytes with 2 byte header
             */
            k = j - (j % bs);
            /* how many data bytes? */
            len = k - mac_size;
            s->s2->three_byte_header = 0;
            p = 0;
        } else if ((bs <= 1) && (!s->s2->escape)) {
            /*-
             * j <= SSL2_MAX_RECORD_LENGTH_3_BYTE_HEADER, thus
             * j < SSL2_MAX_RECORD_LENGTH_2_BYTE_HEADER
             */
            s->s2->three_byte_header = 0;
            p = 0;
        } else {                /* we may have to use a 3 byte header */

            /*-
             * If s->s2->escape is not set, then
             * j <= SSL2_MAX_RECORD_LENGTH_3_BYTE_HEADER, and thus
             * j < SSL2_MAX_RECORD_LENGTH_2_BYTE_HEADER.
             */
            p = (j % bs);
            p = (p == 0) ? 0 : (bs - p);
            if (s->s2->escape) {
                s->s2->three_byte_header = 1;
                if (j > SSL2_MAX_RECORD_LENGTH_3_BYTE_HEADER)
                    j = SSL2_MAX_RECORD_LENGTH_3_BYTE_HEADER;
            } else
                s->s2->three_byte_header = (p == 0) ? 0 : 1;
        }
    }

    /*-
     * Now
     *      j <= SSL2_MAX_RECORD_LENGTH_2_BYTE_HEADER
     * holds, and if s->s2->three_byte_header is set, then even
     *      j <= SSL2_MAX_RECORD_LENGTH_3_BYTE_HEADER.
     */

    /*
     * mac_size is the number of MAC bytes len is the number of data bytes we
     * are going to send p is the number of padding bytes (if it is a
     * two-byte header, then p == 0)
     */

    s->s2->wlength = len;
    s->s2->padding = p;
    s->s2->mac_data = &(s->s2->wbuf[3]);
    s->s2->wact_data = &(s->s2->wbuf[3 + mac_size]);
    /* we copy the data into s->s2->wbuf */
    memcpy(s->s2->wact_data, buf, len);
    if (p)
        memset(&(s->s2->wact_data[len]), 0, p); /* arbitrary padding */

    if (!s->s2->clear_text) {
        s->s2->wact_data_length = len + p;
        ssl2_mac(s, s->s2->mac_data, 1);
        s->s2->wlength += p + mac_size;
        ssl2_enc(s, 1);
    }

    /* package up the header */
    s->s2->wpend_len = s->s2->wlength;
    if (s->s2->three_byte_header) { /* 3 byte header */
        pp = s->s2->mac_data;
        pp -= 3;
        pp[0] = (s->s2->wlength >> 8) & (THREE_BYTE_MASK >> 8);
        if (s->s2->escape)
            pp[0] |= SEC_ESC_BIT;
        pp[1] = s->s2->wlength & 0xff;
        pp[2] = s->s2->padding;
        s->s2->wpend_len += 3;
    } else {
        pp = s->s2->mac_data;
        pp -= 2;
        pp[0] = ((s->s2->wlength >> 8) & (TWO_BYTE_MASK >> 8)) | TWO_BYTE_BIT;
        pp[1] = s->s2->wlength & 0xff;
        s->s2->wpend_len += 2;
    }
    s->s2->write_ptr = pp;

    INC32(s->s2->write_sequence); /* expect next number */

    /* lets try to actually write the data */
    s->s2->wpend_tot = olen;
    s->s2->wpend_buf = buf;

    s->s2->wpend_ret = len;

    s->s2->wpend_off = 0;
    return (write_pending(s, buf, olen));
}

int ssl2_part_read(SSL *s, unsigned long f, int i)
{
    unsigned char *p;
    int j;

    if (i < 0) {
        /* ssl2_return_error(s); */
        /*
         * for non-blocking io, this is not necessarily fatal
         */
        return (i);
    } else {
        s->init_num += i;

        /*
         * Check for error.  While there are recoverable errors, this
         * function is not called when those must be expected; any error
         * detected here is fatal.
         */
        if (s->init_num >= 3) {
            p = (unsigned char *)s->init_buf->data;
            if (p[0] == SSL2_MT_ERROR) {
                j = (p[1] << 8) | p[2];
                SSLerr((int)f, ssl_mt_error(j));
                s->init_num -= 3;
                if (s->init_num > 0)
                    memmove(p, p + 3, s->init_num);
            }
        }

        /*
         * If it's not an error message, we have some error anyway -- the
         * message was shorter than expected.  This too is treated as fatal
         * (at least if SSL_get_error is asked for its opinion).
         */
        return (0);
    }
}

int ssl2_do_write(SSL *s)
{
    int ret;

    ret = ssl2_write(s, &s->init_buf->data[s->init_off], s->init_num);
    if (ret == s->init_num) {
        if (s->msg_callback)
            s->msg_callback(1, s->version, 0, s->init_buf->data,
                            (size_t)(s->init_off + s->init_num), s,
                            s->msg_callback_arg);
        return (1);
    }
    if (ret < 0)
        return (-1);
    s->init_off += ret;
    s->init_num -= ret;
    return (0);
}

static int ssl_mt_error(int n)
{
    int ret;

    switch (n) {
    case SSL2_PE_NO_CIPHER:
        ret = SSL_R_PEER_ERROR_NO_CIPHER;
        break;
    case SSL2_PE_NO_CERTIFICATE:
        ret = SSL_R_PEER_ERROR_NO_CERTIFICATE;
        break;
    case SSL2_PE_BAD_CERTIFICATE:
        ret = SSL_R_PEER_ERROR_CERTIFICATE;
        break;
    case SSL2_PE_UNSUPPORTED_CERTIFICATE_TYPE:
        ret = SSL_R_PEER_ERROR_UNSUPPORTED_CERTIFICATE_TYPE;
        break;
    default:
        ret = SSL_R_UNKNOWN_REMOTE_ERROR_TYPE;
        break;
    }
    return (ret);
}
#else                           /* !OPENSSL_NO_SSL2 */

# if PEDANTIC
static void *dummy = &dummy;
# endif

#endif


text:
package ucar.nc2.dt.point;

import ucar.ma2.*;
import ucar.nc2.*;
import ucar.nc2.dataset.NetcdfDataset;
import ucar.nc2.util.CancelTask;
import ucar.nc2.dt.*;
import java.io.*;
import java.util.*;

/**
 * National Data Buoy Center data. This is a time series at a single buoy.
 *
 *

 * This is a single station of data. Assumed to be time ordered.
 * We construct the list of StationObsDatatype records, but without the data cached.
 *
 * @see http://www.ndbc.noaa.gov/index.shtml
 *
 * @deprecated use ucar.nc2.ft.point
 * @author caron
 */

// LOOK when from a dods server, record structure not there. Havent dealt with that yet.
public class NdbcDataset extends StationObsDatasetImpl implements TypedDatasetFactoryIF {
  private ArrayInt.D1 dates;
  private RecordDatasetHelper recordHelper;
  private StationImpl station;

  public static boolean isValidFile(NetcdfFile ds) {
    if (!ds.findAttValueIgnoreCase(null, "Conventions", "").equalsIgnoreCase("COARDS"))
      return false;
    if (!ds.findAttValueIgnoreCase(null, "data_provider", "").equalsIgnoreCase("National Data Buoy Center"))
      return false;

    if (null == ds.findAttValueIgnoreCase(null, "station", null))
      return false;
    if (null == ds.findAttValueIgnoreCase(null, "location", null))
      return false;

    if (ds.findVariable("lat") == null)
      return false;
    if (ds.findVariable("lon") == null)
      return false;

    // DODS wont have record !!
    if (!ds.hasUnlimitedDimension())
      return false;

    return true;
  }

  /////////////////////////////////////////////////
  // TypedDatasetFactoryIF
  public boolean isMine(NetcdfDataset ds) {
    return isValidFile(ds);
  }

  public TypedDataset open(NetcdfDataset ncd, ucar.nc2.util.CancelTask task, StringBuilder errlog) throws IOException {
    return new NdbcDataset(ncd);
  }

  public NdbcDataset() {}

  public NdbcDataset(NetcdfDataset ds) throws IOException {
    super(ds);

    recordHelper = new RecordDatasetHelper(ds, "time", null, dataVariables);
    removeDataVariable("time");
    timeUnit = recordHelper.timeUnit;

    Variable latVar = ds.findVariable("lat");
    double lat = latVar.readScalarDouble();
    Variable lonVar = ds.findVariable("lon");
    double lon = lonVar.readScalarDouble();

    // LOOK assume its time ordered
    Variable dateVar = ds.findVariable("time");
    dates = (ArrayInt.D1) dateVar.read();
    int count = (int) dates.getSize();
    int firstDate = dates.get(0);
    int lastDate = dates.get(count - 1);

    startDate = timeUnit.makeDate((double) firstDate);
    endDate = timeUnit.makeDate((double) lastDate);

    String name = ds.findAttValueIgnoreCase(null, "station", null);
    String stationDesc = ds.findAttValueIgnoreCase(null, "description", null);

    // only one station in the file
    station = new StationImpl(name, stationDesc, lat, lon, Double.NaN, count);
    stations.add(station);

    // typed dataset fields
    title = ds.findAttValueIgnoreCase(null, "data_provider", null) + " Station " + name;
    desc = title + "\n" + ds.findAttValueIgnoreCase(null, "data_quality", null);

    setBoundingBox();
  }

  protected void setTimeUnits() {}

  protected void setStartDate() {}

  protected void setEndDate() {}

  protected void setBoundingBox() {
    boundingBox = stationHelper.getBoundingBox();
  }

  public List getData(CancelTask cancel) throws IOException {
    return getData(station, cancel);
  }

  public int getDataCount() {
    Dimension unlimitedDim = netcdfDataset.getUnlimitedDimension();
    return unlimitedDim.getLength();
  }

  public List getData(ucar.unidata.geoloc.Station s, CancelTask cancel) throws IOException {
    StationImpl si = (StationImpl) s;
    int count = getDataCount();

    if (null == si.getObservations()) {
      for (int recno = 0; recno < count; recno++) {
        double time = dates.get(recno);
        si.addObs(recordHelper.new RecordStationObs(s, time, time, recno));
        if ((cancel != null) && cancel.isCancel())
          return null;
      }
    }

    return si.getObservations();
  }

  public DataIterator getDataIterator(int bufferSize) throws IOException {
    return new NdbcDatatypeIterator(recordHelper.recordVar, bufferSize);
  }

  private class NdbcDatatypeIterator extends DatatypeIterator {
    protected Object makeDatatypeWithData(int recnum, StructureData sdata) {
      return recordHelper.new RecordStationObs(station, sdata);
    }

    NdbcDatatypeIterator(Structure struct, int bufferSize) {
      super(struct, bufferSize);
    }
  }

  /*
   * public void initNonRecordCase(NetcdfFile ds) throws IOException {
   * this.ds = ds;
   *
   * Variable timeVar = ds.findVariable("record.timeObs");
   * String timeUnitString = ds.findAttValueIgnoreCase(timeVar, "units", "seconds since 1970-01-01");
   * try {
   * dateUnit = (DateUnit) SimpleUnit.factoryWithExceptions(timeUnitString);
   * } catch (Exception e) {
   * System.out.println("Error on string = "+timeUnitString+" == "+e.getMessage());
   * dateUnit = (DateUnit) SimpleUnit.factory("seconds since 1970-01-01");
   * }
   *
   * // get the station info
   * ArrayChar stationIdArray = (ArrayChar) ds.findVariable("id").read();
   * ArrayChar stationDescArray = (ArrayChar) ds.findVariable("location").read();
   * Array latArray = ds.findVariable("latitude").read();
   * Array lonArray = ds.findVariable("longitude").read();
   * Array elevArray = ds.findVariable("elevation").read();
   * Array lastRecordArray = ds.findVariable("lastReport").read();
   * Index ima = lastRecordArray.getIndex();
   *
   * int n = ds.findVariable("num_stations").readScalarInt();
   * for (int i = 0; i<n; i++) {
   * ima.set(i);
   *
   * String stationName = stationIdArray.getString(i).trim();
   * String stationDesc = stationDescArray.getString(i).trim();
   *
   * StationImpl bean = new StationImpl(stationName, stationDesc,
   * latArray.getFloat(ima),
   * lonArray.getFloat(ima),
   * elevArray.getFloat(ima),
   * lastRecordArray.getInt(ima));
   *
   * stationHash.put(stationName, bean);
   * stations.add(bean);
   * // System.out.println(" read " + stationName);
   * }
   * // System.out.println("total stations " + n);
   *
   * // get the record info
   * recordVar = (Structure) ds.findVariable("record");
   * ucar.nc2.Dimension nrecs = ds.findDimension("recNum");
   * int nobs = nrecs.getLength();
   *
   * try {
   * StructureData data = recordVar.readStructure(0);
   * startDate = data.getScalarInt("time_observation");
   * data = data = recordVar.readStructure(nobs-1);
   * endDate = data.getScalarInt("time_observation");
   * } catch (InvalidRangeException e) {
   * e.printStackTrace();
   * }
   *
   * stationHelper = new StationDatasetHelper( this);
   * }
   */
}

redpajama_set_name: RedPajamaGithub


text:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
    android:paddingLeft="0dp"
    android:paddingTop="0px"

    android:background="@drawable/abc_aprender_orange_7_fundo"
    android:paddingRight="0dp"
    android:orientation="vertical">

    <android.support.constraint.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <ImageButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@android:color/transparent"
            app:srcCompat="@drawable/abc_aprender_sete"
            android:id="@+id/abc_aprender_sete_orange"
            android:layout_marginStart="64dp"
            app:layout_constraintLeft_toLeftOf="parent"
            android:layout_marginLeft="64dp"
            android:layout_marginTop="312dp"
            app:layout_constraintTop_toTopOf="parent"/>

        <ImageButton
            android:layout_width="wrap_content"
            android:background="@android:color/transparent"
            android:layout_height="wrap_content"
            app:srcCompat="@drawable/abc_aprender_urso_cinco"
            android:id="@+id/abc_aprender_orange_button_cinco_sete"
            android:layout_marginTop="312dp"
            app:layout_constraintTop_toTopOf="parent"
            android:layout_marginStart="48dp"
            app:layout_constraintLeft_toRightOf="@+id/abc_aprender_sete_orange"
            android:layout_marginLeft="48dp"/>

        <ImageButton
            android:layout_width="wrap_content"
            android:background="@android:color/transparent"
            android:layout_height="wrap_content"
            app:srcCompat="@drawable/abc_aprender_urso_6"
            android:id="@+id/abc_aprender_seis_orange_sete"
            android:layout_marginTop="312dp"
            app:layout_constraintTop_toTopOf="parent"
            android:layout_marginStart="48dp"
            app:layout_constraintLeft_toRightOf="@+id/abc_aprender_orange_button_cinco_sete"
            android:layout_marginLeft="48dp"/>

        <ImageView
            android:layout_width="76dp"
            android:layout_height="73dp"
            android:background="@android:color/transparent"
            app:srcCompat="@drawable/sol_app"
            android:id="@+id/imageView"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintBottom_toBottomOf="parent"
            android:layout_marginBottom="416dp"
            android:layout_marginEnd="8dp"
            android:layout_marginRight="8dp"/>
    </android.support.constraint.ConstraintLayout>
</LinearLayout>


text:
package org.asteriskjava.fastagi.command;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;

class GetDataCommandTest {
    private GetDataCommand getDataCommand;

    @Test
    void shouldBuildGetDataCommand() {
        //given
        GetDataCommand getDataCommand = new GetDataCommand("VAR1");

        //when
        String actual = getDataCommand.buildCommand();

        //then
        assertThat(actual).isEqualTo("GET DATA \"VAR1\"");
    }

    @Test
    void shouldSetTimeoutWhenBuildGetDataCommand() {
        //given
        GetDataCommand getDataCommand = new GetDataCommand("VAR1");
        getDataCommand.setTimeout(10000);

        //when
        String actual = getDataCommand.buildCommand();

        //then
        assertThat(actual).isEqualTo("GET DATA \"VAR1\" 10000");
        assertThat(getDataCommand.getTimeout()).isEqualTo(10000);
        assertThat(getDataCommand.getMaxDigits()).isEqualTo(1024);
    }

    @Test
    void shouldSetMaxDigitsWhenBuildGetDataCommand() {
        //given
        GetDataCommand getDataCommand = new GetDataCommand("VAR1");
        getDataCommand.setMaxDigits(10);

        //when
        String actual = getDataCommand.buildCommand();

        //then
        assertThat(actual).isEqualTo("GET DATA \"VAR1\" 0 10");
        assertThat(getDataCommand.getTimeout()).isEqualTo(0);
        assertThat(getDataCommand.getMaxDigits()).isEqualTo(10);
    }

    @Test
    void shouldSetTimeoutAndSetMaxDigitsWhenBuildGetDataCommand() {
        //given
        GetDataCommand getDataCommand = new GetDataCommand("VAR1");
        getDataCommand.setTimeout(10000);
        getDataCommand.setMaxDigits(20);

        //when
        String actual = getDataCommand.buildCommand();

        //then
        assertThat(actual).isEqualTo("GET DATA \"VAR1\" 10000 20");
        assertThat(getDataCommand.getTimeout()).isEqualTo(10000);
        assertThat(getDataCommand.getMaxDigits()).isEqualTo(20);
    }

    @ParameterizedTest
    @ValueSource(ints = {0, 1025})
    void shouldThrowExceptionWhenMaxDigitsIsOutOfRange(int maxDigits) {
        //when/then
        assertThatThrownBy(() -> new GetDataCommand("VAR1", 10, maxDigits))
                .isInstanceOf(IllegalArgumentException.class)
                .hasMessage("maxDigits must be in [1..1024]");
    }
}


text:
#pragma once
#include <kernel_headers/iir.hpp>
#include <program.hpp>
#include <traits.hpp>
#include <string>
#include <cache.hpp>
#include <common/dispatch.hpp>
#include <Param.hpp>
#include <debug_opencl.hpp>
#include <types.hpp>

using cl::Buffer;
using cl::Program;
using cl::Kernel;
using cl::KernelFunctor;
using cl::EnqueueArgs;
using cl::NDRange;
using std::string;
using af::scalar_to_option;

namespace opencl
{
namespace kernel
{
template<typename T, bool batch_a>
void iir(Param y, Param c, Param a)
{
    //FIXME: This is a temporary fix. Ideally the local memory should be allocted outside
    static const int MAX_A_SIZE = (1024 * sizeof(double)) / sizeof(T);

    std::string refName = std::string("iir_kernel_") +
        std::string(dtype_traits<T>::getName()) + std::to_string(batch_a);

    int device = getActiveDeviceId();
    kc_entry_t entry = kernelCache(device, refName);

    if (entry.prog==0 && entry.ker==0) {
        std::ostringstream options;
        options << " -D MAX_A_SIZE=" << MAX_A_SIZE
            << " -D BATCH_A=" << batch_a
            << " -D ZERO=(T)(" << scalar_to_option(scalar<T>(0)) << ")"
            << " -D T=" << dtype_traits<T>::getName();

        if (std::is_same<T, double>::value || std::is_same<T, cdouble>::value)
            options << " -D USE_DOUBLE";

        const char* ker_strs[] = {iir_cl};
        const int   ker_lens[] = {iir_cl_len};
        Program prog;
        buildProgram(prog, 1, ker_strs, ker_lens, options.str());
        entry.prog = new Program(prog);
        entry.ker  = new Kernel(*entry.prog, "iir_kernel");

        addKernelToCache(device, refName, entry);
    }

    const int groups_y = y.info.dims[1];
    const int groups_x = y.info.dims[2];

    int threads = 256;
    while (threads > (int)y.info.dims[0] && threads > 32) threads /= 2;

    NDRange local(threads, 1);
    NDRange global(groups_x * local[0], groups_y * y.info.dims[3] * local[1]);

    auto iirOp = KernelFunctor<Buffer, KParam, Buffer, KParam, Buffer, KParam, int>(*entry.ker);

    try {
        iirOp(EnqueueArgs(getQueue(), global, local),
              *y.data, y.info, *c.data, c.info, *a.data, a.info, groups_y);
    } catch(cl::Error &clerr) {
        AF_ERROR("Size of a too big for this datatype", AF_ERR_SIZE);
    }

    CL_DEBUG_FINISH(getQueue());
}
}
}


text:
module Parser (mainParser, parseWhileFile) where

import Text.ParserCombinators.Parsec
import qualified Text.ParserCombinators.Parsec.Token as P
import Text.ParserCombinators.Parsec.Language
import Text.ParserCombinators.Parsec.Expr

import While

whileDef = emptyDef { commentStart = "{"
                    , commentEnd = "}"
                    , identStart = letter
                    , identLetter = alphaNum
                    , opStart = oneOf "!&=<:;+-*\""
                    , opLetter = oneOf "!&=<:;+-*\""
                    , reservedOpNames = ["!", "&", "=", "<=", ":=",
                                         ";", "+", "-", "*", "(", ")"]
                    , reservedNames = ["true", "false", "skip",
                                       "if", "then", "else",
                                       "while", "do", "printf"]
                    }

lexer  = P.makeTokenParser whileDef

symbol     = P.symbol lexer
identifier = P.identifier lexer
reserved   = P.reserved lexer
reservedOp = P.reservedOp lexer
parens     = P.parens lexer
natural    = P.natural lexer
whiteSpace = P.whiteSpace lexer
semiSep1   = P.semiSep1 lexer
stringLiteral   = P.stringLiteral lexer

variableParser :: Parser Variable
variableParser = identifier >>= return . Variable

arithmeticParser = buildExpressionParser table term
	where
		table = [ [ Infix (reservedOp "+" >> return Add) AssocLeft ]
		        , [ Infix (reservedOp "-" >> return Sub) AssocLeft ]
		        , [ Infix (reservedOp "*" >> return Mul) AssocLeft ]
		        ]
		term = choice $ map try [ parens arithmeticParser
		                        , fmap AVariable variableParser
		                        , fmap Constant natural
		                        ]

booleanParser = buildExpressionParser table term
	where
		table = [ [ Prefix (reservedOp "!" >> return Not) ]
		        , [ Infix  (reservedOp "&" >> return And) AssocLeft ]
		        ]
		term = choice $ map try [ parens booleanParser
		                        ,  (reserved "true" >> return BTrue)
		                        ,  (reserved "false" >> return BFalse)
		                        ,  infixArith Equal "="
		                        ,  infixArith LTE "<="
		                        ]
		infixArith comb sym = do
			a <- arithmeticParser
			reservedOp sym
			b <- arithmeticParser
			return $ comb a b

singleStatementParser =
	choice $ map try [ parens statementParser
	                 , assignmentParser
	                 , skipParser
	                 , ifParser
	                 , whileParser
	                 , printfParser
	                 ]
		where
			assignmentParser = do
				x <- variableParser
				reservedOp ":="
				a <- arithmeticParser
				return $ Assignment x a
			skipParser = reserved "skip" >> return Skip
			ifParser = do
				reserved "if"
				b <- booleanParser
				reserved "then"
				s1 <- statementParser
				reserved "else"
				s2 <- statementParser
				return $ If b s1 s2
			whileParser = do
				reserved "while"
				b <- booleanParser
				reserved "do"
				s <- singleStatementParser
				return $ While b s
			printfParser = do
				reserved "printf"
				s <- stringLiteral
				args <- many arithmeticParser
				return $ Printf s args

statementParser = semiSep1 singleStatementParser >>= return . toTree
	where
		toTree [s] = s
		toTree (s:ss) = Sequence s $ toTree ss

mainParser = do
	whiteSpace
	stmt <- statementParser
	eof
	return stmt

parseWhileFile = parseFromFile mainParser


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NNSharp.KernelDescriptors
{
    public class Cropping1D : IKernelDescriptor
    {
        public Cropping1D(int trimBegin, int trimEnd)
        {
            this.trimBegin = trimBegin;
            this.trimEnd = trimEnd;
        }

        public int TrimBegin { get { return trimBegin; } }
        public int TrimEnd { get { return trimEnd; } }

        private int trimBegin;
        private int trimEnd;
    }
}


text:
/** @author Brian Cavalier */
/** @author John Hann */

(function(define) { 'use strict';
define(function() {

	return {
		formatError: formatError,
		formatObject: formatObject,
		tryStringify: tryStringify
	};

	/**
	 * Format an error into a string.  If e is an Error and has a stack property,
	 * it's returned.  Otherwise, e is formatted using formatObject, with a
	 * warning added about e not being a proper Error.
	 * @param {*} e
	 * @returns {String} formatted string, suitable for output to developers
	 */
	function formatError(e) {
		var s = typeof e === 'object' && e !== null && (e.stack || e.message) ? e.stack || e.message : formatObject(e);
		return e instanceof Error ? s : s + ' (WARNING: non-Error used)';
	}

	/**
	 * Format an object, detecting "plain" objects and running them through
	 * JSON.stringify if possible.
	 * @param {Object} o
	 * @returns {string}
	 */
	function formatObject(o) {
		var s = String(o);
		if(s === '[object Object]' && typeof JSON !== 'undefined') {
			s = tryStringify(o, s);
		}
		return s;
	}

	/**
	 * Try to return the result of JSON.stringify(x).  If that fails, return
	 * defaultValue
	 * @param {*} x
	 * @param {*} defaultValue
	 * @returns {String|*} JSON.stringify(x) or defaultValue
	 */
	function tryStringify(x, defaultValue) {
		try {
			return JSON.stringify(x);
		} catch(e) {
			return defaultValue;
		}
	}

});
}(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));


text:
using System;
using System.Drawing;
using System.Windows.Forms;

namespace _3._2._38;

public partial class Form1 : Form
{
    private Form2? _drawPad;

    public Form1()
    {
        InitializeComponent();
    }

    /// <inheritdoc />
    protected override void OnShown(EventArgs e)
    {
        base.OnShown(e);
        _drawPad = new Form2
        {
            StartPosition = FormStartPosition.Manual,
            Location = new Point {X = Location.X - 800, Y = Location.Y}
        };
        _drawPad.Show();
    }

    private void AddNode_Click(object sender, EventArgs e)
    {
        _drawPad?.AddNode(int.Parse(textBox1.Text));
    }

    private void DeleteNode_Click(object sender, EventArgs e)
    {
        _drawPad?.DeleteNode(int.Parse(textBox2.Text));
    }
}


text:
package org.jetbrains.idea.maven.dom.converters.repositories;

import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.components.Service;
import com.intellij.util.xmlb.XmlSerializer;
import gnu.trove.THashMap;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.idea.maven.dom.converters.repositories.beans.RepositoriesBean;
import org.jetbrains.idea.maven.dom.converters.repositories.beans.RepositoryBeanInfo;

import java.util.Map;
import java.util.Set;

@Service(Service.Level.APP)
public final class MavenRepositoriesProvider {
  public static MavenRepositoriesProvider getInstance() {
    return ApplicationManager.getApplication().getService(MavenRepositoriesProvider.class);
  }

  final Map<String, RepositoryBeanInfo> myRepositoriesMap = new THashMap<>();

  public MavenRepositoriesProvider() {
    final RepositoriesBean repositoriesBean =
      XmlSerializer.deserialize(MavenRepositoriesProvider.class.getResource("repositories.xml"), RepositoriesBean.class);

    RepositoryBeanInfo[] repositories = repositoriesBean.getRepositories();
    assert repositories != null;

    for (RepositoryBeanInfo repository : repositories) {
      registerRepository(repository.getId(), repository);
    }
  }

  public void registerRepository(@NotNull String id, RepositoryBeanInfo info) {
    myRepositoriesMap.put(id, info);
  }

  @NotNull
  public Set<String> getRepositoryIds() {
    return myRepositoriesMap.keySet();
  }

  @Nullable
  public String getRepositoryName(@Nullable String id) {
    RepositoryBeanInfo pair = myRepositoriesMap.get(id);
    return pair != null ? pair.getName() : null;
  }

  @Nullable
  public String getRepositoryUrl(@Nullable String id) {
    RepositoryBeanInfo pair = myRepositoriesMap.get(id);
    return pair != null ? pair.getUrl() : null;
  }
}


text:
#include "OptVar.hh"

ExistOptVar::ExistOptVar(int var,int scope) {
    varId = var;
    scopeId=scope;
}

int ExistOptVar::getVal(Strategy s) {
//    cout<<"getval on existoptvar "<<varId<<" at scope "<<scopeId<<endl;
    if (s.isTrue()) {cout<<"EOV "<<varId<<" scope "<<scopeId<<" try to get opt value on TRUE"<<endl;abort();}
    if (s.isFalse()) {cout<<"EOV "<<varId<<" scope "<<scopeId<<"Try to get opt value on FALSE"<<endl;abort();} // (sub)Strategy must neither be false
    if (s.isDummy()) {cout<<"EOV "<<varId<<" scope "<<scopeId<<"Try to get opt value on Dummy"<<endl;abort();} // nor begin with a universal scope
    if (s.scope() > scopeId) {cout<<"EOV "<<varId<<" scope "<<scopeId<<"Try to get opt value on  asubstrategy not containing opt variable"<<endl;abort();} // nor begin at a scope after the one we want ^^

    if (s.scope() == scopeId) return s.value(varId-s.VMin());
    // s.getTag() < scope
    Strategy nextScope = s.getChild(0);

    return getVal(nextScope);
}

int ExistOptVar::getScope() {return scopeId;}

UnivOptVar::UnivOptVar(int scope,OptVar* zevar, Aggregator* agg) {
    var=zevar;
    fct=agg;
    scopeId=scope;
}

int UnivOptVar::getVal(Strategy s) {
//    cout<<"getVal sur univoptvar "<<scopeId<<endl;
    vector<int> values; values.clear();
    if (s.isFalse()) {cout<<"UOV Try to get opt value on FALSE"<<endl;abort();}
    if (s.isTrue()) return fct->eval(values);
    if (s.isDummy()) {
        for (int i=0;i<s.degree();i++) {
            values.push_back(var->getVal(s.getChild(i)));
        }
        return fct->eval(values);
    }

    if (s.scope() == (scopeId-1)) {
        for (int i=0;i<s.degree();i++) {
            values.push_back(var->getVal(s.getChild(i)));
        }
        return fct->eval(values);
    }

    if (s.scope() < (scopeId-1) ) {
        if (s.quantifier()) {cout<<"UOV universal scope too soon"<<endl;abort();} // universal quantifier too soon
        return getVal(s.getChild(0));
    }
    // s.scope() > scope-1 -> too far away
    cout<<"UOV try to get aggregate on a substrategy not containing required scope"<<endl;
    abort();
    return 0; // dummy return to avoid a compiler complain...
}

int UnivOptVar::getScope() {return scopeId;}


text:
<?php
namespace FutureSVN\Shell;

use FutureProcess\FutureResult;
use React\Promise\PromiseInterface;
use FutureSVN\Exception\RuntimeException;

/**
 * @author Josh Di Fabio <joshdifabio@gmail.com>
 */
class FutureOutput
{
    private $futureResult;
    private $promise;
    private $error;

    public function __construct(FutureResult $futureResult)
    {
        $this->futureResult = $futureResult;

        $that = $this;
        $error = &$this->error;
        $this->promise = $futureResult->then(
            function (FutureResult $result) use ($that, &$error) {
                if (0 === $result->getExitCode()) {
                    return $that;
                }

                throw $error = new RuntimeException($result->getStreamContents(2));
            },
            function (\Exception $_error) use (&$error) {
                throw $error = $_error;
            }
        );
    }

    /**
     * @return string
     */
    public function getStreamContents()
    {
        $this->wait();

        return $this->futureResult->getStreamContents(1);
    }

    /**
     * @return resource
     */
    public function getStream()
    {
        $this->wait();

        return $this->futureResult->getStream(1);
    }

    /**
     * @param double $timeout OPTIONAL
     * @return static
     */
    public function wait($timeout = null)
    {
        $this->futureResult->wait($timeout);

        if ($this->error) {
            throw $this->error;
        }

        return $this;
    }

    /**
     * @return PromiseInterface
     */
    public function promise()
    {
        return $this->promise;
    }

    /**
     * @param callable $onFulfilled
     * @param callable $onError
     * @param callable $onProgress
     * @return PromiseInterface
     */
    public function then($onFulfilled = null, $onError = null, $onProgress = null)
    {
        return $this->promise->then($onFulfilled, $onError, $onProgress);
    }
}


text:
/*
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 *
 * Should you need to contact me, the author, you can do so either by
 * e-mail - mail your message to <vojtech@ucw.cz>, or by paper mail:
 * Vojtech Pavlik, Simunkova 1594, Prague 8, 182 00 Czech Republic
 */

#include "iforce.h"

void iforce_usb_xmit(struct iforce *iforce)
{
	int n, c;
	unsigned long flags;

	spin_lock_irqsave(&iforce->xmit_lock, flags);

	if (iforce->xmit.head == iforce->xmit.tail) {
		clear_bit(IFORCE_XMIT_RUNNING, iforce->xmit_flags);
		spin_unlock_irqrestore(&iforce->xmit_lock, flags);
		return;
	}

	((char *)iforce->out->transfer_buffer)[0] = iforce->xmit.buf[iforce->xmit.tail];
	XMIT_INC(iforce->xmit.tail, 1);
	n = iforce->xmit.buf[iforce->xmit.tail];
	XMIT_INC(iforce->xmit.tail, 1);

	iforce->out->transfer_buffer_length = n + 1;
	iforce->out->dev = iforce->usbdev;

	/* Copy rest of data then */
	c = CIRC_CNT_TO_END(iforce->xmit.head, iforce->xmit.tail, XMIT_SIZE);
	if (n < c) c=n;

	memcpy(iforce->out->transfer_buffer + 1,
	       &iforce->xmit.buf[iforce->xmit.tail],
	       c);
	if (n != c) {
		memcpy(iforce->out->transfer_buffer + 1 + c,
		       &iforce->xmit.buf[0],
		       n-c);
	}
	XMIT_INC(iforce->xmit.tail, n);

	if ( (n=usb_submit_urb(iforce->out, GFP_ATOMIC)) ) {
		clear_bit(IFORCE_XMIT_RUNNING, iforce->xmit_flags);
		dev_warn(&iforce->dev->dev, "usb_submit_urb failed %d\n", n);
	}

	/* The IFORCE_XMIT_RUNNING bit is not cleared here. That's intended.
	 * As long as the urb completion handler is not called, the transmiting
	 * is considered to be running */
	spin_unlock_irqrestore(&iforce->xmit_lock, flags);
}

static void iforce_usb_irq(struct urb *urb)
{
	struct iforce *iforce = urb->context;
	int status;

	switch (urb->status) {
	case 0:
		/* success */
		break;
	case -ECONNRESET:
	case -ENOENT:
	case -ESHUTDOWN:
		/* this urb is terminated, clean up */
		dbg("%s - urb shutting down with status: %d",
		    __func__, urb->status);
		return;
	default:
		dbg("%s - urb has status of: %d", __func__, urb->status);
		goto exit;
	}

	iforce_process_packet(iforce,
		(iforce->data[0] << 8) | (urb->actual_length - 1), iforce->data + 1);

exit:
	status = usb_submit_urb (urb, GFP_ATOMIC);
	if (status)
		err ("%s - usb_submit_urb failed with result %d",
		     __func__, status);
}

static void iforce_usb_out(struct urb *urb)
{
	struct iforce *iforce = urb->context;

	if (urb->status) {
		clear_bit(IFORCE_XMIT_RUNNING, iforce->xmit_flags);
		dbg("urb->status %d, exiting", urb->status);
		return;
	}

	iforce_usb_xmit(iforce);

	wake_up(&iforce->wait);
}

static void iforce_usb_ctrl(struct urb *urb)
{
	struct iforce *iforce = urb->context;
	if (urb->status) return;
	iforce->ecmd = 0xff00 | urb->actual_length;
	wake_up(&iforce->wait);
}

static int iforce_usb_probe(struct usb_interface *intf,
				const struct usb_device_id *id)
{
	struct usb_device *dev = interface_to_usbdev(intf);
	struct usb_host_interface *interface;
	struct usb_endpoint_descriptor *epirq, *epout;
	struct iforce *iforce;
	int err = -ENOMEM;

	interface = intf->cur_altsetting;

	epirq = &interface->endpoint[0].desc;
	epout = &interface->endpoint[1].desc;

	if (!(iforce = kzalloc(sizeof(struct iforce) + 32, GFP_KERNEL)))
		goto fail;

	if (!(iforce->irq = usb_alloc_urb(0, GFP_KERNEL)))
		goto fail;

	if (!(iforce->out = usb_alloc_urb(0, GFP_KERNEL)))
		goto fail;

	if (!(iforce->ctrl = usb_alloc_urb(0, GFP_KERNEL)))
		goto fail;

	iforce->bus = IFORCE_USB;
	iforce->usbdev = dev;

	iforce->cr.bRequestType = USB_TYPE_VENDOR | USB_DIR_IN | USB_RECIP_INTERFACE;
	iforce->cr.wIndex = 0;
	iforce->cr.wLength = cpu_to_le16(16);

	usb_fill_int_urb(iforce->irq, dev, usb_rcvintpipe(dev, epirq->bEndpointAddress),
			iforce->data, 16, iforce_usb_irq, iforce, epirq->bInterval);

	usb_fill_int_urb(iforce->out, dev, usb_sndintpipe(dev, epout->bEndpointAddress),
			iforce + 1, 32, iforce_usb_out, iforce, epout->bInterval);

	usb_fill_control_urb(iforce->ctrl, dev, usb_rcvctrlpipe(dev, 0),
			(void*) &iforce->cr, iforce->edata, 16, iforce_usb_ctrl, iforce);

	err = iforce_init_device(iforce);
	if (err)
		goto fail;

	usb_set_intfdata(intf, iforce);
	return 0;

fail:
	if (iforce) {
		usb_free_urb(iforce->irq);
		usb_free_urb(iforce->out);
		usb_free_urb(iforce->ctrl);
		kfree(iforce);
	}

	return err;
}

static void iforce_usb_disconnect(struct usb_interface *intf)
{
	struct iforce *iforce = usb_get_intfdata(intf);

	usb_set_intfdata(intf, NULL);

	input_unregister_device(iforce->dev);

	usb_free_urb(iforce->irq);
	usb_free_urb(iforce->out);
	usb_free_urb(iforce->ctrl);

	kfree(iforce);
}

static struct usb_device_id iforce_usb_ids [] = {
	{ USB_DEVICE(0x044f, 0xa01c) },		/* Thrustmaster Motor Sport GT */
	{ USB_DEVICE(0x046d, 0xc281) },		/* Logitech WingMan Force */
	{ USB_DEVICE(0x046d, 0xc291) },		/* Logitech WingMan Formula Force */
	{ USB_DEVICE(0x05ef, 0x020a) },		/* AVB Top Shot Pegasus */
	{ USB_DEVICE(0x05ef, 0x8884) },		/* AVB Mag Turbo Force */
	{ USB_DEVICE(0x05ef, 0x8888) },		/* AVB Top Shot FFB Racing Wheel */
	{ USB_DEVICE(0x061c, 0xc0a4) },         /* ACT LABS Force RS */
	{ USB_DEVICE(0x061c, 0xc084) },         /* ACT LABS Force RS */
	{ USB_DEVICE(0x06f8, 0x0001) },		/* Guillemot Race Leader Force Feedback */
	{ USB_DEVICE(0x06f8, 0x0003) },		/* Guillemot Jet Leader Force Feedback */
	{ USB_DEVICE(0x06f8, 0x0004) },		/* Guillemot Force Feedback Racing Wheel */
	{ USB_DEVICE(0x06f8, 0xa302) },		/* Guillemot Jet Leader 3D */
	{ }					/* Terminating entry */
};

MODULE_DEVICE_TABLE (usb, iforce_usb_ids);

struct usb_driver iforce_usb_driver = {
	.name =		"iforce",
	.probe =	iforce_usb_probe,
	.disconnect =	iforce_usb_disconnect,
	.id_table =	iforce_usb_ids,
};


text:
require "pp"
require "deep/hash/struct/pp/wrapper"
require "deep/hash/struct/pp/dashboard"
require "deep/hash/struct/pp/dashboard/table"
require "deep/hash/struct/pp/dashboard/table/row"
require "deep/hash/struct/pp/dashboard/table/tr"


text:
// Copyright 2015-2018 Sound Metrics Corp. All Rights Reserved.

using System;
using System.IO;
using System.Runtime.InteropServices;

namespace SoundMetrics.Aris.Files
{
    using static ArgChecks;
    using static MatchResult;
    using Int16Result = Result<Int16, ErrorInfo>;
    using UInt16Result = Result<UInt16, ErrorInfo>;
    using Int32Result = Result<Int32, ErrorInfo>;
    using UInt32Result = Result<UInt32, ErrorInfo>;
    using Int64Result = Result<Int64, ErrorInfo>;
    using UInt64Result = Result<UInt64, ErrorInfo>;

    /// <summary>
    /// Provides IO functions for typed reads and reads at specified positions
    /// in a stream.
    /// </summary>
    public static class ArisFileIO
    {
        /// <summary>
        /// Reads a Int16 from the stream at the given position.
        /// </summary>
        /// <param name="position">The position of interest.</param>
        /// <param name="stream">The stream being read.</param>
        /// <returns>The converted value read.</returns>
        public static Int16Result ReadInt16(long position, Stream stream) =>
            Read<Int16>(BitConverter.ToInt16, position, stream);

        /// <summary>
        /// Reads a UInt16 from the stream at the given position.
        /// </summary>
        /// <param name="position">The position of interest.</param>
        /// <param name="stream">The stream being read.</param>
        /// <returns>The converted value read.</returns>
        public static UInt16Result ReadUInt16(long position, Stream stream) =>
            Read<UInt16>(BitConverter.ToUInt16, position, stream);

        /// <summary>
        /// Reads a Int32 from the stream at the given position.
        /// </summary>
        /// <param name="position">The position of interest.</param>
        /// <param name="stream">The stream being read.</param>
        /// <returns>The converted value read.</returns>
        public static Result<Int32, ErrorInfo> ReadInt32(long position, Stream stream) =>
            Read<Int32>(BitConverter.ToInt32, position, stream);

        /// <summary>
        /// Reads a UInt32 from the stream at the given position.
        /// </summary>
        /// <param name="position">The position of interest.</param>
        /// <param name="stream">The stream being read.</param>
        /// <returns>The converted value read.</returns>
        public static Result<UInt32, ErrorInfo> ReadUInt32(long position, Stream stream) =>
            Read<UInt32>(BitConverter.ToUInt32, position, stream);

        /// <summary>
        /// Reads a Int64 from the stream at the given position.
        /// </summary>
        /// <param name="position">The position of interest.</param>
        /// <param name="stream">The stream being read.</param>
        /// <returns>The converted value read.</returns>
        public static Result<Int64, ErrorInfo> ReadInt64(long position, Stream stream) =>
            Read<Int64>(BitConverter.ToInt64, position, stream);

        /// <summary>
        /// Reads a UInt64 from the stream at the given position.
        /// </summary>
        /// <param name="position">The position of interest.</param>
        /// <param name="stream">The stream being read.</param>
        /// <returns>The converted value read.</returns>
        public static Result<UInt64, ErrorInfo> ReadUInt64(long position, Stream stream) =>
            Read<UInt64>(BitConverter.ToUInt64, position, stream);

        /// <summary>
        /// Reads a Single from the stream at the given position.
        /// </summary>
        /// <param name="position">The position of interest.</param>
        /// <param name="stream">The stream being read.</param>
        /// <returns>The converted value read.</returns>
        public static Result<Single, ErrorInfo> ReadSingle(long position, Stream stream) =>
            Read<Single>(BitConverter.ToSingle, position, stream);

        /// <summary>
        /// Reads a Double from the stream at the given position.
        /// </summary>
        /// <param name="position">The position of interest.</param>
        /// <param name="stream">The stream being read.</param>
        /// <returns>The converted value read.</returns>
        public static Result<Double, ErrorInfo> ReadDouble(long position, Stream stream) =>
            Read<Double>(BitConverter.ToDouble, position, stream);

        /// <summary>
        /// Writes a Int32 to the stream at the given position.
        /// </summary>
        /// <param name="position">The position of interest.</param>
        /// <param name="stream">The stream being written.</param>
        /// <param name="value">The value being written.</param>
        public static void WriteInt32(long position, Stream stream, Int32 value) =>
            Write(position, stream, BitConverter.GetBytes(value));

        /// <summary>
        /// Writes a UInt32 to the stream at the given position.
        /// </summary>
        /// <param name="position">The position of interest.</param>
        /// <param name="stream">The stream being written.</param>
        /// <param name="value">The value being written.</param>
        public static void WriteUInt32(long position, Stream stream, UInt32 value) =>
            Write(position, stream, BitConverter.GetBytes(value));

        /// <summary>
        /// Reads bytes from the specified position in the stream.
        /// </summary>
        /// <param name="position">The position of interest.</param>
        /// <param name="length">The number of bytes to be read.</param>
        /// <param name="stream">The stream to be read.</param>
        /// <returns>An array of bytes read, if successful; if the specified
        /// number of bytes cannot be read, and empty array is returned.</returns>
        private static Result<byte[], ErrorInfo> ReadBytes(long position, int length, Stream stream)
        {
            CheckMin(position, 0, nameof(position));
            CheckMin(length, 0, nameof(length));
            CheckNotNull(stream, nameof(stream));

            var buf = new byte[length];

            stream.Position = position;
            var readResult = stream.Read(buf, 0, buf.Length);
            if (readResult == buf.Length)
            {
                return Result<byte[], ErrorInfo>.Ok(buf);
            }
            else if (readResult == 0)
            {
                return Result<byte[], ErrorInfo>.Error(
                    ErrorInfo.Create($"Nothing to read at position {position}; stream size is {stream.Length}"));
            }
            else // readResult != 0
            {
                return Result<byte[], ErrorInfo>.Error(
                    ErrorInfo.Create($"Value incomplete at position {position}"));
            }
        }

        private static Result<T, ErrorInfo> Read<T>(Func<byte[], int, T> convert, long position, Stream stream)
            where T : struct
        {
            CheckNotNull(convert, nameof(convert));
            CheckMin(position, 0, nameof(position));
            CheckNotNull(stream, nameof(stream));

            var length = Marshal.SizeOf<T>();
            var bytes = ReadBytes(position, length, stream);

            return Match(bytes,
                onOk: result => Result<T, ErrorInfo>.Ok(convert(result, 0)),
                onError: msg => Result<T, ErrorInfo>.Error(msg));
        }

        private static void Write(long position, Stream stream, byte[] buf)
        {
            CheckMin(position, 0, nameof(position));
            CheckNotNull(stream, nameof(stream));
            CheckNotNull(buf, nameof(buf));

            stream.Position = position;
            stream.Write(buf, 0, buf.Length);
        }

        private static readonly Lazy<byte[]> Empty = new Lazy<byte[]>(() => Array.Empty<byte>());
    }
}


text:
package jcrib;

public class Action {

    private GameState state;
    private int stateToken;
    private int cardNumber;

    public Action(GameState state, int stateToken, int cardNumber) {
        this.state = state;
        this.stateToken = stateToken;
        this.cardNumber = cardNumber;
    }

    public GameState getState() {
        return state;
    }

    public int getStateToken() {
        return stateToken;
    }

    public int getCardNumber() {
        return cardNumber;
    }
}


text:
template <typename R, typename... Args> \
struct ConceptName<R(Args...) CVQualifier RefQualifier> { \
private: \
    template <typename> \
    friend class raspberry::_detail::BaseAny; \
    template <typename> \
    friend struct raspberry::_detail::Any_BeamConf; \
    template <typename AnyImpl> \
    friend struct raspberry::_detail::anyimpl::AnyImpl_BeamConf; \
    template <typename> \
    friend struct raspberry::_detail::anyimplbase::AnyImplBase_BeamConf; \
    template <typename Next, typename Ancestor> \
    struct Virtual : Next { \
        using Next::FuncName; \
        virtual R FuncName(Args...) CVQualifier RefQualifier = 0; \
    }; \
    template <typename Next> \
    struct Virtual<Next,void> : Next { \
        virtual R FuncName(Args...) CVQualifier RefQualifier = 0; \
    }; \
    template <typename Impl, typename Base> \
    struct VirtualImpl : Base { \
        virtual R FuncName(Args... args) CVQualifier RefQualifier override final { \
            using Value = typename Impl::value_type; \
            using QValue = raspberry::_detail::MakeRef_t<CVQualifier Value RefQualifier>; \
            const auto& self = static_cast<const Impl&>(*this); \
            const auto& value = self.get_value(); \
            return const_cast<QValue>(value).FuncName(std::forward<Args>(args)...); \
        } \
    }; \
    template <typename Impl, typename Next, typename Ancestor> \
    struct NonVirtual : Next { \
        using Next::FuncName; \
        R FuncName(Args... args) CVQualifier RefQualifier { \
            using Base = raspberry::_detail::AnyImplBase<raspberry::_detail::GetConfig_t<Impl>>; \
            using QBase = raspberry::_detail::MakeRef_t<CVQualifier Base RefQualifier>; \
            auto& self = static_cast<const Impl&>(*this); \
            auto& base = self._raspberry_get_impl(); \
            return const_cast<QBase>(base).FuncName(std::forward<Args>(args)...); \
        } \
    }; \
    template <typename Impl, typename Next> \
    struct NonVirtual<Impl,Next,void> : Next { \
        R FuncName(Args... args) CVQualifier RefQualifier { \
            using Base = raspberry::_detail::AnyImplBase<raspberry::_detail::GetConfig_t<Impl>>; \
            using QBase = raspberry::_detail::MakeRef_t<CVQualifier Base RefQualifier>; \
            const auto& self = static_cast<const Impl&>(*this); \
            const auto& base = self._raspberry_get_impl(); \
            return const_cast<QBase>(base).FuncName(std::forward<Args>(args)...); \
        } \
    }; \
}

/// Declares a concept named ConceptName that implements the FuncName method.
#define RASPBERRY_DECL_METHOD(ConceptName, FuncName) \
template <typename Func> \
struct ConceptName; \
RASPBERRY_DETAIL_QUALIFIED_METHOD(ConceptName, FuncName, , ); \
RASPBERRY_DETAIL_QUALIFIED_METHOD(ConceptName, FuncName, , &); \
RASPBERRY_DETAIL_QUALIFIED_METHOD(ConceptName, FuncName, , &&); \
RASPBERRY_DETAIL_QUALIFIED_METHOD(ConceptName, FuncName, const, ); \
RASPBERRY_DETAIL_QUALIFIED_METHOD(ConceptName, FuncName, const, &); \
RASPBERRY_DETAIL_QUALIFIED_METHOD(ConceptName, FuncName, const, &&)

namespace raspberry {

namespace _detail {

namespace typelist {

    /// A simple list of types.
    template <typename...>
    struct TypeList {};

    template <typename...>
    struct TypeListCat;

    /// Concatenates any number of TypeLists into a single TypeList.
    template <typename... Ts>
    using TypeListCat_t = typename TypeListCat<Ts...>::type;

    template <typename... As, typename... Bs, typename... Tail>
    struct TypeListCat<TypeList<As...>, TypeList<Bs...>, Tail...> {
        using type = TypeListCat_t<TypeList<As..., Bs...>, Tail...>;
    };

    template <typename T>
    struct TypeListCat<T> {
        using type = T;
    };

    template <>
    struct TypeListCat<> {
        using type = TypeList<>;
    };

} // namespace typelist

using typelist::TypeList;
using typelist::TypeListCat_t;

namespace makeref {

    template <typename T>
    struct MakeRef {
        using type = T&;
    };

    /// Given T with underlying type U, maps { U -> U&, U& -> U&, U&& -> U&& }.
    template <typename T>
    using MakeRef_t = typename MakeRef<T>::type;

    template <typename T>
    struct MakeRef<T&&> {
        using type = T&&;
    };

} // namespace makeref

using makeref::MakeRef_t;

// Forward declarations.
template <typename Config>
class BaseAny;
template <typename... Concepts>
class Any;

namespace inheritance {

    template <typename, typename>
    struct InheritAll;

    /// Inherits from each `Config::Base<T>` for each `T` in `Types`.
    template <typename Config, typename Types>
    using InheritAll_t = typename InheritAll<Config,Types>::type;

    template <typename Config, typename... Ts>
    struct InheritAll<Config, TypeList<Ts...>> {
        struct type : Config::template Base<Ts>... {};
    };

    template<typename, typename, typename>
    struct BeamInheritance;

    /// Converts multiple inheritance into a chain of single inheritance (to avoid arithmetic on `this` pointer).
    /// `Conf::Base` is the leaf base class.
    /// `Conf::Link<H, B, T...>` is invoked using mutual recursion.
    /// - `H` is the current element in `Types...`
    /// - `B` is the current base class that `Link` must inherit from (it will either be the next `Link` or `Base`)
    /// - `T...` is a list of the remaining elements of `Types...`
    template<typename Conf, typename Types, typename SuperConf = Conf>
    using BeamInheritance_t = typename BeamInheritance<Conf, Types, SuperConf>::type;

    template<typename Conf, typename SuperConf>
    struct BeamInheritance<Conf, TypeList<>, SuperConf> {
        using type = typename Conf::Base;
    };

    template<typename Conf, typename HeadConcept, typename... TailConcepts, typename SuperConf>
    struct BeamInheritance<Conf, TypeList<HeadConcept, TailConcepts...>, SuperConf> {
        using type = typename Conf::template Link<HeadConcept, BeamInheritance_t<SuperConf, TypeList<TailConcepts...>>, TailConcepts...>;
    };

} // namespace inheritance

using inheritance::InheritAll_t;
using inheritance::BeamInheritance_t;

namespace find_overload {

    template <typename, typename...>
    struct FindOverloadOrVoid;

    /// Given T = C<X>, searches Us for C<Y> and returns it, else returns void.
    template <typename T, typename... Us>
    using FindOverloadOrVoid_t = typename FindOverloadOrVoid<T,Us...>::type;

    template <typename T>
    struct FindOverloadOrVoid<T> {
        using type = void;
    };

    template <typename T, typename U, typename... Vs>
    struct FindOverloadOrVoid<T,U,Vs...> {
        using type = FindOverloadOrVoid_t<T,Vs...>;
    };

    template <template <typename> class C, typename T, typename U, typename... Vs>
    struct FindOverloadOrVoid<C<T>,C<U>,Vs...> {
        using type = C<U>;
    };

} // namespace find_overload

using find_overload::FindOverloadOrVoid_t;

namespace get_config {

    template <typename Any>
    struct GetConfig;

    /// Given a `BaseAny<Config>`, returns `Config`.
    template <typename Any>
    using GetConfig_t = typename GetConfig<Any>::type;

    template <typename Config>
    struct GetConfig<BaseAny<Config>> {
        using type = Config;
    };

} // namespace get_config

using get_config::GetConfig_t;

namespace anyimplbase {

    template <typename Config>
    struct AnyImplBase_BeamConf {
        struct BaseConfig {
            template <typename Any>
            using Base = typename Any::_raspberry_impl_base;
        };
        using Base = InheritAll_t<BaseConfig, typename Config::Bases>;
        template <typename Concept, typename Next, typename... TailConcepts>
        using Link = typename Concept::template Virtual<Next,FindOverloadOrVoid_t<Concept,TailConcepts...>>;
    };

    template <typename Config>
    struct AnyImplBase : BeamInheritance_t<AnyImplBase_BeamConf<Config>, typename Config::Concepts> {
        virtual ~AnyImplBase() = 0;
    };

    template <typename Config>
    inline AnyImplBase<Config>::~AnyImplBase() {}

} // namespace anyimplbase

using anyimplbase::AnyImplBase;

namespace anyimpl {

    template <typename T, typename Config>
    struct AnyImpl;

    template <typename AnyImpl>
    struct AnyImpl_BeamConf;

    template <typename T, typename Config>
    struct AnyImpl_BeamConf<AnyImpl<T,Config>> {
        using Base = AnyImplBase<Config>;
        template <typename Concept, typename Next, typename... TailConcepts>
        using Link = typename Concept::template VirtualImpl<AnyImpl<T,Config>, Next>;
    };

    /// Implementation that contains a value.
    template <typename T, typename Config>
    struct AnyImpl final : BeamInheritance_t<AnyImpl_BeamConf<AnyImpl<T,Config>>, typename Config::AllConcepts> {
        using value_type = T;
        value_type value;
        AnyImpl(const value_type& value) : value(value) {}
        AnyImpl(value_type&& value) : value(std::move(value)) {}
        const value_type& get_value() const { return value; }
    };

    /// Specialized implementation that contains a reference.
    /// Must not outlive the referred-to object.
    template <typename T, typename Config>
    struct AnyImpl<T&,Config> final : BeamInheritance_t<AnyImpl_BeamConf<AnyImpl<T&,Config>>, typename Config::AllConcepts> {
        using value_type = T;
        value_type& value;
        AnyImpl(value_type& value) : value(value) {}
        const value_type& get_value() const { return value; }
    };

    /// Specialized implementation that contains a pointer.
    /// Must not outlive the pointed-to object.
    template <typename T, typename Config>
    struct AnyImpl<T*,Config> final : BeamInheritance_t<AnyImpl_BeamConf<AnyImpl<T*,Config>>, typename Config::AllConcepts> {
        using value_type = T;
        value_type* value;
        AnyImpl(value_type* value) : value(value) {}
        const value_type& get_value() const { return *value; }
    };

    /// Specialized implementation that contains a std::unique_pointer.
    template <typename T, typename Config>
    struct AnyImpl<std::unique_ptr<T>,Config> final : BeamInheritance_t<AnyImpl_BeamConf<AnyImpl<std::unique_ptr<T>,Config>>, typename Config::AllConcepts> {
        using value_type = T;
        std::unique_ptr<T> value;
        AnyImpl(std::unique_ptr<T> value) : value(std::move(value)) {}
        const value_type& get_value() const { return *value; }
    };

    /// Specialized implementation that contains a std::shared_pointer.
    template <typename T, typename Config>
    struct AnyImpl<std::shared_ptr<T>,Config> final : BeamInheritance_t<AnyImpl_BeamConf<AnyImpl<std::shared_ptr<T>,Config>>, typename Config::AllConcepts> {
        using value_type = T;
        std::shared_ptr<T> value;
        AnyImpl(std::shared_ptr<T> value) : value(std::move(value)) {}
        const value_type& get_value() const { return *value; }
    };

} // namespace anyimpl

using anyimpl::AnyImpl;

/// Tags used for BaseAny constructor dispatching.
struct Tags {
    using Default = struct{};
    using Reference = struct{};
    using Derived = struct{};
    using Unrelated = struct{};
    using Pointer = struct{};
};

namespace get_tag {

    template <typename T, typename Config>
    struct GetTag {
        using type = Tags::Default;
    };

    /// Selects the appropriate tag for constructor dispatching.
    template <typename T, typename Config>
    using GetTag_t = typename GetTag<std::decay_t<T>,Config>::type;

    template <typename T, typename Config>
    struct GetTag<std::reference_wrapper<T>, Config> {
        using type = Tags::Reference;
    };

    template <typename... Ts, typename Config>
    struct GetTag<Any<Ts...>, Config> {
        using type = std::conditional_t<std::is_base_of<AnyImplBase<Config>, typename Any<Ts...>::_raspberry_impl_base>::value, Tags::Derived, Tags::Unrelated>;
    };

    template <typename T, typename Config>
    struct GetTag<T*, Config> {
        using type = Tags::Pointer;
    };

    template <typename T, typename Config>
    struct GetTag<std::unique_ptr<T>, Config> {
        using type = Tags::Pointer;
    };

    template <typename T, typename Config>
    struct GetTag<std::shared_ptr<T>, Config> {
        using type = Tags::Pointer;
    };

} // namespace get_tag

using get_tag::GetTag_t;

template <typename Any>
struct Any_BeamConf;

template <typename Config>
struct Any_BeamConf<BaseAny<Config>> {
    struct BaseConfig {
        template <typename SuperAny>
        using Base = BeamInheritance_t<Any_BeamConf, typename GetConfig_t<SuperAny>::Concepts, Any_BeamConf<SuperAny>>;
    };
    using Any = BaseAny<Config>;
    using Base = InheritAll_t<BaseConfig, typename GetConfig_t<Any>::Bases>;
    template <typename Concept, typename Next, typename... TailConcepts>
    using Link = typename Concept::template NonVirtual<Any,Next,FindOverloadOrVoid_t<Concept,TailConcepts...>>;
};

/// The backbone of Any.
template <typename Config>
class BaseAny : public BeamInheritance_t<Any_BeamConf<BaseAny<Config>>, typename Config::Concepts> {
    template <typename>
    friend class BaseAny;

    /// Pointer to implementation.
    std::unique_ptr<AnyImplBase<Config>> _raspberry_impl_ptr;

public:
    using _raspberry_impl_base = AnyImplBase<Config>;

    /// Any must never be empty.
    BaseAny() = delete;

    /// Dispatcher.
    template <typename T>
    BaseAny(T&& t) : BaseAny(std::forward<T>(t), GetTag_t<T,Config>{})
    {}

    /// Default behavior for storing most types.
    template <typename T>
    BaseAny(T&& t, Tags::Default) : _raspberry_impl_ptr(std::make_unique<AnyImpl<std::decay_t<T>,Config>>(std::forward<T>(t)))
    {}

    /// Stores a reference instead of a value.
    /// Use with caution; this Any must not outlive the given reference.
    template <typename T>
    BaseAny(const std::reference_wrapper<T>& t, Tags::Reference) : _raspberry_impl_ptr(std::make_unique<AnyImpl<T&,Config>>(t.get()))
    {}

    /// Derived to base Any upcast.
    /// This is equivalent to a static_cast, no allocation is used.
    template <typename T>
    BaseAny(T&& t, Tags::Derived) : _raspberry_impl_ptr(std::forward<T>(t)._raspberry_impl_ptr)
    {}

    /// Stores an unrelated Any as if it were a normal type.
    /// Guarantees dynamic allocation; consider using Any concept inheritance instead.
    template <typename T>
    [[deprecated("Conversion between unrelated Anys causes unnecessary dynamic allocation.")]]
    BaseAny(T&& t, Tags::Unrelated) : BaseAny(std::forward<T>(t), Tags::Default{})
    {}

    /// Stores a pointer instead of a value.
    /// \note Raw pointers will not be deleted, and cannot be retrieved.
    template <typename T>
    BaseAny(T&& t, Tags::Pointer) : BaseAny(std::forward<T>(t), Tags::Default{})
    {}

    /// Gets a pointer to the implementation.
    const _raspberry_impl_base& _raspberry_get_impl() const {
        return *_raspberry_impl_ptr;
    }
};

namespace concept_filter {

    template <typename... Concepts>
    struct ConceptFilter;

    template <typename ConceptList, typename BaseList, typename... Concepts>
    struct ConceptFilterImpl;

    template <typename... PrevConcepts, typename... PrevBases, typename... Nested, typename... Concepts>
    struct ConceptFilterImpl <TypeList<PrevConcepts...>, TypeList<PrevBases...>, Any<Nested...>, Concepts...> :
        ConceptFilterImpl<TypeList<PrevConcepts...>, TypeList<PrevBases..., BaseAny<ConceptFilter<Nested...>>>, Concepts...>
    {};

    template <typename... PrevConcepts, typename... PrevBases, typename HeadConcept, typename... Concepts>
    struct ConceptFilterImpl <TypeList<PrevConcepts...>, TypeList<PrevBases...>, HeadConcept, Concepts...> :
        ConceptFilterImpl<TypeList<PrevConcepts..., HeadConcept>, TypeList<PrevBases...>, Concepts...>
    {};

    template <typename, typename>
    struct CollapseConcepts;

    /// Recursively unwraps Bases into their concepts and returns a flat list of all the concepts, including Concepts.
    /// Example: `CollapseConcepts_t<{C0, C4}, {Any<C1>, Any<Any<C2>,C3>}> => {C0, C4, C1, C2, C3}`
    template <typename Concepts, typename Bases>
    using CollapseConcepts_t = typename CollapseConcepts<Concepts,Bases>::type;

    template <typename Concepts, typename... BaseFilters>
    struct CollapseConcepts<Concepts, TypeList<BaseAny<BaseFilters>...>> {
        using type = TypeListCat_t<Concepts, typename BaseFilters::AllConcepts...>;
    };

    template <typename PrevConcepts, typename PrevBases>
    struct ConceptFilterImpl <PrevConcepts, PrevBases> {
        using Concepts = PrevConcepts;
        using Bases = PrevBases;
        using AllConcepts = CollapseConcepts_t<Concepts, Bases>;
    };

    /// Filters parameters into a list of concepts and a list of Any bases.
    template <typename... Concepts>
    struct ConceptFilter : ConceptFilterImpl<TypeList<>, TypeList<>, Concepts...> {};

} // namespace concept_filter

using concept_filter::ConceptFilter;

/// Erasure container.
/// All-natural replacement for inheritance.
template <typename... Concepts>
class Any : public BaseAny<ConceptFilter<Concepts...>> {
    using Base = BaseAny<ConceptFilter<Concepts...>>;
public:
    using Base::BaseAny;
};

} // namespace _detail

using _detail::Any;

} // namespace Raspberry

#endif // RASPBERRY_HPP


text:
import _ from 'lodash';

export default function initLogger(plugin) {
  const { log } = plugin.settings.app;

  if (log) {
    const logMessages = _.isArray(log) ? log : [log];
    plugin.on('log', (message) => {
      if (message.tags.indexOf('odyssee') > -1) {
        if (_.intersection(message.tags, logMessages).length) {
          console.log(message.tags, message.data);
        }
      }
    });
  }
}


text:
/* tslint:disable:no-mergeable-namespace no-namespace */
"use strict";

import conventionalChangelogPresetLoader from "conventional-changelog-preset-loader";

namespace Module {
    declare const path: string;
    declare const config: conventionalChangelogPresetLoader.Config;

    // $ExpectType Config<Commit<string | number | symbol>, Context>
    conventionalChangelogPresetLoader(path);
    // $ExpectType Config<Commit<string | number | symbol>, Context>
    conventionalChangelogPresetLoader(config);

    // $ExpectError
    conventionalChangelogPresetLoader();
}

namespace Module.presetLoader {
    declare const require: conventionalChangelogPresetLoader.presetLoader.RequireMethod;

    // $ExpectType typeof conventionalChangelogPresetLoader
    conventionalChangelogPresetLoader.presetLoader(require);

    // $ExpectError
    conventionalChangelogPresetLoader.presetLoader();
}

namespace Module.Config {
    declare const config: conventionalChangelogPresetLoader.Config;

    // $ExpectType Config
    config;
    config.name; // $ExpectType string
}


text:
namespace CodeGenerator
{
    public interface ICodeGenerator
    {
        void GenerateToFile(string message, string filePath);
    }
}


text:
START_ATF_NAMESPACE
    namespace Detail
    {
        Info::_DTRADE_ITEMReleaseData2_ptr _DTRADE_ITEMReleaseData2_next(nullptr);
        Info::_DTRADE_ITEMReleaseData2_clbk _DTRADE_ITEMReleaseData2_user(nullptr);

        Info::_DTRADE_ITEMSetData4_ptr _DTRADE_ITEMSetData4_next(nullptr);
        Info::_DTRADE_ITEMSetData4_clbk _DTRADE_ITEMSetData4_user(nullptr);

        void _DTRADE_ITEMReleaseData2_wrapper(struct _DTRADE_ITEM* _this)
        {
           _DTRADE_ITEMReleaseData2_user(_this, _DTRADE_ITEMReleaseData2_next);
        };
        void _DTRADE_ITEMSetData4_wrapper(struct _DTRADE_ITEM* _this, char p_byStorageCode, unsigned int p_dwSerial, char p_byAmount)
        {
           _DTRADE_ITEMSetData4_user(_this, p_byStorageCode, p_dwSerial, p_byAmount, _DTRADE_ITEMSetData4_next);
        };

        ::std::array<hook_record, 2> _DTRADE_ITEM_functions =
        {
            _hook_record {
                (LPVOID)0x1400f79f0L,
                (LPVOID *)&_DTRADE_ITEMReleaseData2_user,
                (LPVOID *)&_DTRADE_ITEMReleaseData2_next,
                (LPVOID)cast_pointer_function(_DTRADE_ITEMReleaseData2_wrapper),
                (LPVOID)cast_pointer_function((void(_DTRADE_ITEM::*)())&_DTRADE_ITEM::ReleaseData)
            },
            _hook_record {
                (LPVOID)0x1400f7a10L,
                (LPVOID *)&_DTRADE_ITEMSetData4_user,
                (LPVOID *)&_DTRADE_ITEMSetData4_next,
                (LPVOID)cast_pointer_function(_DTRADE_ITEMSetData4_wrapper),
                (LPVOID)cast_pointer_function((void(_DTRADE_ITEM::*)(char, unsigned int, char))&_DTRADE_ITEM::SetData)
            },
        };
    }; // end namespace Detail
END_ATF_NAMESPACE


text:
package org.caleydo.core.serialize;

import java.util.List;

import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

import org.caleydo.core.data.datadomain.ADataDomain;

/**
 * Collection-class for a list of all data domains to store
 *
 * @author Marc Streit
 */
@XmlType
@XmlRootElement
public class DataDomainList {

	/** list of all data domains to (re-)store */
	private List<? extends ADataDomain> dataDomains;

	@XmlElementWrapper
	public List<? extends ADataDomain> getDataDomains() {
		return dataDomains;
	}

	public void setDataDomains(List<? extends ADataDomain> dataDomains) {
		this.dataDomains = dataDomains;
	}
}