text:
<?xml version="1.0" encoding="UTF-8"?>
<RETSComplianceTest>
    <TestName>DMQL Dynamic Tests</TestName>
    <TestDescription>Test DMQL query language by using user's selections in TestParameters</TestDescription>
    <SearchTransaction>
        <TransactionLabel>DMQL Numeric Search - Minimum Value</TransactionLabel>
        <SearchType>${DMQL.Search.SearchType}</SearchType>
        <SearchClass>${DMQL.SearchClass}</SearchClass>
        <Query>(${DMQL.System.Decimal.Minimum.Field} = ${DMQL.System.Decimal.Minimum.Value}+)</Query>
        <QueryType>DMQL2</QueryType>
        <Count>1</Count>
        <Format>COMPACT-DECODED</Format>
        <Limit>2</Limit>
        <Offset>1</Offset>
        <StandardNames>0</StandardNames>
        <TestEvaluators>
            <JavaClassName>com.realtor.rets.compliance.tests.dmql.DMQLSystemNumericResultsMin</JavaClassName>
        </TestEvaluators>
    </SearchTransaction>
    <SearchTransaction>
        <TransactionLabel>DMQL Numeric Search - Maximum Value</TransactionLabel>
        <SearchType>${DMQL.Search.SearchType}</SearchType>
        <SearchClass>${DMQL.SearchClass}</SearchClass>
        <Query>(${DMQL.System.Decimal.Maximum.Field} = ${DMQL.System.Decimal.Maximum.Value}-)</Query>
        <QueryType>DMQL2</QueryType>
        <Count>1</Count>
        <Format>COMPACT-DECODED</Format>
        <Limit>2</Limit>
        <Offset>1</Offset>
        <StandardNames>0</StandardNames>
        <TestEvaluators>
            <JavaClassName>com.realtor.rets.compliance.tests.dmql.DMQLSystemNumericResultsMax</JavaClassName>
        </TestEvaluators>
    </SearchTransaction>
    <SearchTransaction>
        <TransactionLabel>DMQL Numeric Search - Range</TransactionLabel>
        <SearchType>${DMQL.Search.SearchType}</SearchType>
        <SearchClass>${DMQL.SearchClass}</SearchClass>
        <Query>(${DMQL.System.Decimal.RangeHigh.Field} = ${DMQL.System.Decimal.RangeLow.Value}-${DMQL.System.Decimal.RangeHigh.Value})</Query>
        <QueryType>DMQL2</QueryType>
        <Count>1</Count>
        <Format>COMPACT-DECODED</Format>
        <Limit>2</Limit>
        <Offset>1</Offset>
        <StandardNames>0</StandardNames>
        <TestEvaluators>
            <JavaClassName>com.realtor.rets.compliance.tests.dmql.DMQLSystemNumericResultsRange</JavaClassName>
        </TestEvaluators>
    </SearchTransaction>
    <SearchTransaction>
        <TransactionLabel>DMQL Character Search - AND</TransactionLabel>
        <SearchType>${DMQL.Search.SearchType}</SearchType>
        <SearchClass>${DMQL.SearchClass}</SearchClass>
        <Query>(${DMQL.System.Character.AndOr.Field} = ${DMQL.System.Character.AndOr.Value}), (${DMQL.System.Decimal.Maximum.Field} = ${DMQL.System.Decimal.Maximum.Value}-)</Query>
        <QueryType>DMQL2</QueryType>
        <Count>1</Count>
        <Format>COMPACT-DECODED</Format>
        <Limit>2</Limit>
        <Offset>1</Offset>
        <StandardNames>0</StandardNames>
        <TestEvaluators>
            <JavaClassName>com.realtor.rets.compliance.tests.dmql.DMQLSystemCharResultsAND</JavaClassName>
        </TestEvaluators>
    </SearchTransaction>
    <SearchTransaction>
        <TransactionLabel>DMQL Character Search - OR</TransactionLabel>
        <SearchType>${DMQL.Search.SearchType}</SearchType>
        <SearchClass>${DMQL.SearchClass}</SearchClass>
        <Query>(${DMQL.System.Character.AndOr.Field} = ${DMQL.System.Character.AndOr.Value}) | (${DMQL.System.Decimal.Maximum.Field} = ${DMQL.System.Decimal.Maximum.Value}-)</Query>
        <QueryType>DMQL2</QueryType>
        <Count>1</Count>
        <Format>COMPACT-DECODED</Format>
        <Limit>2</Limit>
        <Offset>1</Offset>
        <StandardNames>0</StandardNames>
        <TestEvaluators>
            <JavaClassName>com.realtor.rets.compliance.tests.dmql.DMQLSystemCharResultsOR</JavaClassName>
        </TestEvaluators>
    </SearchTransaction>
    <SearchTransaction>
        <TransactionLabel>DMQL Character Search - Starts With</TransactionLabel>
        <SearchType>${DMQL.Search.SearchType}</SearchType>
        <SearchClass>${DMQL.SearchClass}</SearchClass>
        <Query>(${DMQL.System.Character.StartsWith.Field} = ${DMQL.System.Character.StartsWith.Value}*)</Query>
        <QueryType>DMQL2</QueryType>
        <Count>1</Count>
        <Format>COMPACT-DECODED</Format>
        <Limit>2</Limit>
        <Offset>1</Offset>
        <StandardNames>0</StandardNames>
        <TestEvaluators>
            <JavaClassName>com.realtor.rets.compliance.tests.dmql.DMQLSystemCharResultsStarts</JavaClassName>
        </TestEvaluators>
    </SearchTransaction>
    <SearchTransaction>
        <TransactionLabel>DMQL Character Search - Contains</TransactionLabel>
        <SearchType>${DMQL.Search.SearchType}</SearchType>
        <SearchClass>${DMQL.SearchClass}</SearchClass>
        <Query>(${DMQL.System.Character.Contains.Field} = *${DMQL.System.Character.Contains.Value}*)</Query>
        <QueryType>DMQL2</QueryType>
        <Count>1</Count>
        <Format>COMPACT-DECODED</Format>
        <Limit>2</Limit>
        <Offset>1</Offset>
        <StandardNames>0</StandardNames>
        <TestEvaluators>
            <JavaClassName>com.realtor.rets.compliance.tests.dmql.DMQLSystemCharResultsContains</JavaClassName>
        </TestEvaluators>
    </SearchTransaction>
    <SearchTransaction>
        <TransactionLabel>DMQL Date Search - After This Date</TransactionLabel>
        <SearchType>${DMQL.Search.SearchType}</SearchType>
        <SearchClass>${DMQL.SearchClass}</SearchClass>
        <Query>(${DMQL.System.Date.Minimum.Field} = ${DMQL.System.Date.Minimum.Value}+)</Query>
        <QueryType>DMQL2</QueryType>
        <Count>1</Count>
        <Format>COMPACT-DECODED</Format>
        <Limit>2</Limit>
        <Offset>1</Offset>
        <StandardNames>0</StandardNames>
        <TestEvaluators>
            <JavaClassName>com.realtor.rets.compliance.tests.dmql.DMQLSystemDateResultsMin</JavaClassName>
        </TestEvaluators>
    </SearchTransaction>
    <SearchTransaction>
        <TransactionLabel>DMQL Date Search - Before This Date</TransactionLabel>
        <SearchType>${DMQL.Search.SearchType}</SearchType>
        <SearchClass>${DMQL.SearchClass}</SearchClass>
        <Query>(${DMQL.System.Date.Maximum.Field} = ${DMQL.System.Date.Maximum.Value}-)</Query>
        <QueryType>DMQL2</QueryType>
        <Count>1</Count>
        <Format>COMPACT-DECODED</Format>
        <Limit>2</Limit>
        <Offset>1</Offset>
        <StandardNames>0</StandardNames>
        <TestEvaluators>
            <JavaClassName>com.realtor.rets.compliance.tests.dmql.DMQLSystemDateResultsMax</JavaClassName>
        </TestEvaluators>
    </SearchTransaction>
    <SearchTransaction>
        <TransactionLabel>DMQL Date Search - Today</TransactionLabel>
        <SearchType>${DMQL.Search.SearchType}</SearchType>
        <SearchClass>${DMQL.SearchClass}</SearchClass>
        <Query>(${DMQL.System.Date.Today.Field} = TODAY)</Query>
        <QueryType>DMQL2</QueryType>
        <Count>1</Count>
        <Format>COMPACT-DECODED</Format>
        <Limit>2</Limit>
        <Offset>1</Offset>
        <StandardNames>0</StandardNames>
        <TestEvaluators>
            <JavaClassName>com.realtor.rets.compliance.tests.dmql.DMQLSystemDateResultsToday</JavaClassName>
        </TestEvaluators>
    </SearchTransaction>
    <TestEvaluators>
        <JavaClassName>com.realtor.rets.compliance.tests.CheckWellFormed</JavaClassName>
        <JavaClassName>com.realtor.rets.compliance.tests.CheckOptionalResponseHeaders</JavaClassName>
        <JavaClassName>com.realtor.rets.compliance.tests.CheckResponseHeaders</JavaClassName>
    </TestEvaluators>
</RETSComplianceTest>


text:
layout: post
microblog: true
audio:
photo:
date: 2017-08-15 10:09:28 -0700
guid: http://curt.micro.blog/2017/08/15/the-intellectual-virtues.html
---
"The intellectual virtues may seem elitist, but once a country tolerates dishonesty, incuriosity and intellectual laziness, then everything else falls apart." —[David Brooks](https://www.nytimes.com/2017/08/15/opinion/fanaticism-white-nationalists-charlottesville.html?smprod=nytcore-ipad&smid=nytcore-ipad-share)

redpajama_set_name: RedPajamaGithub


text:
/* Stuff that reads stuff from the server. */

#include <assert.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <errno.h>

#include "xcb.h"
#include "xcbext.h"
#include "xcbint.h"
#if USE_POLL
#include <poll.h>
#endif
#ifndef _WIN32
#include <sys/select.h>
#include <sys/socket.h>
#endif

#ifdef _WIN32
#include "xcb_windefs.h"
#endif /* _WIN32 */

#define XCB_ERROR 0
#define XCB_REPLY 1
#define XCB_XGE_EVENT 35

/* required for compiling for Win32 using MinGW */
#ifndef MSG_WAITALL
#define MSG_WAITALL 0
#endif

struct event_list {
    xcb_generic_event_t *event;
    struct event_list *next;
};

struct reply_list {
    void *reply;
    struct reply_list *next;
};

typedef struct pending_reply {
    uint64_t first_request;
    uint64_t last_request;
    enum workarounds workaround;
    int flags;
    struct pending_reply *next;
} pending_reply;

typedef struct reader_list {
    uint64_t request;
    pthread_cond_t *data;
    struct reader_list *next;
} reader_list;

static void remove_finished_readers(reader_list **prev_reader, uint64_t completed)
{
    while(*prev_reader && XCB_SEQUENCE_COMPARE((*prev_reader)->request, <=, completed))
    {
        /* If you don't have what you're looking for now, you never
         * will. Wake up and leave me alone. */
        pthread_cond_signal((*prev_reader)->data);
        *prev_reader = (*prev_reader)->next;
    }
}

static int read_packet(xcb_connection_t *c)
{
    xcb_generic_reply_t genrep;
    int length = 32;
    int eventlength = 0; /* length after first 32 bytes for GenericEvents */
    void *buf;
    pending_reply *pend = 0;
    struct event_list *event;

    /* Wait for there to be enough data for us to read a whole packet */
    if(c->in.queue_len < length)
        return 0;

    /* Get the response type, length, and sequence number. */
    memcpy(&genrep, c->in.queue, sizeof(genrep));

    /* Compute 32-bit sequence number of this packet. */
    if((genrep.response_type & 0x7f) != XCB_KEYMAP_NOTIFY)
    {
        uint64_t lastread = c->in.request_read;
        c->in.request_read = (lastread & UINT64_C(0xffffffffffff0000)) | genrep.sequence;
        if(XCB_SEQUENCE_COMPARE(c->in.request_read, <, lastread))
            c->in.request_read += 0x10000;
        if(XCB_SEQUENCE_COMPARE(c->in.request_read, >, c->in.request_expected))
            c->in.request_expected = c->in.request_read;

        if(c->in.request_read != lastread)
        {
            if(c->in.current_reply)
            {
                _xcb_map_put(c->in.replies, lastread, c->in.current_reply);
                c->in.current_reply = 0;
                c->in.current_reply_tail = &c->in.current_reply;
            }
            c->in.request_completed = c->in.request_read - 1;
        }

        while(c->in.pending_replies &&
              c->in.pending_replies->workaround != WORKAROUND_EXTERNAL_SOCKET_OWNER &&
	      XCB_SEQUENCE_COMPARE (c->in.pending_replies->last_request, <=, c->in.request_completed))
        {
            pending_reply *oldpend = c->in.pending_replies;
            c->in.pending_replies = oldpend->next;
            if(!oldpend->next)
                c->in.pending_replies_tail = &c->in.pending_replies;
            free(oldpend);
        }

        if(genrep.response_type == XCB_ERROR)
            c->in.request_completed = c->in.request_read;

        remove_finished_readers(&c->in.readers, c->in.request_completed);
    }

    if(genrep.response_type == XCB_ERROR || genrep.response_type == XCB_REPLY)
    {
        pend = c->in.pending_replies;
        if(pend &&
           !(XCB_SEQUENCE_COMPARE(pend->first_request, <=, c->in.request_read) &&
             (pend->workaround == WORKAROUND_EXTERNAL_SOCKET_OWNER ||
              XCB_SEQUENCE_COMPARE(c->in.request_read, <=, pend->last_request))))
            pend = 0;
    }

    /* For reply packets, check that the entire packet is available. */
    if(genrep.response_type == XCB_REPLY)
    {
        if(pend && pend->workaround == WORKAROUND_GLX_GET_FB_CONFIGS_BUG)
        {
            uint32_t *p = (uint32_t *) c->in.queue;
            genrep.length = p[2] * p[3] * 2;
        }
        length += genrep.length * 4;
    }

    /* XGE events may have sizes > 32 */
    if ((genrep.response_type & 0x7f) == XCB_XGE_EVENT)
        eventlength = genrep.length * 4;

    buf = malloc(length + eventlength +
            (genrep.response_type == XCB_REPLY ? 0 : sizeof(uint32_t)));
    if(!buf)
    {
        _xcb_conn_shutdown(c);
        return 0;
    }

    if(_xcb_in_read_block(c, buf, length) <= 0)
    {
        free(buf);
        return 0;
    }

    /* pull in XGE event data if available, append after event struct */
    if (eventlength)
    {
        if(_xcb_in_read_block(c, &((xcb_generic_event_t*)buf)[1], eventlength) <= 0)
        {
            free(buf);
            return 0;
        }
    }

    if(pend && (pend->flags & XCB_REQUEST_DISCARD_REPLY))
    {
        free(buf);
        return 1;
    }

    if(genrep.response_type != XCB_REPLY)
        ((xcb_generic_event_t *) buf)->full_sequence = c->in.request_read;

    /* reply, or checked error */
    if( genrep.response_type == XCB_REPLY ||
       (genrep.response_type == XCB_ERROR && pend && (pend->flags & XCB_REQUEST_CHECKED)))
    {
        struct reply_list *cur = malloc(sizeof(struct reply_list));
        if(!cur)
        {
            _xcb_conn_shutdown(c);
            free(buf);
            return 0;
        }
        cur->reply = buf;
        cur->next = 0;
        *c->in.current_reply_tail = cur;
        c->in.current_reply_tail = &cur->next;
        if(c->in.readers && c->in.readers->request == c->in.request_read)
            pthread_cond_signal(c->in.readers->data);
        return 1;
    }

    /* event, or unchecked error */
    event = malloc(sizeof(struct event_list));
    if(!event)
    {
        _xcb_conn_shutdown(c);
        free(buf);
        return 0;
    }
    event->event = buf;
    event->next = 0;
    *c->in.events_tail = event;
    c->in.events_tail = &event->next;
    pthread_cond_signal(&c->in.event_cond);
    return 1; /* I have something for you... */
}

static xcb_generic_event_t *get_event(xcb_connection_t *c)
{
    struct event_list *cur = c->in.events;
    xcb_generic_event_t *ret;
    if(!c->in.events)
        return 0;
    ret = cur->event;
    c->in.events = cur->next;
    if(!cur->next)
        c->in.events_tail = &c->in.events;
    free(cur);
    return ret;
}

static void free_reply_list(struct reply_list *head)
{
    while(head)
    {
        struct reply_list *cur = head;
        head = cur->next;
        free(cur->reply);
        free(cur);
    }
}

static int read_block(const int fd, void *buf, const ssize_t len)
{
    int done = 0;
    while(done < len)
    {
        int ret = recv(fd, ((char *) buf) + done, len - done,MSG_WAITALL);
        if(ret > 0)
            done += ret;
#ifndef _WIN32
        if(ret < 0 && errno == EAGAIN)
#else
        if(ret == SOCKET_ERROR && WSAGetLastError() == WSAEWOULDBLOCK)
#endif /* !_Win32 */
        {
#if USE_POLL
            struct pollfd pfd;
            pfd.fd = fd;
            pfd.events = POLLIN;
            pfd.revents = 0;
            do {
                ret = poll(&pfd, 1, -1);
            } while (ret == -1 && errno == EINTR);
#else
            fd_set fds;
            FD_ZERO(&fds);
            FD_SET(fd, &fds);

	    /* Initializing errno here makes sure that for Win32 this loop will execute only once */
	    errno = 0;
	    do {
		ret = select(fd + 1, &fds, 0, 0, 0);
	    } while (ret == -1 && errno == EINTR);
#endif /* USE_POLL */
        }
        if(ret <= 0)
            return ret;
    }
    return len;
}

static int poll_for_reply(xcb_connection_t *c, uint64_t request, void **reply, xcb_generic_error_t **error)
{
    struct reply_list *head;

    /* If an error occurred when issuing the request, fail immediately. */
    if(!request)
        head = 0;
    /* We've read requests past the one we want, so if it has replies we have
     * them all and they're in the replies map. */
    else if(XCB_SEQUENCE_COMPARE(request, <, c->in.request_read))
    {
        head = _xcb_map_remove(c->in.replies, request);
        if(head && head->next)
            _xcb_map_put(c->in.replies, request, head->next);
    }
    /* We're currently processing the responses to the request we want, and we
     * have a reply ready to return. So just return it without blocking. */
    else if(request == c->in.request_read && c->in.current_reply)
    {
        head = c->in.current_reply;
        c->in.current_reply = head->next;
        if(!head->next)
            c->in.current_reply_tail = &c->in.current_reply;
    }
    /* We know this request can't have any more replies, and we've already
     * established it doesn't have a reply now. Don't bother blocking. */
    else if(request == c->in.request_completed)
        head = 0;
    /* We may have more replies on the way for this request: block until we're
     * sure. */
    else
        return 0;

    if(error)
        *error = 0;
    *reply = 0;

    if(head)
    {
        if(((xcb_generic_reply_t *) head->reply)->response_type == XCB_ERROR)
        {
            if(error)
                *error = head->reply;
            else
                free(head->reply);
        }
        else
            *reply = head->reply;

        free(head);
    }

    return 1;
}

static void insert_reader(reader_list **prev_reader, reader_list *reader, uint64_t request, pthread_cond_t *cond)
{
    while(*prev_reader && XCB_SEQUENCE_COMPARE((*prev_reader)->request, <=, request))
        prev_reader = &(*prev_reader)->next;
    reader->request = request;
    reader->data = cond;
    reader->next = *prev_reader;
    *prev_reader = reader;
}

static void remove_reader(reader_list **prev_reader, reader_list *reader)
{
    while(*prev_reader && XCB_SEQUENCE_COMPARE((*prev_reader)->request, <=, reader->request))
        if(*prev_reader == reader)
        {
            *prev_reader = (*prev_reader)->next;
            break;
        }
}

static void *wait_for_reply(xcb_connection_t *c, uint64_t request, xcb_generic_error_t **e)
{
    void *ret = 0;

    /* If this request has not been written yet, write it. */
    if(c->out.return_socket || _xcb_out_flush_to(c, request))
    {
        pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
        reader_list reader;

        insert_reader(&c->in.readers, &reader, request, &cond);

        while(!poll_for_reply(c, request, &ret, e))
            if(!_xcb_conn_wait(c, &cond, 0, 0))
                break;

        remove_reader(&c->in.readers, &reader);
        pthread_cond_destroy(&cond);
    }

    _xcb_in_wake_up_next_reader(c);
    return ret;
}

static uint64_t widen(xcb_connection_t *c, unsigned int request)
{
    uint64_t widened_request = (c->out.request & UINT64_C(0xffffffff00000000)) | request;
    if(widened_request > c->out.request)
        widened_request -= UINT64_C(1) << 32;
    return widened_request;
}

/* Public interface */

void *xcb_wait_for_reply(xcb_connection_t *c, unsigned int request, xcb_generic_error_t **e)
{
    void *ret;
    if(e)
        *e = 0;
    if(c->has_error)
        return 0;

    pthread_mutex_lock(&c->iolock);
    ret = wait_for_reply(c, widen(c, request), e);
    pthread_mutex_unlock(&c->iolock);
    return ret;
}

static void insert_pending_discard(xcb_connection_t *c, pending_reply **prev_next, uint64_t seq)
{
    pending_reply *pend;
    pend = malloc(sizeof(*pend));
    if(!pend)
    {
        _xcb_conn_shutdown(c);
        return;
    }

    pend->first_request = seq;
    pend->last_request = seq;
    pend->workaround = 0;
    pend->flags = XCB_REQUEST_DISCARD_REPLY;
    pend->next = *prev_next;
    *prev_next = pend;

    if(!pend->next)
        c->in.pending_replies_tail = &pend->next;
}

static void discard_reply(xcb_connection_t *c, uint64_t request)
{
    void *reply;
    pending_reply **prev_pend;

    /* Free any replies or errors that we've already read. Stop if
     * xcb_wait_for_reply would block or we've run out of replies. */
    while(poll_for_reply(c, request, &reply, 0) && reply)
        free(reply);

    /* If we've proven there are no more responses coming, we're done. */
    if(XCB_SEQUENCE_COMPARE(request, <=, c->in.request_completed))
        return;

    /* Walk the list of pending requests. Mark the first match for deletion. */
    for(prev_pend = &c->in.pending_replies; *prev_pend; prev_pend = &(*prev_pend)->next)
    {
        if(XCB_SEQUENCE_COMPARE((*prev_pend)->first_request, >, request))
            break;

        if((*prev_pend)->first_request == request)
        {
            /* Pending reply found. Mark for discard: */
            (*prev_pend)->flags |= XCB_REQUEST_DISCARD_REPLY;
            return;
        }
    }

    /* Pending reply not found (likely due to _unchecked request). Create one: */
    insert_pending_discard(c, prev_pend, request);
}

void xcb_discard_reply(xcb_connection_t *c, unsigned int sequence)
{
    if(c->has_error)
        return;

    /* If an error occurred when issuing the request, fail immediately. */
    if(!sequence)
        return;

    pthread_mutex_lock(&c->iolock);
    discard_reply(c, widen(c, sequence));
    pthread_mutex_unlock(&c->iolock);
}

int xcb_poll_for_reply(xcb_connection_t *c, unsigned int request, void **reply, xcb_generic_error_t **error)
{
    int ret;
    if(c->has_error)
    {
        *reply = 0;
        if(error)
            *error = 0;
        return 1; /* would not block */
    }
    assert(reply != 0);
    pthread_mutex_lock(&c->iolock);
    ret = poll_for_reply(c, widen(c, request), reply, error);
    pthread_mutex_unlock(&c->iolock);
    return ret;
}

xcb_generic_event_t *xcb_wait_for_event(xcb_connection_t *c)
{
    xcb_generic_event_t *ret;
    if(c->has_error)
        return 0;
    pthread_mutex_lock(&c->iolock);
    /* get_event returns 0 on empty list. */
    while(!(ret = get_event(c)))
        if(!_xcb_conn_wait(c, &c->in.event_cond, 0, 0))
            break;

    _xcb_in_wake_up_next_reader(c);
    pthread_mutex_unlock(&c->iolock);
    return ret;
}

static xcb_generic_event_t *poll_for_next_event(xcb_connection_t *c, int queued)
{
    xcb_generic_event_t *ret = 0;
    if(!c->has_error)
    {
        pthread_mutex_lock(&c->iolock);
        /* FIXME: follow X meets Z architecture changes. */
        ret = get_event(c);
        if(!ret && !queued && c->in.reading == 0 && _xcb_in_read(c)) /* _xcb_in_read shuts down the connection on error */
            ret = get_event(c);
        pthread_mutex_unlock(&c->iolock);
    }
    return ret;
}

xcb_generic_event_t *xcb_poll_for_event(xcb_connection_t *c)
{
    return poll_for_next_event(c, 0);
}

xcb_generic_event_t *xcb_poll_for_queued_event(xcb_connection_t *c)
{
    return poll_for_next_event(c, 1);
}

xcb_generic_error_t *xcb_request_check(xcb_connection_t *c, xcb_void_cookie_t cookie)
{
    uint64_t request;
    xcb_generic_error_t *ret = 0;
    void *reply;
    if(c->has_error)
        return 0;
    pthread_mutex_lock(&c->iolock);
    request = widen(c, cookie.sequence);
    if(XCB_SEQUENCE_COMPARE(request, >=, c->in.request_expected)
       && XCB_SEQUENCE_COMPARE(request, >, c->in.request_completed))
    {
        _xcb_out_send_sync(c);
        _xcb_out_flush_to(c, c->out.request);
    }
    reply = wait_for_reply(c, request, &ret);
    assert(!reply);
    pthread_mutex_unlock(&c->iolock);
    return ret;
}

/* Private interface */

int _xcb_in_init(_xcb_in *in)
{
    if(pthread_cond_init(&in->event_cond, 0))
        return 0;
    in->reading = 0;

    in->queue_len = 0;

    in->request_read = 0;
    in->request_completed = 0;

    in->replies = _xcb_map_new();
    if(!in->replies)
        return 0;

    in->current_reply_tail = &in->current_reply;
    in->events_tail = &in->events;
    in->pending_replies_tail = &in->pending_replies;

    return 1;
}

void _xcb_in_destroy(_xcb_in *in)
{
    pthread_cond_destroy(&in->event_cond);
    free_reply_list(in->current_reply);
    _xcb_map_delete(in->replies, (void (*)(void *)) free_reply_list);
    while(in->events)
    {
        struct event_list *e = in->events;
        in->events = e->next;
        free(e->event);
        free(e);
    }
    while(in->pending_replies)
    {
        pending_reply *pend = in->pending_replies;
        in->pending_replies = pend->next;
        free(pend);
    }
}

void _xcb_in_wake_up_next_reader(xcb_connection_t *c)
{
    int pthreadret;
    if(c->in.readers)
        pthreadret = pthread_cond_signal(c->in.readers->data);
    else
        pthreadret = pthread_cond_signal(&c->in.event_cond);
    assert(pthreadret == 0);
}

int _xcb_in_expect_reply(xcb_connection_t *c, uint64_t request, enum workarounds workaround, int flags)
{
    pending_reply *pend = malloc(sizeof(pending_reply));
    assert(workaround != WORKAROUND_NONE || flags != 0);
    if(!pend)
    {
        _xcb_conn_shutdown(c);
        return 0;
    }
    pend->first_request = pend->last_request = request;
    pend->workaround = workaround;
    pend->flags = flags;
    pend->next = 0;
    *c->in.pending_replies_tail = pend;
    c->in.pending_replies_tail = &pend->next;
    return 1;
}

void _xcb_in_replies_done(xcb_connection_t *c)
{
    struct pending_reply *pend;
    if (c->in.pending_replies_tail != &c->in.pending_replies)
    {
        pend = container_of(c->in.pending_replies_tail, struct pending_reply, next);
        if(pend->workaround == WORKAROUND_EXTERNAL_SOCKET_OWNER)
        {
            pend->last_request = c->out.request;
            pend->workaround = WORKAROUND_NONE;
        }
    }
}

int _xcb_in_read(xcb_connection_t *c)
{
    int n = recv(c->fd, c->in.queue + c->in.queue_len, sizeof(c->in.queue) - c->in.queue_len,MSG_WAITALL);
    if(n > 0)
        c->in.queue_len += n;
    while(read_packet(c))
        /* empty */;
#ifndef _WIN32
    if((n > 0) || (n < 0 && errno == EAGAIN))
#else
    if((n > 0) || (n < 0 && WSAGetLastError() == WSAEWOULDBLOCK))
#endif /* !_WIN32 */
        return 1;
    _xcb_conn_shutdown(c);
    return 0;
}

int _xcb_in_read_block(xcb_connection_t *c, void *buf, int len)
{
    int done = c->in.queue_len;
    if(len < done)
        done = len;

    memcpy(buf, c->in.queue, done);
    c->in.queue_len -= done;
    memmove(c->in.queue, c->in.queue + done, c->in.queue_len);

    if(len > done)
    {
        int ret = read_block(c->fd, (char *) buf + done, len - done);
        if(ret <= 0)
        {
            _xcb_conn_shutdown(c);
            return ret;
        }
    }

    return len;
}


text:
.. _guide-common-tasks

==================
Working with Tasks
==================

The Gini Android SDK makes heavy use of the concept of tasks. Tasks are convenient when you want to
do execute work in succession, each one waiting for the previous to finish (comparable to
Promises in JavaScript). This is a common pattern when working with Gini's remote API. The Gini
Android SDK uses `facebook's task implementation, which is called bolts
<https://github.com/BoltsFramework/Bolts-Android>`_. Before you continue reading this guide, we
strongly encourage you to read the `short guide for the Bolts framework
<https://github.com/BoltsFramework/Bolts-Android/blob/master/Readme.md#tasks>`_.

Upload a document
=================

As the key aspect of the Gini API is to provide information extraction for analyzing documents, the
API is mainly built around the concept of documents. A document can be any written representation of
information such as invoices, reminders, contracts and so on.

The Gini Android SDK supports creating documents from images, PDFs or UTF-8 encoded text. Images are
usually a picture of a paper document which was taken with the device's camera.

The following example shows how to create a new document from a byte array containing a JPEG image.

.. code-block:: java

    import net.gini.android.Gini;
    import net.gini.android.DocumentTaskManager;
    import net.gini.android.models.Document;

    ...

    // Assuming that `gini` is an instance of the `Gini` facade class and `imageBytes`
    // is an instance of a byte array containing a JPEG image,
    // e.g. from a picture taken by the camera

    DocumentTaskManager documentTaskManager = gini.getDocumentTaskManager();
    documentTaskManager.createPartialDocument(imageBytes, "image/jpeg", "myFirstDocument.jpg", null)
        .onSuccess(new Continuation<Document, Void>() {
            @Override
            public Void then(Task<Document> task) throws Exception {
                Document document = task.getResult();
                return null;
            }
        });

In version 2.0.0 we introduced *partial documents* to allow scanning documents with multiple pages.
Each page of a document needs to uploaded as a partial document. In addition documents consisting of
one page also should be uploaded as a partial document.

.. warning::

    If you are using the Gini Accounting API, then partial documents are not supported. Use the
    `DocumentTaskManager#createDocument()` methods instead.

.. note::

    PDFs and UTF-8 encoded text should also be uploaded as partial documents. Even though PDFs might
    contain multiple pages and text is "pageless", creating partial documents for these keeps your
    interaction with Gini consistent for all the supported document types.

Extractions are not available for partial documents. Creating a partial document is analogous to an
upload. For retrieving extractions see :ref:`getting-extractions`.

.. note::

    The filename (``myFirstDocument.jpg`` in the example) is not required, it could be ``null``, but
    setting a filename is a good praxis for human readable document identification.

Setting the document type hint
------------------------------

To easily set the document type hint we introduced the ``DocumentType`` enum. It is safer and easier
to use than a ``String``. For more details about the document type hints see the `Document Type
Hints in the Gini API documentation
<http://developer.gini.net/gini-api/html/documents.html#document-type-hints>`_.

.. _getting-extractions:

Getting extractions
===================

After you have successfully created the partial documents, you most likely want to get the
extractions for the document. In version 2.0.0 we introduced *composite documents* which consist of
previously created *partial documents*. You can consider creating partial documents analogous to
uploading pages of a document and creating a composite document analogous to processing those page
as a single document.

.. warning::

    If you are using the Gini Accounting API, then composite documents are not supported. You need to
    use `DocumentTaskManager#pollDocument()` and then `DocumentTaskManager#getExtractions()` without
    creating a composite document.

Before retrieving extractions you need to create a composite document from your partial documents.
The ``createCompositeDocument()`` method accepts either a ``List`` of partial ``Documents`` or a
``LinkedHashMap``. The ``LinkedHashMap`` contains partial ``Documents`` as keys and the user applied
rotation as values. In both cases the order is important and the partial documents should be in the
same order as the pages of the scanned document.

Gini needs to process the composite document first before you can fetch the extractions. Effectively
this means that you won't get any extractions before the composite document is fully processed. The
processing time may vary, usually it is in the range of a couple of seconds, but blurred or slightly
rotated images are known to drasticly increase the processing time.

The ``DocumentTaskManager`` provides the ``pollDocument`` and ``getAllExtractions`` methods which can be
used to fetch the extractions after the processing of the document is completed. The following
example shows how to achieve this in detail.

.. code-block:: java

        import net.gini.android.Gini;
        import net.gini.android.DocumentTaskManager;
        import net.gini.android.models.Document;
        import net.gini.android.models.SpecificExtraction;

        ...

        // Assuming that `gini` is an instance of the `Gini` facade class and `partialDocuments` is
        // a list of `Documents` which were returned by `createPartialDocument(...)` calls

        final DocumentTaskManager documentTaskManager = gini.getDocumentTaskManager();
        documentTaskManager.createCompositeDocument(partialDocuments, null)
            .onSuccessTask(
                new Continuation<Document, Task<Document>>() {
                    @Override
                    public Task<Document> then(
                            final Task<Document> task)
                            throws Exception {
                        final Document document = task.getResult();
                        return documentTaskManager.pollDocument(document);
                    }
            })
            .onSuccessTask(new Continuation<Document, Task<Map<String, SpecificExtraction>>>() {
                @Override
                public Object then(Task<Document> task) throws Exception {
                    final Document document = task.getResult();
                    return documentTaskManager.getAllExtractions(document);
                }
            })
            .onSuccess(new Continuation<ExtractionsContainer>, Void>() {
                @Override
                public Void then(Task<ExtractionsContainer> task) {
                    final ExtractionsContainer extractions = task.getResult();
                    final SpecificExtraction amountToPay =
                            extractions.getSpecificExtractions().get("amountToPay");
                    final CompoundExtraction lineItems =
                            extractions.getCompoundExtractions().get("lineItems");
                    // You may use the extractions to fulfill your use-case
                    return null;
                }
            });

Sending feedback
================

Depending on your use case your app probably presents the extractions to the user and offers the
opportunity to correct them. We do our best to prevent errors. You can help improve our service if
your app sends feedback for the extractions Gini delivered. Your app should send feedback only for
the extractions the *user has seen and accepted*. Feedback should be sent for corrected extractions
**and** for *correct extractions*. The code example below shows how to correct extractions and send
feedback.

.. code-block:: java

        final Task<Map<String, SpecificExtraction>> retrievedExtractions // provided
        final Document document // provided

        final Map<String, SpecificExtraction> extractions = retrieveExtractions.getResult();
        // amounTo pay was wrong, we'll correct it
        SpecificExtraction amountToPay = extractions.get("amountToPay");
        amountToPay.setValue("31:00");

        // we should send only feedback for extractions we have seen and accepted
        // all extractions we've seen were correct except amountToPay
        Map<String, SpecificExtraction> feedback = new HashMap<String, SpecificExtraction>();
        feedback.put("iban", extractions.get("iban"));
        feedback.put("amountToPay", amountToPay);
        feedback.put("bic", extractions.get("bic"));
        feedback.put("senderName", extractions.get("senderName"));

        final Task<Document> sendFeedback = documentTaskManager.sendFeedbackForExtractions(document, feedback);
        sendFeedback.waitForCompletion();

Report an extraction error to Gini
==================================

If the processing result for a document was not satisfactory for the user, your app can enable your
user the opportunity to report an error directly to Gini. Gini will return an error identifier which
can be used to refer to it towards the Gini support. The user must agree that Gini can use this
document for debugging and error analysis. The code example below shows how to send the error report
to Gini.

.. code-block:: java

        final Document document // provided
        documentTaskManager.reportDocument(document, "short summary", "detailed description");

Handling SDK errors
===================

Currently, the Gini Android SDK doesn't have intelligent error-handling mechanisms. All errors that
occure during executing a task are handed over transparently. You can react on those errors in the
``onError(...)`` method of the task. We may add better error-handling mechanisms in the future. At
the moment we recommend checking the network status when a task failed and retrying the task.


text:
package water.fvec;

import water.*;

/**
 * The empty-compression function, if all elements fit directly on UNSIGNED bytes.
 * Cannot store 0xFF, the value is a marker for N/A.
 */
public class C1Chunk extends Chunk {
  static protected final int _OFF = 0;
  static protected final long _NA = 0xFF;
  C1Chunk(byte[] bs) { _mem=bs; _start = -1; set_len(_mem.length); }
  @Override protected final long at8_impl( int i ) {
    long res = 0xFF&_mem[i+_OFF];
    if( res == _NA ) throw new IllegalArgumentException("at8_abs but value is missing");
    return res;
  }
  @Override protected final double atd_impl( int i ) {
    long res = 0xFF&_mem[i+_OFF];
    return (res == _NA)?Double.NaN:res;
  }
  @Override protected final boolean isNA_impl( int i ) { return (0xFF&_mem[i+_OFF]) == _NA; }
  @Override boolean set_impl(int i, long l) {
    if( !(0 <= l && l < 255) ) return false;
    _mem[i+_OFF] = (byte)l;
    return true;
  }
  @Override boolean set_impl(int i, double d) { return false; }
  @Override boolean set_impl(int i, float f ) { return false; }
  @Override boolean setNA_impl(int idx) { _mem[idx+_OFF] = (byte)_NA; return true; }
  @Override public NewChunk inflate_impl(NewChunk nc) {
    nc.set_sparseLen(0);
    nc.set_len(0);
    final int len = _len;
    for( int i=0; i<len; i++ ) {
      int res = 0xFF&_mem[i+_OFF];
      if( res == _NA ) nc.addNA();
      else             nc.addNum(res,0);
    }
    return nc;
  }
  @Override final public AutoBuffer write_impl(AutoBuffer bb) { return bb.putA1(_mem,_mem.length); }
  @Override final public C1Chunk read_impl(AutoBuffer bb) {
    _mem = bb.bufClose();
    _start = -1;  _cidx = -1;
    set_len(_mem.length);
    return this;
  }
  @Override
  public boolean hasFloat() {return false;}
}


text:
package simulator

import (
	"context"
	"errors"
	"fmt"
	"testing"

	"github.com/vmware/govmomi/performance"
	"github.com/vmware/govmomi/simulator/esx"
	"github.com/vmware/govmomi/simulator/vpx"
	"github.com/vmware/govmomi/vim25/mo"
	"github.com/vmware/govmomi/vim25/types"
)

func testMetricsConsistency(counterInfo []types.PerfCounterInfo, ids [][]types.PerfMetricId) error {

	// Build a lookup table for speed and convenience
	lookup := make(map[int32]bool, len(counterInfo))
	for _, pc := range counterInfo {
		lookup[pc.Key] = true
	}

	// Check metric ids against map
	for _, list := range ids {
		for _, id := range list {
			if _, ok := lookup[id.CounterId]; !ok {
				return fmt.Errorf("Counter with ID %d not found in PerfCounter", id.CounterId)
			}
		}
	}
	return nil
}

func TestMetricsConsistency(t *testing.T) {
	esxIds := [][]types.PerfMetricId{esx.VmMetrics, esx.HostMetrics, esx.ResourcePoolMetrics}
	vpxIds := [][]types.PerfMetricId{vpx.VmMetrics, vpx.HostMetrics, vpx.ClusterMetrics,
		vpx.DatastoreMetrics, vpx.ResourcePoolMetrics}
	if err := testMetricsConsistency(esx.PerfCounter, esxIds); err != nil {
		t.Fatal(err)
	}
	if err := testMetricsConsistency(vpx.PerfCounter, vpxIds); err != nil {
		t.Fatal(err)
	}
}

func checkDuplicates(ids []types.PerfMetricId) error {
	m := make(map[string]bool, len(ids))
	for _, id := range ids {
		k := fmt.Sprintf("%d|%s", id.CounterId, id.Instance)
		if _, ok := m[k]; ok {
			return fmt.Errorf("Duplicate metric key: %s", k)
		}
		m[k] = true
	}
	return nil
}

func TestMetricsDuplicates(t *testing.T) {
	if err := checkDuplicates(esx.VmMetrics); err != nil {
		t.Fatal(err)
	}
	if err := checkDuplicates(esx.HostMetrics); err != nil {
		t.Fatal(err)
	}
	if err := checkDuplicates(vpx.VmMetrics); err != nil {
		t.Fatal(err)
	}
	if err := checkDuplicates(vpx.HostMetrics); err != nil {
		t.Fatal(err)
	}
	if err := checkDuplicates(vpx.ClusterMetrics); err != nil {
		t.Fatal(err)
	}
	if err := checkDuplicates(vpx.DatastoreMetrics); err != nil {
		t.Fatal(err)
	}
}

func TestQueryProviderSummary(t *testing.T) {
	ctx := context.Background()

	m := VPX()

	err := m.Create()
	if err != nil {
		t.Fatal(err)
	}

	defer m.Remove()

	c := m.Service.client

	p := performance.NewManager(c)

	vm := Map.Any("VirtualMachine").(*VirtualMachine)
	if info, err := p.ProviderSummary(ctx, vm.Reference()); err != nil {
		t.Fatal(err)
	} else {
		if info.RefreshRate != 20 {
			t.Fatalf("VM wefresh rate is %d, should be 20", info.RefreshRate)
		}
	}

	host := Map.Any("HostSystem").(*HostSystem)
	if info, err := p.ProviderSummary(ctx, host.Reference()); err != nil {
		t.Fatal(err)
	} else {
		if info.RefreshRate != 20 {
			t.Fatalf("Host refresh rate is %d, should be 20", info.RefreshRate)
		}
	}

	pool := Map.Any("ResourcePool").(*ResourcePool)
	if info, err := p.ProviderSummary(ctx, pool.Reference()); err != nil {
		t.Fatal(err)
	} else {
		if info.RefreshRate != 20 {
			t.Fatalf("ResourcePool refresh rate is %d, should be 20", info.RefreshRate)
		}
	}

	cluster := Map.Any("ClusterComputeResource").(*ClusterComputeResource)
	if info, err := p.ProviderSummary(ctx, cluster.Reference()); err != nil {
		t.Fatal(err)
	} else {
		if info.RefreshRate != -1 {
			t.Fatalf("Cluster refresh rate is %d, should be -1", info.RefreshRate)
		}
	}

	datastore := Map.Any("Datastore").(*Datastore)
	if info, err := p.ProviderSummary(ctx, datastore.Reference()); err != nil {
		t.Fatal(err)
	} else {
		if info.RefreshRate != -1 {
			t.Fatalf("Datastore refresh rate is %d, should be -1", info.RefreshRate)
		}
	}

	nonExistent := types.ManagedObjectReference{
		Type:  "Not a valid type",
		Value: "This object doesn't exist",
	}
	if _, err := p.ProviderSummary(ctx, nonExistent); err == nil {
		t.Fatal("This should have failed (nonexistent object)")
	}
}

func TestQueryAvailablePerfMetric(t *testing.T) {
	ctx := context.Background()

	m := VPX()

	err := m.Create()
	if err != nil {
		t.Fatal(err)
	}

	defer m.Remove()

	c := m.Service.client
	p := performance.NewManager(c)

	vm := Map.Any("VirtualMachine").(*VirtualMachine)
	if info, err := p.AvailableMetric(ctx, vm.Reference(), 20); err != nil {
		t.Fatal(err)
	} else {
		if len(info) == 0 {
			t.Fatal("Expected non-empty list of vm")
		}
	}

	host := Map.Any("HostSystem").(*HostSystem)
	if info, err := p.AvailableMetric(ctx, host.Reference(), 20); err != nil {
		t.Fatal(err)
	} else {
		if len(info) == 0 {
			t.Fatal("Expected non-empty list of host")
		}
		var ids []int32
		for i := range info {
			ids = append(ids, info[i].CounterId)
		}
		perf, err := p.QueryCounter(ctx, ids)
		if err != nil {
			t.Fatal(err)
		}
		if len(perf) != len(ids) {
			t.Errorf("%d counters", len(perf))
		}
	}

	pool := Map.Any("ResourcePool").(*ResourcePool)
	if info, err := p.AvailableMetric(ctx, pool.Reference(), 20); err != nil {
		t.Fatal(err)
	} else {
		if len(info) == 0 {
			t.Fatal("Expected non-empty list of resource pool")
		}
	}

	cluster := Map.Any("ClusterComputeResource").(*ClusterComputeResource)
	if info, err := p.AvailableMetric(ctx, cluster.Reference(), 300); err != nil {
		t.Fatal(err)
	} else {
		if len(info) == 0 {
			t.Fatal("Expected non-empty list of clusters")
		}
	}

	if info, err := p.AvailableMetric(ctx, cluster.Reference(), 20); err != nil {
		t.Fatal(err)
	} else {
		if len(info) != 0 {
			t.Fatal("Expected empty list of clusters")
		}
	}

	ds := Map.Any("Datastore").(*Datastore)
	if info, err := p.AvailableMetric(ctx, ds.Reference(), 300); err != nil {
		t.Fatal(err)
	} else {
		if len(info) == 0 {
			t.Fatal("Expected non-empty list of datastores")
		}
	}

	if info, err := p.AvailableMetric(ctx, ds.Reference(), 20); err != nil {
		t.Fatal(err)
	} else {
		if len(info) != 0 {
			t.Fatal("Expected empty list of datastores")
		}
	}

	dc := Map.Any("Datacenter").(*Datacenter)
	if info, err := p.AvailableMetric(ctx, dc.Reference(), 300); err != nil {
		t.Fatal(err)
	} else {
		if len(info) == 0 {
			t.Fatal("Expected non-empty list of datacenters")
		}
	}

	if info, err := p.AvailableMetric(ctx, dc.Reference(), 20); err != nil {
		t.Fatal(err)
	} else {
		if len(info) != 0 {
			t.Fatal("Expected empty list of datacenters")
		}
	}

}

func testPerfQuery(ctx context.Context, m *Model, e mo.Entity, interval int32) error {
	c := m.Service.client

	p := performance.NewManager(c)

	// Single metric, single VM
	//
	qs := []types.PerfQuerySpec{
		{
			MaxSample:  4,
			IntervalId: interval,
			MetricId:   []types.PerfMetricId{{CounterId: 1, Instance: ""}},
			Entity:     e.Reference(),
		},
	}
	result, err := p.Query(ctx, qs)
	if err != nil {
		return err
	}
	if len(result) == 0 {
		return errors.New("Empty result set")
	}
	ms, err := p.ToMetricSeries(ctx, result)
	if err != nil {
		return err
	}
	if len(ms) == 0 {
		return errors.New("Empty metric series")
	}
	return nil
}

func TestQueryPerf(t *testing.T) {
	ctx := context.Background()

	m := VPX()

	err := m.Create()
	if err != nil {
		t.Fatal(err)
	}

	defer m.Remove()

	if err := testPerfQuery(ctx, m, Map.Any("VirtualMachine"), 20); err != nil {
		t.Fatal(err)
	}
	if err := testPerfQuery(ctx, m, Map.Any("HostSystem"), 20); err != nil {
		t.Fatal(err)
	}
	if err := testPerfQuery(ctx, m, Map.Any("ClusterComputeResource"), 300); err != nil {
		t.Fatal(err)
	}
	if err := testPerfQuery(ctx, m, Map.Any("Datastore"), 300); err != nil {
		t.Fatal(err)
	}
	if err := testPerfQuery(ctx, m, Map.Any("Datacenter"), 300); err != nil {
		t.Fatal(err)
	}
	if err := testPerfQuery(ctx, m, Map.Any("ResourcePool"), 300); err != nil {
		t.Fatal(err)
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<ModelDesign xmlns:cas="http://cas.eu/UA/CommServer/UnitTests/DataTypeTest" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:uax="http://opcfoundation.org/UA/2008/02/Types.xsd" xmlns:ua="http://opcfoundation.org/UA/" TargetNamespace="http://cas.eu/UA/CommServer/UnitTests/DataTypeTest" xmlns="http://opcfoundation.org/UA/ModelDesign.xsd">
  <Namespaces>
    <Namespace Name="cas" Prefix="DataTypeTest" XmlPrefix="cas">http://cas.eu/UA/CommServer/UnitTests/DataTypeTest</Namespace>
    <Namespace Name="ua" XmlPrefix="ua">http://opcfoundation.org/UA/</Namespace>
  </Namespaces>
  <DataType SymbolicName="cas:AbstractEnumerationDataType" BaseType="ua:Enumeration" IsAbstract="true">
    <Fields>
      <Field Name="Field1" Identifier="0" />
      <Field Name="Field2" Identifier="1" />
    </Fields>
  </DataType>
  <DataType SymbolicName="cas:EnumerationDataType" BaseType="cas:AbstractEnumerationDataType">
    <Description>Enumeration DataType derived from abstract type</Description>
    <Fields>
      <Field Name="Field3" Identifier="1" />
    </Fields>
  </DataType>
  <DataType SymbolicName="cas:AbstractStructure" BaseType="ua:Structure" IsAbstract="true">
    <Description>Abstract structure</Description>
    <Fields>
      <Field Name="Number" DataType="ua:Number" />
    </Fields>
  </DataType>
  <DataType SymbolicName="cas:DerivedStructure" BaseType="cas:AbstractStructure">
    <Fields>
      <Field Name="Number" DataType="ua:Int32">
        <Description>Derived from Number</Description>
      </Field>
    </Fields>
  </DataType>
</ModelDesign>


text:
"""
defines classes, that describe C++ types
"""

from . import compilers
from . import algorithms_cache

class type_t(object):

    """base class for all types"""

    def __init__(self):
        object.__init__(self)
        self.cache = algorithms_cache.type_algs_cache_t()
        self._byte_size = 0
        self._byte_align = 0
        self.compiler = None

    def __str__(self):
        res = self.decl_string
        if res[:2] == "::":
            res = res[2:]
        return res

    def __eq__(self, other):
        if not isinstance(other, type_t):
            return False
        return self.decl_string == other.decl_string

    def __hash__(self):
        return hash(self.decl_string)

    def __ne__(self, other):
        return not self.__eq__(other)

    def __lt__(self, other):
        if not isinstance(other, self.__class__):
            return self.__class__.__name__ < other.__class__.__name__
        return self.decl_string < other.decl_string

    def build_decl_string(self, with_defaults=True):
        raise NotImplementedError()

    @property
    def decl_string(self):
        return self.build_decl_string()

    @property
    def partial_decl_string(self):
        return self.build_decl_string(False)

    def _clone_impl(self):
        raise NotImplementedError()

    def clone(self):
        "returns new instance of the type"
        answer = self._clone_impl()
        return answer

    @property
    def byte_size(self):
        "Size of this type in bytes @type: int"
        return self._byte_size

    @byte_size.setter
    def byte_size(self, new_byte_size):
        self._byte_size = new_byte_size

    @property
    def byte_align(self):
        "Alignment of this type in bytes @type: int"
        return self._byte_align

    @byte_align.setter
    def byte_align(self, new_byte_align):
        self._byte_align = new_byte_align

# There are cases when GCC-XML reports something like this
# <Unimplemented id="_9482" tree_code="188" \
# tree_code_name="template_type_parm" node="0xcc4d5b0"/>
# In this case I will use this as type

class dummy_type_t(type_t):

    """provides :class:`type_t` interface for a string, that defines C++ type.

    This class could be very useful in the code generator.
    """

    def __init__(self, decl_string):
        type_t.__init__(self)
        self._decl_string = decl_string

    def build_decl_string(self, with_defaults=True):
        return self._decl_string

    def _clone_impl(self):
        return dummy_type_t(self._decl_string)

class unknown_t(type_t):

    "type, that represents all C++ types, that could not be parsed  by GCC-XML"

    def __init__(self):
        type_t.__init__(self)

    def build_decl_string(self, with_defaults=True):
        return '?unknown?'

    def _clone_impl(self):
        return self

class ellipsis_t(type_t):

    """type, that represents "..." in function definition"""

    def __init__(self):
        type_t.__init__(self)

    def build_decl_string(self, with_defaults=True):
        return '...'

    def _clone_impl(self):
        return self

##########################################################################
# Fundamental types:

class fundamental_t(type_t):

    """base class for all fundamental, build-in types"""

    def __init__(self, name):
        type_t.__init__(self)
        self._name = name

    def build_decl_string(self, with_defaults=True):
        return self._name

    def _clone_impl(self):
        return self

class java_fundamental_t(fundamental_t):

    """base class for all JNI defined fundamental types"""

    def __init__(self, name):
        fundamental_t.__init__(self, name)

class void_t(fundamental_t):

    """represents void type"""
    CPPNAME = 'void'

    def __init__(self):
        fundamental_t.__init__(self, void_t.CPPNAME)

class char_t(fundamental_t):

    """represents char type"""
    CPPNAME = 'char'

    def __init__(self):
        fundamental_t.__init__(self, char_t.CPPNAME)

class signed_char_t(fundamental_t):

    """represents signed char type"""
    CPPNAME = 'signed char'

    def __init__(self):
        fundamental_t.__init__(self, signed_char_t.CPPNAME)

class unsigned_char_t(fundamental_t):

    """represents unsigned char type"""
    CPPNAME = 'unsigned char'

    def __init__(self):
        fundamental_t.__init__(self, unsigned_char_t.CPPNAME)

class wchar_t(fundamental_t):

    """represents wchar_t type"""
    CPPNAME = 'wchar_t'

    def __init__(self):
        fundamental_t.__init__(self, wchar_t.CPPNAME)

class short_int_t(fundamental_t):

    """represents short int type"""
    CPPNAME = 'short int'

    def __init__(self):
        fundamental_t.__init__(self, short_int_t.CPPNAME)

class short_unsigned_int_t(fundamental_t):

    """represents short unsigned int type"""
    CPPNAME = 'short unsigned int'

    def __init__(self):
        fundamental_t.__init__(self, short_unsigned_int_t.CPPNAME)

class bool_t(fundamental_t):

    """represents bool type"""
    CPPNAME = 'bool'

    def __init__(self):
        fundamental_t.__init__(self, bool_t.CPPNAME)

class int_t(fundamental_t):

    """represents int type"""
    CPPNAME = 'int'

    def __init__(self):
        fundamental_t.__init__(self, int_t.CPPNAME)

class unsigned_int_t(fundamental_t):

    """represents unsigned int type"""
    CPPNAME = 'unsigned int'

    def __init__(self):
        fundamental_t.__init__(self, unsigned_int_t.CPPNAME)

class long_int_t(fundamental_t):

    """represents long int type"""
    CPPNAME = 'long int'

    def __init__(self):
        fundamental_t.__init__(self, long_int_t.CPPNAME)

class long_unsigned_int_t(fundamental_t):

    """represents long unsigned int type"""
    CPPNAME = 'long unsigned int'

    def __init__(self):
        fundamental_t.__init__(self, long_unsigned_int_t.CPPNAME)

class long_long_int_t(fundamental_t):

    """represents long long int type"""
    CPPNAME = 'long long int'

    def __init__(self):
        fundamental_t.__init__(self, long_long_int_t.CPPNAME)

class long_long_unsigned_int_t(fundamental_t):

    """represents long long unsigned int type"""
    CPPNAME = 'long long unsigned int'

    def __init__(self):
        fundamental_t.__init__(self, long_long_unsigned_int_t.CPPNAME)

class float_t(fundamental_t):

    """represents float type"""
    CPPNAME = 'float'

    def __init__(self):
        fundamental_t.__init__(self, float_t.CPPNAME)

class double_t(fundamental_t):

    """represents double type"""
    CPPNAME = 'double'

    def __init__(self):
        fundamental_t.__init__(self, double_t.CPPNAME)

class long_double_t(fundamental_t):

    """represents long double type"""
    CPPNAME = 'long double'

    def __init__(self):
        fundamental_t.__init__(self, long_double_t.CPPNAME)

class complex_double_t(fundamental_t):

    """represents complex double type"""
    CPPNAME = 'complex double'

    def __init__(self):
        fundamental_t.__init__(self, complex_double_t.CPPNAME)

class complex_long_double_t(fundamental_t):

    """represents complex long double type"""
    CPPNAME = 'complex long double'

    def __init__(self):
        fundamental_t.__init__(self, complex_long_double_t.CPPNAME)

class complex_float_t(fundamental_t):

    """represents complex float type"""
    CPPNAME = 'complex float'

    def __init__(self):
        fundamental_t.__init__(self, complex_float_t.CPPNAME)

class jbyte_t(java_fundamental_t):

    """represents jbyte type"""
    JNAME = 'jbyte'

    def __init__(self):
        java_fundamental_t.__init__(self, jbyte_t.JNAME)

class jshort_t(java_fundamental_t):

    """represents jshort type"""
    JNAME = 'jshort'

    def __init__(self):
        java_fundamental_t.__init__(self, jshort_t.JNAME)

class jint_t(java_fundamental_t):

    """represents jint type"""
    JNAME = 'jint'

    def __init__(self):
        java_fundamental_t.__init__(self, jint_t.JNAME)

class jlong_t(java_fundamental_t):

    """represents jlong type"""
    JNAME = 'jlong'

    def __init__(self):
        java_fundamental_t.__init__(self, jlong_t.JNAME)

class jfloat_t(java_fundamental_t):

    """represents jfloat type"""
    JNAME = 'jfloat'

    def __init__(self):
        java_fundamental_t.__init__(self, jfloat_t.JNAME)

class jdouble_t(java_fundamental_t):

    """represents jdouble type"""
    JNAME = 'jdouble'

    def __init__(self):
        java_fundamental_t.__init__(self, jdouble_t.JNAME)

class jchar_t(java_fundamental_t):

    """represents jchar type"""
    JNAME = 'jchar'

    def __init__(self):
        java_fundamental_t.__init__(self, jchar_t.JNAME)

class jboolean_t(java_fundamental_t):

    """represents jboolean type"""
    JNAME = 'jboolean'

    def __init__(self):
        java_fundamental_t.__init__(self, jboolean_t.JNAME)

class int128_t(fundamental_t):

    """represents __int128_t type"""
    CPPNAME = '__int128_t'

    def __init__(self):
        fundamental_t.__init__(self, int128_t.CPPNAME)

class uint128_t(fundamental_t):

    """represents __uint128_t type"""
    CPPNAME = '__uint128_t'

    def __init__(self):
        fundamental_t.__init__(self, uint128_t.CPPNAME)

FUNDAMENTAL_TYPES = {
    # adding java types
    void_t.CPPNAME: void_t(),
    char_t.CPPNAME: char_t(),
    signed_char_t.CPPNAME: signed_char_t(),
    unsigned_char_t.CPPNAME: unsigned_char_t(),
    wchar_t.CPPNAME: wchar_t(),
    short_int_t.CPPNAME: short_int_t(),
    'signed ' + short_int_t.CPPNAME: short_int_t(),
    short_unsigned_int_t.CPPNAME: short_unsigned_int_t(),
    bool_t.CPPNAME: bool_t(),
    int_t.CPPNAME: int_t(),
    'signed ' + int_t.CPPNAME: int_t(),
    unsigned_int_t.CPPNAME: unsigned_int_t(),
    long_int_t.CPPNAME: long_int_t(),
    long_unsigned_int_t.CPPNAME: long_unsigned_int_t(),
    long_long_int_t.CPPNAME: long_long_int_t(),
    long_long_unsigned_int_t.CPPNAME: long_long_unsigned_int_t(),
    int128_t.CPPNAME: int128_t(),
    uint128_t.CPPNAME: uint128_t(),
    float_t.CPPNAME: float_t(),
    double_t.CPPNAME: double_t(),
    long_double_t.CPPNAME: long_double_t(),
    complex_long_double_t.CPPNAME: complex_long_double_t(),
    complex_double_t.CPPNAME: complex_double_t(),
    complex_float_t.CPPNAME: complex_float_t(),
    jbyte_t.JNAME: jbyte_t(),
    jshort_t.JNAME: jshort_t(),
    jint_t.JNAME: jint_t(),
    jlong_t.JNAME: jlong_t(),
    jfloat_t.JNAME: jfloat_t(),
    jdouble_t.JNAME: jdouble_t(),
    jchar_t.JNAME: jchar_t(),
    jboolean_t.JNAME: jboolean_t(),
    '__java_byte': jbyte_t(),
    '__java_short': jshort_t(),
    '__java_int': jint_t(),
    '__java_long': jlong_t(),
    '__java_float': jfloat_t(),
    '__java_double': jdouble_t(),
    '__java_char': jchar_t(),
    '__java_boolean': jboolean_t()
}
"""
defines a mapping between fundamental type name and its synonym to the instance
of class that describes the type
"""

##########################################################################
# Compaund types:

class compound_t(type_t):

    """class that allows to represent compound types like `const int*`"""

    def __init__(self, base):
        type_t.__init__(self)
        self._base = base

    @property
    def base(self):
        "reference to internal/base class"
        return self._base

    @base.setter
    def base(self, new_base):
        self._base = new_base

class volatile_t(compound_t):

    """represents `volatile whatever` type"""

    def __init__(self, base):
        compound_t.__init__(self, base)

    def build_decl_string(self, with_defaults=True):
        return self.base.build_decl_string(with_defaults) + ' volatile'

    def _clone_impl(self):
        return volatile_t(self.base.clone())

class restrict_t(compound_t):

    """represents `restrict whatever` type"""

    # The restrict keyword can be considered an extension to the strict
    # aliasing rule. It allows the programmer to declare that pointers which
    # share the same type (or were otherwise validly created) do not alias
    # eachother. By using restrict the programmer can declare that any loads
    # and stores through the qualified pointer (or through another pointer
    # copied either directly or indirectly from the restricted pointer) are
    # the only loads and stores to the same address during the lifetime of
    # the pointer. In other words, the pointer is not aliased by any pointers
    # other than its own copies.

    def __init__(self, base):
        compound_t.__init__(self, base)

    def build_decl_string(self, with_defaults=True):
        return '__restrict__ ' + self.base.build_decl_string(with_defaults)

    def _clone_impl(self):
        return restrict_t(self.base.clone())

class const_t(compound_t):

    """represents `whatever const` type"""

    def __init__(self, base):
        compound_t.__init__(self, base)

    def build_decl_string(self, with_defaults=True):
        return self.base.build_decl_string(with_defaults) + ' const'

    def _clone_impl(self):
        return const_t(self.base.clone())

class pointer_t(compound_t):

    """represents `whatever*` type"""

    def __init__(self, base):
        compound_t.__init__(self, base)

    def build_decl_string(self, with_defaults=True):
        return self.base.build_decl_string(with_defaults) + ' *'

    def _clone_impl(self):
        return pointer_t(self.base.clone())

class reference_t(compound_t):

    """represents `whatever&` type"""

    def __init__(self, base):
        compound_t.__init__(self, base)

    def build_decl_string(self, with_defaults=True):
        return self.base.build_decl_string(with_defaults) + ' &'

    def _clone_impl(self):
        return reference_t(self.base.clone())

class array_t(compound_t):

    """represents C++ array type"""
    SIZE_UNKNOWN = -1

    def __init__(self, base, size):
        compound_t.__init__(self, base)
        self._size = size

    @property
    def size(self):
        "returns array size"
        return self._size

    @size.setter
    def size(self, size):
        """sometimes there is a need to update the size of the array"""
        self.cache.reset()
        self._size = size

    def build_decl_string(self, with_defaults=True):
        # return self.base.build_decl_string(with_defaults) + '[%d]' %
        # self.size
        return self.__bds_for_multi_dim_arrays(None, with_defaults)

    def __bds_for_multi_dim_arrays(self, parent_dims=None, with_defaults=True):
        if parent_dims:
            parent_dims.append(self.size)
        else:
            parent_dims = [self.size]

        if isinstance(self.base, array_t):
            return self.base.__bds_for_multi_dim_arrays(
                parent_dims,
                with_defaults)
        else:
            tmp = []
            for s in parent_dims:
                tmp.append('[%d]' % s)
            return self.base.build_decl_string(with_defaults) + ''.join(tmp)

    def _clone_impl(self):
        return array_t(self.base.clone(), self.size)

class calldef_type_t(object):

    """base class for all types that describes "callable" declaration"""

    def __init__(self, return_type=None, arguments_types=None):
        object.__init__(self)
        self._return_type = return_type
        if arguments_types is None:
            arguments_types = []
        self._arguments_types = arguments_types

    @property
    def return_type(self):
        """reference to :class:`return type <type_t>`"""
        return self._return_type

    @return_type.setter
    def return_type(self, new_return_type):
        self._return_type = new_return_type

    @property
    def arguments_types(self):
        """list of argument :class:`types <type_t>`"""
        return self._arguments_types

    @arguments_types.setter
    def arguments_types(self, new_arguments_types):
        self._arguments_types = new_arguments_types

    @property
    def has_ellipsis(self):
        return self.arguments_types and isinstance(
            self.arguments_types[-1], ellipsis_t)

class free_function_type_t(type_t, calldef_type_t):

    """describes free function type"""
    NAME_TEMPLATE = '%(return_type)s (*)( %(arguments)s )'
    TYPEDEF_NAME_TEMPLATE = (
        '%(return_type)s ( *%(typedef_name)s )( %(arguments)s )')

    def __init__(self, return_type=None, arguments_types=None):
        type_t.__init__(self)
        calldef_type_t.__init__(self, return_type, arguments_types)

    @staticmethod
    def create_decl_string(return_type, arguments_types, with_defaults=True):
        """
        returns free function type

        :param return_type: function return type
        :type return_type: :class:`type_t`
        :param arguments_types: list of argument :class:`type <type_t>`
        :rtype: :class:`free_function_type_t`
        """
        f = lambda x: x.build_decl_string(with_defaults)
        return free_function_type_t.NAME_TEMPLATE % {
            'return_type': return_type.build_decl_string(with_defaults),
            'arguments': ','.join(
                map(
                    f,
                    arguments_types))}

    def build_decl_string(self, with_defaults=True):
        return self.create_decl_string(
            self.return_type,
            self.arguments_types,
            with_defaults)

    def _clone_impl(self):
        rt_clone = None
        if self.return_type:
            rt_clone = self.return_type.clone()
        return free_function_type_t(
            rt_clone, [
                arg.clone() for arg in self.arguments_types])

    # TODO: create real typedef
    def create_typedef(self, typedef_name, unused=None, with_defaults=True):
        """returns string, that contains valid C++ code, that defines typedef
        to function type

        :param name: the desired name of typedef
        """
        # unused argument simplifies user code
        f = lambda x: x.build_decl_string(with_defaults)
        return free_function_type_t.TYPEDEF_NAME_TEMPLATE % {
            'typedef_name': typedef_name,
            'return_type': self.return_type.build_decl_string(with_defaults),
            'arguments': ','.join(map(f, self.arguments_types))}

class member_function_type_t(type_t, calldef_type_t):

    """describes member function type"""
    NAME_TEMPLATE = (
        '%(return_type)s ( %(class)s::* )( %(arguments)s )%(has_const)s')
    TYPEDEF_NAME_TEMPLATE = (
        '%(return_type)s ( %(class)s::*%(typedef_name)s' +
        ')( %(arguments)s ) %(has_const)s')

    def __init__(
            self,
            class_inst=None,
            return_type=None,
            arguments_types=None,
            has_const=False):
        type_t.__init__(self)
        calldef_type_t.__init__(self, return_type, arguments_types)
        self._has_const = has_const
        self._class_inst = class_inst

    @property
    def has_const(self):
        """describes, whether function has const modifier"""
        return self._has_const

    @has_const.setter
    def has_const(self, has_const):
        self._has_const = has_const

    @property
    def class_inst(self):
        """reference to parent :class:`class <declaration_t>`"""
        return self._class_inst

    @class_inst.setter
    def class_inst(self, class_inst):
        self._class_inst = class_inst

    # TODO: create real typedef
    def create_typedef(
            self,
            typedef_name,
            class_alias=None,
            with_defaults=True):
        """creates typedef to the function type

        :param typedef_name: desired type name
        :rtype: string
        """
        has_const_str = ''
        if self.has_const:
            has_const_str = 'const'
        if None is class_alias:
            if with_defaults:
                class_alias = self.class_inst.decl_string
            else:
                class_alias = self.class_inst.partial_decl_string
        f = lambda x: x.build_decl_string(with_defaults)
        return member_function_type_t.TYPEDEF_NAME_TEMPLATE % {
            'typedef_name': typedef_name,
            'return_type': self.return_type.build_decl_string(with_defaults),
            'class': class_alias,
            'arguments': ','.join(
                map(
                    f,
                    self.arguments_types)),
            'has_const': has_const_str}

    def create(self):
        return self.build_decl_string(
            self.return_type,
            self.class_inst.decl_string,
            self.arguments_types,
            self.has_const)

    @staticmethod
    def create_decl_string(
            return_type,
            class_decl_string,
            arguments_types,
            has_const,
            with_defaults=True):
        has_const_str = ''
        if has_const:
            has_const_str = 'const'
        return_type_decl_string = ''
        if return_type:
            return_type_decl_string = return_type.build_decl_string(
                with_defaults)
        f = lambda x: x.build_decl_string(with_defaults)
        return member_function_type_t.NAME_TEMPLATE % {
            'return_type': return_type_decl_string,
            'class': class_decl_string,
            'arguments': ','.join(
                map(
                    f,
                    arguments_types)),
            'has_const': has_const_str}

    def build_decl_string(self, with_defaults=True):
        return self.create_decl_string(
            self.return_type,
            self.class_inst.decl_string,
            self.arguments_types,
            self.has_const,
            with_defaults)

    def _clone_impl(self):
        rt_clone = None
        if self.return_type:
            rt_clone = self.return_type.clone()

        return member_function_type_t(
            self.class_inst, rt_clone, [
                arg.clone() for arg in self.arguments_types], self.has_const)

class member_variable_type_t(compound_t):

    """describes member variable type"""
    NAME_TEMPLATE = '%(type)s ( %(class)s::* )'

    def __init__(self, class_inst=None, variable_type=None):
        compound_t.__init__(self, class_inst)
        self._mv_type = variable_type

    @property
    def variable_type(self):
        """describes member variable :class:`type <type_t>`"""
        return self._mv_type

    @variable_type.setter
    def variable_type(self, new_type):
        self._mv_type = new_type

    def build_decl_string(self, with_defaults=True):
        return self.NAME_TEMPLATE % {
            'type': self.variable_type.build_decl_string(with_defaults),
            'class': self.base.build_decl_string(with_defaults)}

    def _clone_impl(self):
        return member_variable_type_t(
            class_inst=self.base,
            variable_type=self.variable_type.clone())

##########################################################################
# declarated types:

class declarated_t(type_t):

    """class that binds between to hierarchies: :class:`type_t`
    and :class:`declaration_t`"""

    def __init__(self, declaration):
        type_t.__init__(self)
        self._declaration = declaration

    @property
    def declaration(self):
        "reference to :class:`declaration_t`"
        return self._declaration

    @declaration.setter
    def declaration(self, new_declaration):
        self._declaration = new_declaration

    def build_decl_string(self, with_defaults=True):
        if with_defaults:
            return self._declaration.decl_string
        else:
            return self._declaration.partial_decl_string

    def _clone_impl(self):
        return declarated_t(self._declaration)

    @property
    def byte_size(self):
        "Size of this type in bytes @type: int"
        return self._declaration.byte_size

    @property
    def byte_align(self):
        "alignment of this type in bytes @type: int"
        return self._declaration.byte_align

class type_qualifiers_t(object):

    """contains additional information about type: mutable, static, extern"""

    def __init__(self, has_static=False, has_mutable=False):
        self._has_static = has_static
        self._has_mutable = has_mutable

    def __eq__(self, other):
        if not isinstance(other, type_qualifiers_t):
            return False
        return self.has_static == other.has_static \
            and self.has_mutable == other.has_mutable

    def __hash__(self):
        return super.__hash__(self)

    def __ne__(self, other):
        return not self.__eq__(other)

    def __lt__(self, other):
        if not isinstance(other, type_qualifiers_t):
            return object.__lt__(self, other)
        return self.has_static < other.has_static \
            and self.has_mutable < other.has_mutable

    @property
    def has_static(self):
        return self._has_static

    @has_static.setter
    def has_static(self, has_static):
        self._has_static = has_static

    @property
    def has_extern(self):
        """synonym to static"""
        return self.has_static

    @has_extern.setter
    def has_extern(self, has_extern):
        self.has_static = has_extern

    @property
    def has_mutable(self):
        return self._has_mutable

    @has_mutable.setter
    def has_mutable(self, has_mutable):
        self._has_mutable = has_mutable


text:
#include <math.h>
#include <GL/glew.h>
#include <string>
#ifndef WIN32
#include <sys/time.h>
#include <unistd.h>
#endif
#include <sys/types.h>

#include "ogldev_engine_common.h"
#include "ogldev_app.h"
#include "ogldev_util.h"
#include "ogldev_pipeline.h"
#include "ogldev_camera.h"
#include "ogldev_basic_lighting.h"
#include "ogldev_backend.h"
#include "ogldev_camera.h"
#include "ogldev_basic_mesh.h"
#include "ogldev_atb.h"

#define WINDOW_WIDTH  1280
#define WINDOW_HEIGHT 1024

Quaternion g_Rotation = Quaternion(0.707f, 0.0f, 0.0f, 0.707f);

typedef enum { BUDDHA, BUNNY, DRAGON } MESH_TYPE;

bool gAutoRotate = false;
int gGLMajorVersion = 0;

void TW_CALL AutoRotateCB(void *p)
{
    gAutoRotate = !gAutoRotate;
}

class Tutorial48 : public ICallbacks, public OgldevApp
{
public:

    Tutorial48()
    {
        m_pGameCamera = NULL;

        m_directionalLight.Name = "DirLight1";
        m_directionalLight.Color = Vector3f(1.0f, 1.0f, 1.0f);
        m_directionalLight.AmbientIntensity = 0.66f;
        m_directionalLight.DiffuseIntensity = 1.0f;
        m_directionalLight.Direction = Vector3f(1.0f, 0.0, 0.0);

        m_persProjInfo.FOV    = 60.0f;
        m_persProjInfo.Height = WINDOW_HEIGHT;
        m_persProjInfo.Width  = WINDOW_WIDTH;
        m_persProjInfo.zNear  = 1.0f;
        m_persProjInfo.zFar   = 1000.0f;

        m_pipeline.SetPerspectiveProj(m_persProjInfo);

        m_currentMesh = BUDDHA;
        m_rotationSpeed = 0.2f;

        glGetIntegerv(GL_MAJOR_VERSION, &gGLMajorVersion);
    }

    ~Tutorial48()
    {
        SAFE_DELETE(m_pGameCamera);
    }

    bool Init()
    {
        if (!m_atb.Init()) {
            return false;
        }

        Vector3f Pos(0.0f, 0.0f, 0.0f);
        Vector3f Target(0.0f, -0.1f, 1.0f);
        Vector3f Up(0.0, 1.0f, 0.0f);

        m_pGameCamera = new Camera(WINDOW_WIDTH, WINDOW_HEIGHT, Pos, Target, Up);

        if (!m_LightingTech.Init()) {
            OGLDEV_ERROR0("Error initializing the lighting technique\n");
            return false;
        }

        m_LightingTech.Enable();

        m_LightingTech.SetColorTextureUnit(COLOR_TEXTURE_UNIT_INDEX);
        m_LightingTech.SetDirectionalLight(m_directionalLight);
        m_LightingTech.SetMatSpecularIntensity(0.0f);
        m_LightingTech.SetMatSpecularPower(0);

        if (!m_mesh[BUDDHA].LoadMesh("../Content/buddha.obj")) {
            return false;
        }
        m_mesh[BUDDHA].GetOrientation().m_rotation.y = 180.0f;

        if (!m_mesh[BUNNY].LoadMesh("../Content/bunny.obj")) {
            return false;
        }

        if (!m_mesh[DRAGON].LoadMesh("../Content/dragon.obj")) {
            return false;
        }

        for (int i = 0 ; i < 3 ; i++) {
            m_mesh[i].GetOrientation().m_pos = Vector3f(0.0f, -8.0f, 34.0f);
        }
#ifndef WIN32
        // Disabled for now because it somehow clashes with the regular rendering...
 //       if (!m_fontRenderer.InitFontRenderer()) {
   //         return false;
   //     }
#endif
        bar = TwNewBar("OGLDEV");

        TwEnumVal Meshes[] = { {BUDDHA, "Buddha"}, {BUNNY, "Bunny"}, {DRAGON, "Dragon"}};
        TwType MeshTwType = TwDefineEnum("MeshType", Meshes, 3);
        TwAddVarRW(bar, "Mesh", MeshTwType, &m_currentMesh, NULL);

        TwAddSeparator(bar, "", NULL);

        m_pGameCamera->AddToATB(bar);

        TwAddSeparator(bar, "", NULL);

        TwAddVarRW(bar, "ObjRotation", TW_TYPE_QUAT4F, &g_Rotation, " axisz=-z ");

        TwAddButton(bar, "AutoRotate", AutoRotateCB, NULL, " label='Auto rotate' ");

        TwAddVarRW(bar, "Rot Speed", TW_TYPE_FLOAT, &m_rotationSpeed,
                   " min=0 max=5 step=0.1 keyIncr=s keyDecr=d help='Rotation speed (turns/second)' ");

        TwAddSeparator(bar, "", NULL);

        m_directionalLight.AddToATB(bar);

        float refresh = 0.1f;
        TwSetParam(bar, NULL, "refresh", TW_PARAM_FLOAT, 1, &refresh);

        TwDefine(" GLOBAL help='This example shows how to integrate AntTweakBar with OGLDEV.' "); // Message added to the help bar.

        TwAddVarRO(bar, "GL Major Version", TW_TYPE_INT32, &gGLMajorVersion, " label='Major version of GL' ");

        return true;
    }

    void Run()
    {
        OgldevBackendRun(this);
    }

    virtual void RenderSceneCB()
    {
        m_pGameCamera->OnRender();

        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        m_LightingTech.SetEyeWorldPos(m_pGameCamera->GetPos());
        m_LightingTech.SetDirectionalLight(m_directionalLight);

        m_pipeline.SetCamera(*m_pGameCamera);

        if (gAutoRotate) {
            m_mesh[m_currentMesh].GetOrientation().m_rotation.y += m_rotationSpeed;
        }
        else {
            m_mesh[m_currentMesh].GetOrientation().m_rotation = g_Rotation.ToDegrees();
        }

        m_pipeline.Orient(m_mesh[m_currentMesh].GetOrientation());
        m_LightingTech.SetWVP(m_pipeline.GetWVPTrans());
        m_LightingTech.SetWorldMatrix(m_pipeline.GetWorldTrans());

        m_mesh[m_currentMesh].Render();

      //  RenderFPS();
        CalcFPS();

        OgldevBackendSwapBuffers();
    }

    virtual void KeyboardCB(OGLDEV_KEY OgldevKey, OGLDEV_KEY_STATE OgldevKeyState)
    {
        if (OgldevKeyState == OGLDEV_KEY_STATE_PRESS) {
            if (m_atb.KeyboardCB(OgldevKey)) {
                return;
            }
        }

        switch (OgldevKey) {
            case OGLDEV_KEY_A:
            {
                int Pos[2], Size[2];
                TwGetParam(bar, NULL, "position", TW_PARAM_INT32, 2, Pos);
                TwGetParam(bar, NULL, "size", TW_PARAM_INT32, 2, Size);
                OgldevBackendSetMousePos(Pos[0] + Size[0]/2,
                                         Pos[1] + Size[1]/2);
                break;
            }
            case OGLDEV_KEY_B:
                m_currentMesh = DRAGON;
                break;
            case OGLDEV_KEY_C:
                m_currentMesh = BUDDHA;
                break;
            case OGLDEV_KEY_ESCAPE:
            case OGLDEV_KEY_q:
                OgldevBackendLeaveMainLoop();
                break;
            default:
                m_pGameCamera->OnKeyboard(OgldevKey);
        }
    }

    virtual void PassiveMouseCB(int x, int y)
    {
        if (!m_atb.PassiveMouseCB(x, y)) {
            m_pGameCamera->OnMouse(x, y);
        }
    }

    virtual void MouseCB(OGLDEV_MOUSE Button, OGLDEV_KEY_STATE State, int x, int y)
    {
        m_atb.MouseCB(Button, State, x, y);
    }

private:

    BasicLightingTechnique m_LightingTech;
    Camera* m_pGameCamera;
    DirectionalLight m_directionalLight;
    BasicMesh m_mesh[3];
    PersProjInfo m_persProjInfo;
    Pipeline m_pipeline;
    ATB m_atb;
    MESH_TYPE m_currentMesh;
    float m_rotationSpeed;
    TwBar *bar;
};

int main(int argc, char** argv)
{
    OgldevBackendInit(OGLDEV_BACKEND_TYPE_GLFW, argc, argv, true, false);

    if (!OgldevBackendCreateWindow(WINDOW_WIDTH, WINDOW_HEIGHT, false, "Tutorial 48")) {
        OgldevBackendTerminate();
		return 1;
    }

    SRANDOM;

    Tutorial48* pApp = new Tutorial48();

    if (!pApp->Init()) {
		delete pApp;
		OgldevBackendTerminate();
        return 1;
    }

    pApp->Run();

    delete pApp;

	OgldevBackendTerminate();

    return 0;
}


text:
const DrawCard = require('../../drawcard.js');

class BurningOnTheSand extends DrawCard {
    setupCardAbilities() {
        this.reaction({
            when: {
                afterChallenge: event => event.challenge.loser === this.controller && event.challenge.isUnopposed()
            },
            handler: context => {
                let opponent = context.event.challenge.winner;
                this.untilEndOfChallenge(ability => ({
                    match: card => card === card.controller.activePlot,
                    targetController: opponent,
                    effect: ability.effects.setClaim(0)
                }));

                this.game.addMessage('{0} plays {1} to set the claim value on {2}\'s revealed plot card to 0 until the end of the challenge',
                    this.controller, this, opponent);
            }
        });
    }
}

BurningOnTheSand.code = '04076';

module.exports = BurningOnTheSand;


text:
<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;

/* @var $this yii\web\View */
/* @var $model backend\models\Goods */
/* @var $form yii\widgets\ActiveForm */
?>

    <?php $form = ActiveForm::begin(); ?>

    <?= $form->field($model, 'goods_sn')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'goods_name')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'shop_price')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'promote_price')->textInput(['maxlength' => true]) ?>

        <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>

    <?php ActiveForm::end(); ?>


text:
var COLLISION_TYPE =
{
    RECTANGLE: 0,
    CIRCLE: 1
};

function Collision(type, player, properties)
{
    this.player = player;
    this.type = type;
    if(type === COLLISION_TYPE.CIRCLE)
    {
        if(properties.hasOwnProperty("radius"))
        {
            var _radius = parseInt(properties.radius);
            Object.defineProperty(this, "radius", {
                get: function() { return _radius; }
            });
        }else
        {
            console.log("Incorrect collision properties");
            return false;
        }
    }else if (type === COLLISION_TYPE.RECTANGLE)
    {
        if(properties.hasOwnProperty("size"))
        {
            var _size = new Vector(properties.size.x, properties.size.y);
            Object.defineProperty(this, "size", {
                get: function() { return _size; }
            });

            Object.defineProperty(this, "min", {
                get: function() { return new Vector(this.player.position.x - (this.size.x / 2), this.player.position.y - (this.size.y / 2)); }
            });

            Object.defineProperty(this, "max", {
                get: function() { return new Vector(this.player.position.x + (this.size.x / 2), this.player.position.y + (this.size.y / 2)); }
            });

            Object.defineProperty(this, "centerCornerLength", {
                get: function() { return Math.sqrt(Math.pow(this.size.x / 2, 2) + Math.pow(this.size.y / 2, 2)); }
            });
        }else
        {
            console.log("Incorrect collision properties");
            return false;
        }
    }
};

Collision.CheckRectangleCircle = function(r, c)
{
    if(r.centerCornerLength + c.radius > r.player.position.distanceToPoint(c.player.position))
    {

    }
    return [false, "none", "none"];
};

Collision.CheckCircles = function(c1, c2)
{
    if(c1.radius + c2.radius > c1.player.position.distanceToPoint(c2.player.position))
    {
        return [true, "none", "none"];
    }
    return [false, "none", "none"];
};

Collision.CheckCirclePoint = function(c, v)
{
    if(c.radius > c.player.position.distanceToPoint(v))
    {
        return [true, "none", "none"];
    }
    return [false, "none", "none"];
};

Collision.CheckRectangles = function(r1, r2)
{
    if(r1.centerCornerLength + r2.centerCornerLength > r1.player.position.distanceToPoint(r2.player.position))
    {
        var yHit = r1.max.y > r2.min.y && r1.min.y < r2.max.y;
        var xHit = r1.max.x > r2.min.x && r1.min.x < r2.max.x;
        if(yHit && xHit)
        {
            var line1 = new LineSegment(new Vector(r1.player.position.x, r1.player.position.y), new Vector(r2.player.position.x, r2.player.position.y));
            var line2 = new LineSegment(new Vector(r1.max.x, r1.min.y), new Vector(r1.max.x, r1.max.y));

            if(line1.intersection(line2))
            {
                return [true, "right", "left"];
                //RIGHT
            }

            line2 = new LineSegment(new Vector(r1.min.x, r1.max.y), new Vector(r1.min.x, r1.min.y));
            if(line1.intersection(line2))
            {
                return [true, "left", "right"];
                //LEFT
            }

            line2 = new LineSegment(new Vector(r1.min.x, r1.min.y), new Vector(r1.max.x, r1.min.y));
            if(line1.intersection(line2))
            {
                return [true, "top", "bottom"];
                //TOP
            }

            line2 = new LineSegment(new Vector(r1.min.x, r1.max.y), new Vector(r1.max.x, r1.max.y));
            if(line1.intersection(line2))
            {
                return [true, "bottom", "top"];
                //BOTTOM
            }
            if(r1.player.position.distanceToPoint(r2.player.position) < r1.size.x + r2.size.x)
            {
                return [true, "unkown", "unkown"];
            }
        }
    }
    return [false, "none", "none"];
};

Collision.CheckRectanglePoint = function(r1, v)
{
    if(r1.centerCornerLength > r1.player.position.distanceToPoint(v))
    {
        if(r1.min.x <= v.x && r1.max.x >= v.x)
        {
            if(r1.min.y <= v.y && r1.max.y >= v.y)
            {
                return [true, "none", "none"];
            }
        }
    }
    return [false, "none", "none"];
};


text:
package org.assertj.core.api.zoneddatetime;

import static java.lang.String.format;
import static java.time.ZoneOffset.UTC;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.util.FailureMessages.actualIsNull;

import java.time.ZoneId;
import java.time.ZonedDateTime;

import org.junit.jupiter.api.Test;

/**
 * @author Paweł Stawicki
 * @author Joel Costigliola
 * @author Marcin Zajączkowski
 */
public class ZonedDateTimeAssert_isBefore_Test extends ZonedDateTimeAssertBaseTest {

  @Test
  public void test_isBefore_assertion() {
    // WHEN
    assertThat(BEFORE).isBefore(REFERENCE);
    assertThat(BEFORE).isBefore(REFERENCE.toString());
    // THEN
    verify_that_isBefore_assertion_fails_and_throws_AssertionError(REFERENCE, REFERENCE);
    verify_that_isBefore_assertion_fails_and_throws_AssertionError(AFTER, REFERENCE);
  }

  @Test
  public void isBefore_should_compare_datetimes_in_actual_timezone() {
    ZonedDateTime utcDateTime = ZonedDateTime.of(2013, 6, 10, 0, 0, 0, 0, UTC);
    ZoneId cestTimeZone = ZoneId.of("Europe/Berlin");
    ZonedDateTime cestDateTime2 = ZonedDateTime.of(2013, 6, 10, 3, 0, 0, 0, cestTimeZone);
    //  utcDateTime < cestDateTime2
    assertThat(utcDateTime).as("in UTC time zone").isBefore(cestDateTime2);
    // utcDateTime = cestDateTime1
    try {
        ZonedDateTime cestDateTime1 = ZonedDateTime.of(2013, 6, 10, 2, 0, 0, 0, cestTimeZone);
      assertThat(utcDateTime).as("in UTC time zone").isBefore(cestDateTime1);
    } catch (AssertionError e) {
      return;
    }
    fail("Should have thrown AssertionError");
  }

  @Test
  public void test_isBefore_assertion_error_message() {
    assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> assertThat(ZonedDateTime.of(2000, 1, 5, 3, 0, 0, 0, UTC)).isBefore(ZonedDateTime.of(1998, 1, 1, 3, 3, 0, 0, UTC)))
                                                   .withMessage(format("%nExpecting:%n  <2000-01-05T03:00Z>%nto be strictly before:%n  <1998-01-01T03:03Z>"));
  }

  @Test
  public void should_fail_if_actual_is_null() {
    assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> {
      ZonedDateTime actual = null;
      assertThat(actual).isBefore(ZonedDateTime.now());
    }).withMessage(actualIsNull());
  }

  @Test
  public void should_fail_if_dateTime_parameter_is_null() {
    assertThatIllegalArgumentException().isThrownBy(() -> assertThat(ZonedDateTime.now()).isBefore((ZonedDateTime) null))
                                        .withMessage("The ZonedDateTime to compare actual with should not be null");
  }

  @Test
  public void should_fail_if_dateTime_as_string_parameter_is_null() {
    assertThatIllegalArgumentException().isThrownBy(() -> assertThat(ZonedDateTime.now()).isBefore((String) null))
                                        .withMessage("The String representing the ZonedDateTime to compare actual with should not be null");
  }

  private static void verify_that_isBefore_assertion_fails_and_throws_AssertionError(ZonedDateTime dateToTest,
      ZonedDateTime reference) {
    try {
      assertThat(dateToTest).isBefore(reference);
    } catch (AssertionError e) {
      // AssertionError was expected, test same assertion with String based parameter
      try {
        assertThat(dateToTest).isBefore(reference.toString());
      } catch (AssertionError e2) {
        // AssertionError was expected (again)
        return;
      }
    }
    fail("Should have thrown AssertionError");
  }

}