<commit_before>/*
 * Copyright 2007-2017 Content Management AG
 * All rights reserved.
 *
 * author: Max Kellermann <mk@cm4all.com>
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * - Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *
 * - 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.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * ``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
 * FOUNDATION 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.
 */

#include "rubber.hxx"
#include "util/Compiler.h"

#include <gtest/gtest.h>

#include <assert.h>
#include <stdint.h>
#include <stdlib.h>

static void
Fill(void *_p, size_t length, unsigned seed)
{
    for (uint8_t *p = (uint8_t *)_p, *end = p + length; p != end; ++p)
        *p = (uint8_t)seed++;
}

gcc_pure
static bool
Check(const void *_p, size_t length, unsigned seed)
{
    for (const uint8_t *p = (const uint8_t *)_p, *end = p + length;
         p != end; ++p)
        if (*p != (uint8_t)seed++)
            return false;

    return true;
}

static void
FillRubber(Rubber *r, unsigned id, size_t length)
{
    Fill(rubber_write(r, id), length, id);
}

static unsigned
AddFillRubber(Rubber *r, size_t length)
{
    unsigned id = rubber_add(r, length);
    if (id != 0)
        FillRubber(r, id, length);

    return id;
}

gcc_pure
static bool
CheckRubber(Rubber *r, unsigned id, size_t length)
{
    return Check(rubber_read(r, id), length, id);
}

TEST(RubberTest, Basic)
{
    size_t total = 4 * 1024 * 1024;

    Rubber *r = rubber_new(total);
    ASSERT_NE(r, nullptr);

    total = rubber_get_max_size(r);

    /* fill the whole "rubber" object with four quarters */

    unsigned a = AddFillRubber(r, total / 4);
    ASSERT_GT(a, 0);
    ASSERT_EQ(rubber_size_of(r, a), total / 4);

    unsigned b = AddFillRubber(r, total / 4);
    ASSERT_GT(b, 0);
    ASSERT_EQ(rubber_size_of(r, b), total / 4);

    ASSERT_EQ(rubber_get_netto_size(r), total / 2);
    ASSERT_EQ(rubber_get_brutto_size(r), total / 2);

    unsigned c = AddFillRubber(r, total / 4);
    ASSERT_GT(c, 0);
    ASSERT_EQ(rubber_size_of(r, c), total / 4);

    unsigned d = AddFillRubber(r, total / 4);
    ASSERT_GT(d, 0);
    ASSERT_EQ(rubber_size_of(r, d), total / 4);

    ASSERT_EQ(rubber_get_netto_size(r), total);
    ASSERT_EQ(rubber_get_brutto_size(r), total);

    /* another allocation must fail */

    ASSERT_EQ(AddFillRubber(r, 1), 0u);

    ASSERT_TRUE(CheckRubber(r, a, total / 4));
    ASSERT_TRUE(CheckRubber(r, b, total / 4));
    ASSERT_TRUE(CheckRubber(r, c, total / 4));
    ASSERT_TRUE(CheckRubber(r, d, total / 4));

    /* remove two non-adjacent allocations; the following
       rubber_add() call must automatically compress the "rubber"
       object, and the allocation succeeds */

    rubber_remove(r, b);
    rubber_remove(r, d);

    ASSERT_EQ(rubber_get_netto_size(r), total / 2);
    ASSERT_EQ(rubber_get_brutto_size(r), total * 3 / 4);

    unsigned e = AddFillRubber(r, total / 2);
    ASSERT_GT(e, 0);

    ASSERT_EQ(rubber_get_netto_size(r), total);
    ASSERT_EQ(rubber_get_brutto_size(r), total);

    ASSERT_TRUE(CheckRubber(r, a, total / 4));
    ASSERT_TRUE(CheckRubber(r, c, total / 4));
    ASSERT_TRUE(CheckRubber(r, e, total / 2));

    /* remove one after another, and see if rubber results are
       correct */

    rubber_remove(r, a);

    ASSERT_EQ(rubber_get_netto_size(r), total * 3 / 4);
    ASSERT_EQ(rubber_get_brutto_size(r), total);

    rubber_compress(r);

    ASSERT_EQ(rubber_get_netto_size(r), total * 3 / 4);
    ASSERT_EQ(rubber_get_brutto_size(r), total * 3 / 4);
    ASSERT_TRUE(CheckRubber(r, c, total / 4));
    ASSERT_TRUE(CheckRubber(r, e, total / 2));

    rubber_remove(r, c);

    ASSERT_EQ(rubber_get_netto_size(r), total / 2);
    ASSERT_EQ(rubber_get_brutto_size(r), total * 3 / 4);
    ASSERT_TRUE(CheckRubber(r, e, total / 2));

    rubber_compress(r);

    ASSERT_EQ(rubber_get_netto_size(r), total / 2);
    ASSERT_EQ(rubber_get_brutto_size(r), total / 2);
    ASSERT_TRUE(CheckRubber(r, e, total / 2));

    rubber_remove(r, e);

    ASSERT_EQ(rubber_get_netto_size(r), size_t(0u));
    ASSERT_EQ(rubber_get_brutto_size(r), size_t(0u));

    rubber_compress(r);

    ASSERT_EQ(rubber_get_netto_size(r), size_t(0u));
    ASSERT_EQ(rubber_get_brutto_size(r), size_t(0u));

    rubber_free(r);
}

TEST(RubberTest, Shrink)
{
    size_t total = 4 * 1024 * 1024;

    Rubber *r = rubber_new(total);
    ASSERT_NE(r, nullptr);

    total = rubber_get_max_size(r);

    /* fill the whole "rubber" object */

    unsigned a = AddFillRubber(r, total * 3 / 4);
    ASSERT_GT(a, 0);
    ASSERT_EQ(rubber_size_of(r, a), total * 3 / 4);

    unsigned b = AddFillRubber(r, total / 4);
    ASSERT_GT(b, 0);

    ASSERT_EQ(rubber_get_netto_size(r), total);
    ASSERT_EQ(rubber_get_brutto_size(r), total);

    /* another allocation must fail */

    ASSERT_EQ(AddFillRubber(r, 1), 0u);

    ASSERT_TRUE(CheckRubber(r, a, total * 3 / 4));
    ASSERT_TRUE(CheckRubber(r, b, total / 4));

    /* shrink the first allocation, try again */

    rubber_shrink(r, a, total / 4);
    ASSERT_EQ(rubber_size_of(r, a), total / 4);

    ASSERT_EQ(rubber_get_netto_size(r), total / 2);
    ASSERT_EQ(rubber_get_brutto_size(r), total);

    unsigned c = AddFillRubber(r, total / 2);
    ASSERT_GT(c, 0);

    ASSERT_EQ(rubber_get_netto_size(r), total);
    ASSERT_EQ(rubber_get_brutto_size(r), total);

    ASSERT_TRUE(CheckRubber(r, a, total / 4));
    ASSERT_TRUE(CheckRubber(r, b, total / 4));
    ASSERT_TRUE(CheckRubber(r, c, total / 2));

    /* shrink the third allocation, verify rubber_compress() */

    rubber_shrink(r, c, total / 4);

    ASSERT_EQ(rubber_get_netto_size(r), total * 3 / 4);
    ASSERT_EQ(rubber_get_brutto_size(r), total);

    ASSERT_TRUE(CheckRubber(r, a, total / 4));
    ASSERT_TRUE(CheckRubber(r, b, total / 4));
    ASSERT_TRUE(CheckRubber(r, c, total / 4));

    rubber_compress(r);

    ASSERT_EQ(rubber_get_netto_size(r), total * 3 / 4);
    ASSERT_EQ(rubber_get_brutto_size(r), total * 3 / 4);

    ASSERT_TRUE(CheckRubber(r, a, total / 4));
    ASSERT_TRUE(CheckRubber(r, b, total / 4));
    ASSERT_TRUE(CheckRubber(r, c, total / 4));

    /* clean up */

    rubber_remove(r, a);
    rubber_remove(r, b);
    rubber_remove(r, c);
    rubber_free(r);
}

/**
 * Fill the allocation table, see if the allocator fails
 * eventually even though there's memory available.
 */
TEST(RubberTest, FullTable)
{
    size_t total = 64 * 1024 * 1024;

    Rubber *r = rubber_new(total);
    ASSERT_NE(r, nullptr);

    total = rubber_get_max_size(r);

    static const size_t max = 300000;
    static unsigned ids[max], n = 0;
    while (n < max) {
        unsigned id = rubber_add(r, 1);
        if (id == 0)
            break;

        ASSERT_EQ((size_t)rubber_read(r, id) % 0x10, size_t(0));

        ids[n++] = id;
    }

    ASSERT_GT(n, 0);
    ASSERT_LT(n, max);

    /* just to be sure: try again, must still fail */

    ASSERT_EQ(rubber_add(r, 1024 * 1024), 0u);

    /* remove one item; now a large allocation must succeed */

    rubber_remove(r, ids[n / 2]);

    unsigned id = rubber_add(r, 1024 * 1024);
    ASSERT_GT(id, 0);
    ASSERT_EQ(id, ids[n / 2]);

    /* cleanup */

    for (unsigned i = 0; i < n; ++i)
        rubber_remove(r, ids[i]);

    rubber_free(r);
}
<commit_msg>test/t_rubber: call Rubber methods directly<commit_after>/*
 * Copyright 2007-2017 Content Management AG
 * All rights reserved.
 *
 * author: Max Kellermann <mk@cm4all.com>
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * - Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *
 * - 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.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * ``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
 * FOUNDATION 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.
 */

#include "rubber.hxx"
#include "util/Compiler.h"

#include <gtest/gtest.h>

#include <assert.h>
#include <stdint.h>
#include <stdlib.h>

static void
Fill(void *_p, size_t length, unsigned seed)
{
    for (uint8_t *p = (uint8_t *)_p, *end = p + length; p != end; ++p)
        *p = (uint8_t)seed++;
}

gcc_pure
static bool
Check(const void *_p, size_t length, unsigned seed)
{
    for (const uint8_t *p = (const uint8_t *)_p, *end = p + length;
         p != end; ++p)
        if (*p != (uint8_t)seed++)
            return false;

    return true;
}

static void
FillRubber(Rubber &r, unsigned id, size_t length)
{
    Fill(r.Write(id), length, id);
}

static unsigned
AddFillRubber(Rubber &r, size_t length)
{
    unsigned id = r.Add(length);
    if (id != 0)
        FillRubber(r, id, length);

    return id;
}

gcc_pure
static bool
CheckRubber(Rubber &r, unsigned id, size_t length)
{
    return Check(r.Read(id), length, id);
}

TEST(RubberTest, Basic)
{
    size_t total = 4 * 1024 * 1024;

    Rubber r(total);

    total = r.GetMaxSize();

    /* fill the whole "rubber" object with four quarters */

    unsigned a = AddFillRubber(r, total / 4);
    ASSERT_GT(a, 0);
    ASSERT_EQ(r.GetSizeOf(a), total / 4);

    unsigned b = AddFillRubber(r, total / 4);
    ASSERT_GT(b, 0);
    ASSERT_EQ(r.GetSizeOf(b), total / 4);

    ASSERT_EQ(r.GetNettoSize(), total / 2);
    ASSERT_EQ(r.GetBruttoSize(), total / 2);

    unsigned c = AddFillRubber(r, total / 4);
    ASSERT_GT(c, 0);
    ASSERT_EQ(r.GetSizeOf(c), total / 4);

    unsigned d = AddFillRubber(r, total / 4);
    ASSERT_GT(d, 0);
    ASSERT_EQ(r.GetSizeOf(d), total / 4);

    ASSERT_EQ(r.GetNettoSize(), total);
    ASSERT_EQ(r.GetBruttoSize(), total);

    /* another allocation must fail */

    ASSERT_EQ(AddFillRubber(r, 1), 0u);

    ASSERT_TRUE(CheckRubber(r, a, total / 4));
    ASSERT_TRUE(CheckRubber(r, b, total / 4));
    ASSERT_TRUE(CheckRubber(r, c, total / 4));
    ASSERT_TRUE(CheckRubber(r, d, total / 4));

    /* remove two non-adjacent allocations; the following
       rubber_add() call must automatically compress the "rubber"
       object, and the allocation succeeds */

    r.Remove(b);
    r.Remove(d);

    ASSERT_EQ(r.GetNettoSize(), total / 2);
    ASSERT_EQ(r.GetBruttoSize(), total * 3 / 4);

    unsigned e = AddFillRubber(r, total / 2);
    ASSERT_GT(e, 0);

    ASSERT_EQ(r.GetNettoSize(), total);
    ASSERT_EQ(r.GetBruttoSize(), total);

    ASSERT_TRUE(CheckRubber(r, a, total / 4));
    ASSERT_TRUE(CheckRubber(r, c, total / 4));
    ASSERT_TRUE(CheckRubber(r, e, total / 2));

    /* remove one after another, and see if rubber results are
       correct */

    r.Remove(a);

    ASSERT_EQ(r.GetNettoSize(), total * 3 / 4);
    ASSERT_EQ(r.GetBruttoSize(), total);

    r.Compress();

    ASSERT_EQ(r.GetNettoSize(), total * 3 / 4);
    ASSERT_EQ(r.GetBruttoSize(), total * 3 / 4);
    ASSERT_TRUE(CheckRubber(r, c, total / 4));
    ASSERT_TRUE(CheckRubber(r, e, total / 2));

    r.Remove(c);

    ASSERT_EQ(r.GetNettoSize(), total / 2);
    ASSERT_EQ(r.GetBruttoSize(), total * 3 / 4);
    ASSERT_TRUE(CheckRubber(r, e, total / 2));

    r.Compress();

    ASSERT_EQ(r.GetNettoSize(), total / 2);
    ASSERT_EQ(r.GetBruttoSize(), total / 2);
    ASSERT_TRUE(CheckRubber(r, e, total / 2));

    r.Remove(e);

    ASSERT_EQ(r.GetNettoSize(), size_t(0u));
    ASSERT_EQ(r.GetBruttoSize(), size_t(0u));

    r.Compress();

    ASSERT_EQ(r.GetNettoSize(), size_t(0u));
    ASSERT_EQ(r.GetBruttoSize(), size_t(0u));
}

TEST(RubberTest, Shrink)
{
    size_t total = 4 * 1024 * 1024;

    Rubber r(total);

    total = r.GetMaxSize();

    /* fill the whole "rubber" object */

    unsigned a = AddFillRubber(r, total * 3 / 4);
    ASSERT_GT(a, 0);
    ASSERT_EQ(r.GetSizeOf(a), total * 3 / 4);

    unsigned b = AddFillRubber(r, total / 4);
    ASSERT_GT(b, 0);

    ASSERT_EQ(r.GetNettoSize(), total);
    ASSERT_EQ(r.GetBruttoSize(), total);

    /* another allocation must fail */

    ASSERT_EQ(AddFillRubber(r, 1), 0u);

    ASSERT_TRUE(CheckRubber(r, a, total * 3 / 4));
    ASSERT_TRUE(CheckRubber(r, b, total / 4));

    /* shrink the first allocation, try again */

    r.Shrink(a, total / 4);
    ASSERT_EQ(r.GetSizeOf(a), total / 4);

    ASSERT_EQ(r.GetNettoSize(), total / 2);
    ASSERT_EQ(r.GetBruttoSize(), total);

    unsigned c = AddFillRubber(r, total / 2);
    ASSERT_GT(c, 0);

    ASSERT_EQ(r.GetNettoSize(), total);
    ASSERT_EQ(r.GetBruttoSize(), total);

    ASSERT_TRUE(CheckRubber(r, a, total / 4));
    ASSERT_TRUE(CheckRubber(r, b, total / 4));
    ASSERT_TRUE(CheckRubber(r, c, total / 2));

    /* shrink the third allocation, verify rubber_compress() */

    r.Shrink(c, total / 4);

    ASSERT_EQ(r.GetNettoSize(), total * 3 / 4);
    ASSERT_EQ(r.GetBruttoSize(), total);

    ASSERT_TRUE(CheckRubber(r, a, total / 4));
    ASSERT_TRUE(CheckRubber(r, b, total / 4));
    ASSERT_TRUE(CheckRubber(r, c, total / 4));

    r.Compress();

    ASSERT_EQ(r.GetNettoSize(), total * 3 / 4);
    ASSERT_EQ(r.GetBruttoSize(), total * 3 / 4);

    ASSERT_TRUE(CheckRubber(r, a, total / 4));
    ASSERT_TRUE(CheckRubber(r, b, total / 4));
    ASSERT_TRUE(CheckRubber(r, c, total / 4));

    /* clean up */

    r.Remove(a);
    r.Remove(b);
    r.Remove(c);
}

/**
 * Fill the allocation table, see if the allocator fails
 * eventually even though there's memory available.
 */
TEST(RubberTest, FullTable)
{
    size_t total = 64 * 1024 * 1024;

    Rubber r(total);

    total = r.GetMaxSize();

    static const size_t max = 300000;
    static unsigned ids[max], n = 0;
    while (n < max) {
        unsigned id = r.Add(1);
        if (id == 0)
            break;

        ASSERT_EQ((size_t)r.Read(id) % 0x10, size_t(0));

        ids[n++] = id;
    }

    ASSERT_GT(n, 0);
    ASSERT_LT(n, max);

    /* just to be sure: try again, must still fail */

    ASSERT_EQ(r.Add(1024 * 1024), 0u);

    /* remove one item; now a large allocation must succeed */

    r.Remove(ids[n / 2]);

    unsigned id = r.Add(1024 * 1024);
    ASSERT_GT(id, 0);
    ASSERT_EQ(id, ids[n / 2]);

    /* cleanup */

    for (unsigned i = 0; i < n; ++i)
        r.Remove(ids[i]);
}
<|endoftext|>


<commit_before>#include "inline_widget.hxx"
#include "uri/uri_parser.hxx"
#include "widget.hxx"
#include "widget_http.hxx"
#include "widget_resolver.hxx"
#include "processor.hxx"
#include "penv.hxx"
#include "async.hxx"
#include "http_response.hxx"
#include "istream/istream.hxx"
#include "istream/istream_iconv.hxx"
#include "pool.hxx"
#include "RootPool.hxx"
#include "session.hxx"
#include "event/Loop.hxx"

#include <glib.h>

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

const char *
Widget::GetLogName() const
{
    return "dummy";
}

Istream *
istream_iconv_new(gcc_unused struct pool *pool, Istream &input,
                  gcc_unused const char *tocode,
                  gcc_unused const char *fromcode)
{
    return &input;
}

void
Widget::Cancel()
{
}

bool
Widget::CheckHost(const char *, const char *) const
{
    return true;
}

RealmSessionLease
processor_env::GetRealmSession() const
{
    return nullptr;
}

void
session_put(Session *session gcc_unused)
{
}

void
Widget::LoadFromSession(gcc_unused RealmSession &session)
{
}

void
widget_http_request(gcc_unused struct pool &pool,
                    gcc_unused Widget &widget,
                    gcc_unused struct processor_env &env,
                    HttpResponseHandler &handler,
                    gcc_unused struct async_operation_ref &async_ref)
{
    GError *error = g_error_new_literal(g_quark_from_static_string("test"), 0,
                                        "Test");
    handler.InvokeError(error);
}

struct TestOperation {
    struct async_operation operation;
    struct pool *pool;
};

static void
test_abort(struct async_operation *ao gcc_unused)
{
    auto *to = (TestOperation *)ao;

    pool_unref(to->pool);
}

static const struct async_operation_class test_operation = {
    .abort = test_abort,
};

void
ResolveWidget(struct pool &pool,
              gcc_unused Widget &widget,
              gcc_unused struct tcache &translate_cache,
              gcc_unused WidgetResolverCallback callback,
              struct async_operation_ref &async_ref)
{
    auto to = NewFromPool<TestOperation>(pool);

    to->pool = &pool;

    to->operation.Init(test_operation);
    async_ref.Set(to->operation);
    pool_ref(&pool);
}

static void
test_abort_resolver(struct pool *pool)
{
    const char *uri;
    bool ret;
    struct parsed_uri parsed_uri;
    EventLoop event_loop;
    struct processor_env env;
    env.event_loop = &event_loop;
    Istream *istream;

    pool = pool_new_linear(pool, "test", 4096);

    uri = "/beng.html";
    ret = parsed_uri.Parse(uri);
    if (!ret) {
        fprintf(stderr, "uri_parse() failed\n");
        exit(2);
    }

    Widget widget(*pool, nullptr);

    istream = embed_inline_widget(*pool, env, false, widget);
    pool_unref(pool);

    istream->CloseUnused();
}

int main(int argc, char **argv) {
    (void)argc;
    (void)argv;

    test_abort_resolver(RootPool());
}
<commit_msg>test/t_wembed: use async_operation::Init2()<commit_after>#include "inline_widget.hxx"
#include "uri/uri_parser.hxx"
#include "widget.hxx"
#include "widget_http.hxx"
#include "widget_resolver.hxx"
#include "processor.hxx"
#include "penv.hxx"
#include "async.hxx"
#include "http_response.hxx"
#include "istream/istream.hxx"
#include "istream/istream_iconv.hxx"
#include "pool.hxx"
#include "RootPool.hxx"
#include "session.hxx"
#include "event/Loop.hxx"

#include <glib.h>

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

const char *
Widget::GetLogName() const
{
    return "dummy";
}

Istream *
istream_iconv_new(gcc_unused struct pool *pool, Istream &input,
                  gcc_unused const char *tocode,
                  gcc_unused const char *fromcode)
{
    return &input;
}

void
Widget::Cancel()
{
}

bool
Widget::CheckHost(const char *, const char *) const
{
    return true;
}

RealmSessionLease
processor_env::GetRealmSession() const
{
    return nullptr;
}

void
session_put(Session *session gcc_unused)
{
}

void
Widget::LoadFromSession(gcc_unused RealmSession &session)
{
}

void
widget_http_request(gcc_unused struct pool &pool,
                    gcc_unused Widget &widget,
                    gcc_unused struct processor_env &env,
                    HttpResponseHandler &handler,
                    gcc_unused struct async_operation_ref &async_ref)
{
    GError *error = g_error_new_literal(g_quark_from_static_string("test"), 0,
                                        "Test");
    handler.InvokeError(error);
}

struct TestOperation {
    struct async_operation operation;
    struct pool *pool;

    TestOperation(struct pool &_pool):pool(&_pool) {
        operation.Init2<TestOperation>();
    }

    void Abort() {
        pool_unref(pool);
    }
};

void
ResolveWidget(struct pool &pool,
              gcc_unused Widget &widget,
              gcc_unused struct tcache &translate_cache,
              gcc_unused WidgetResolverCallback callback,
              struct async_operation_ref &async_ref)
{
    auto to = NewFromPool<TestOperation>(pool, pool);
    async_ref.Set(to->operation);
    pool_ref(&pool);
}

static void
test_abort_resolver(struct pool *pool)
{
    const char *uri;
    bool ret;
    struct parsed_uri parsed_uri;
    EventLoop event_loop;
    struct processor_env env;
    env.event_loop = &event_loop;
    Istream *istream;

    pool = pool_new_linear(pool, "test", 4096);

    uri = "/beng.html";
    ret = parsed_uri.Parse(uri);
    if (!ret) {
        fprintf(stderr, "uri_parse() failed\n");
        exit(2);
    }

    Widget widget(*pool, nullptr);

    istream = embed_inline_widget(*pool, env, false, widget);
    pool_unref(pool);

    istream->CloseUnused();
}

int main(int argc, char **argv) {
    (void)argc;
    (void)argv;

    test_abort_resolver(RootPool());
}
<|endoftext|>


<commit_before>#include <cassert>
#include <cstdarg>
#include <cstdio>
#include <cstring>
#include <exception>

#include "cuda.h"

#include "objective_cuda.h"

namespace CuError {
    const char *strerror(CUresult result) {
        switch(result) {
            case CUDA_SUCCESS: return "No errors";
            case CUDA_ERROR_INVALID_VALUE: return "Invalid value";
            case CUDA_ERROR_OUT_OF_MEMORY: return "Out of memory";
            case CUDA_ERROR_NOT_INITIALIZED: return "Driver not initialized";
            case CUDA_ERROR_DEINITIALIZED: return "Driver deinitialized";

            case CUDA_ERROR_NO_DEVICE: return "No CUDA-capable device available";
            case CUDA_ERROR_INVALID_DEVICE: return "Invalid device";

            case CUDA_ERROR_INVALID_IMAGE: return "Invalid kernel image";
            case CUDA_ERROR_INVALID_CONTEXT: return "Invalid context";
            case CUDA_ERROR_CONTEXT_ALREADY_CURRENT: return "Context already current";
            case CUDA_ERROR_MAP_FAILED: return "Map failed";
            case CUDA_ERROR_UNMAP_FAILED: return "Unmap failed";
            case CUDA_ERROR_ARRAY_IS_MAPPED: return "Array is mapped";
            case CUDA_ERROR_ALREADY_MAPPED: return "Already mapped";
            case CUDA_ERROR_NO_BINARY_FOR_GPU: return "No binary for GPU";
            case CUDA_ERROR_ALREADY_ACQUIRED: return "Already acquired";
            case CUDA_ERROR_NOT_MAPPED: return "Not mapped";
            case CUDA_ERROR_NOT_MAPPED_AS_ARRAY: return "Mapped resource not available for access as an array";
            case CUDA_ERROR_NOT_MAPPED_AS_POINTER: return "Mapped resource not available for access as a pointer";
            case CUDA_ERROR_ECC_UNCORRECTABLE: return "Uncorrectable ECC error detected";
            case CUDA_ERROR_UNSUPPORTED_LIMIT: return "CUlimit not supported by device";

            case CUDA_ERROR_INVALID_SOURCE: return "Invalid source";
            case CUDA_ERROR_FILE_NOT_FOUND: return "File not found";
            case CUDA_ERROR_SHARED_OBJECT_SYMBOL_NOT_FOUND: return "Link to a shared object failed to resolve";
            case CUDA_ERROR_SHARED_OBJECT_INIT_FAILED: return "Shared object initialization failed";

            case CUDA_ERROR_INVALID_HANDLE: return "Invalid handle";

            case CUDA_ERROR_NOT_FOUND: return "Not found";

            case CUDA_ERROR_NOT_READY: return "CUDA not ready";

            case CUDA_ERROR_LAUNCH_FAILED: return "Launch failed";
            case CUDA_ERROR_LAUNCH_OUT_OF_RESOURCES: return "Launch exceeded resources";
            case CUDA_ERROR_LAUNCH_TIMEOUT: return "Launch exceeded timeout";
            case CUDA_ERROR_LAUNCH_INCOMPATIBLE_TEXTURING: return "Launch with incompatible texturing";

            case CUDA_ERROR_UNKNOWN: return "Unknown error";

            default: return "Unknown CUDA error value";
        }
    }

    void cu_assert(CUresult result, const char *message) {
        if (result != CUDA_SUCCESS) {
            throw CuException("%s : %s : %d", message, strerror(result), result);
        }
    }
}

Cuda::Cuda(int device_id, int init_flags) {
    // Init driver
    cuInit(init_flags);

    // Get device handler
    CUresult res = cuDeviceGet(&cuDevice, device_id);
    if (res != CUDA_SUCCESS) {
        throw CuError::DeviceNotExist("Device id: %d\n%s", device_id, CuError::strerror(res));
    }

    // Create context
    res = cuCtxCreate(&cuContext, 0, cuDevice);
    if (res != CUDA_SUCCESS) {
        throw CuError::ContextCreateError("%s", CuError::strerror(res));
    }
}

Cuda::~Cuda() {
    cuCtxDestroy(cuContext);
}

CUmodule Cuda::set_default_module(CUmodule module) {
    // Set default module from existing module
    default_module = module;
    return module;
}

CUmodule Cuda::set_default_module(const char *module_name) {
    // Set default module from path
    return set_default_module(create_module(module_name));
}

CUmodule Cuda::create_module(const char *module_name) {
    // Create module from .ptx
    CUmodule cuModule = (CUmodule)0;
    CUresult res = cuModuleLoad(&cuModule, module_name);
    if (res != CUDA_SUCCESS) {
        throw CuError::ModuleLoadError("Module id: %d\n%s", res, CuError::strerror(res));
    }
    return cuModule;
}

CUfunction Cuda::get_kernel(const char *kernel_name) {
    if (default_module) {
        return get_kernel(kernel_name, default_module);
    } else {
        throw CuError::DefaultModuleNotExist();
    }
}

CUfunction Cuda::get_kernel(const char *kernel_name, CUmodule cuModule) {
    // Get kernel handler from module
    CUfunction kernel;
    CUresult res = cuModuleGetFunction(&kernel, cuModule, kernel_name);
    if (res != CUDA_SUCCESS) {
        throw CuError::KernelGetError("Kernel name: %s\n%s", kernel_name, CuError::strerror(res));
    }
    return kernel;
}

void Cuda::launch_kernel_3d(CUfunction kernel,
        uint grid_dim_x, uint grid_dim_y, uint grid_dim_z,
        uint block_dim_x, uint block_dim_y, uint block_dim_z,
        void ** args,
        uint shared_mem_bytes,
        CUstream h_stream,
        void ** extra) {

    assert(grid_dim_x > 0);
    assert(grid_dim_y > 0);
    assert(grid_dim_z > 0);
    assert(block_dim_x > 0);
    assert(block_dim_y > 0);
    assert(block_dim_z > 0);

    if (args == NULL) {
        args = new void *[0];
    }

    CUresult res = cuLaunchKernel(kernel,
            grid_dim_x, grid_dim_y, grid_dim_z,
            block_dim_x, block_dim_y, block_dim_z,
            shared_mem_bytes,
            h_stream,
            args,
            extra);
    if (res != CUDA_SUCCESS){
        throw CuError::KernelLaunchError("%s", CuError::strerror(res));
    }
}
void Cuda::launch_kernel(CUfunction kernel,
        uint grid_dim_x,
        uint block_dim_x,
        void ** args,
        uint shared_mem_bytes,
        CUstream h_stream,
        void ** extra) {
    launch_kernel_3d(kernel,
            grid_dim_x, 1, 1,
            block_dim_x, 1, 1,
            args,
            shared_mem_bytes,
            h_stream,
            extra);
}
void Cuda::launch_kernel_2d(CUfunction kernel,
        uint grid_dim_x, uint grid_dim_y,
        uint block_dim_x, uint block_dim_y,
        void ** args,
        uint shared_mem_bytes,
        CUstream h_stream,
        void ** extra) {
    launch_kernel_3d(kernel,
            grid_dim_x, grid_dim_y, 1,
            block_dim_x, block_dim_y, 1,
            args,
            shared_mem_bytes,
            h_stream,
            extra);
}

void Cuda::ctx_synchronize() {
    CUresult res = cuCtxSynchronize();
    if (res != CUDA_SUCCESS) {
        throw CuError::ContextSynchronizeError("%s", CuError::strerror(res));
    }
}
<commit_msg>CuError::strerror: added new codes<commit_after>#include <cassert>
#include <cstdarg>
#include <cstdio>
#include <cstring>
#include <exception>

#include "cuda.h"

#include "objective_cuda.h"

namespace CuError {
    const char *strerror(CUresult result) {
        switch(result) {
            case CUDA_SUCCESS: return "No errors";
            case CUDA_ERROR_INVALID_VALUE: return "Invalid value";
            case CUDA_ERROR_OUT_OF_MEMORY: return "Out of memory";
            case CUDA_ERROR_NOT_INITIALIZED: return "Driver not initialized";
            case CUDA_ERROR_DEINITIALIZED: return "Driver deinitialized";

            case CUDA_ERROR_NO_DEVICE: return "No CUDA-capable device available";
            case CUDA_ERROR_INVALID_DEVICE: return "Invalid device";

            case CUDA_ERROR_INVALID_IMAGE: return "Invalid kernel image";
            case CUDA_ERROR_INVALID_CONTEXT: return "Invalid context";
            case CUDA_ERROR_CONTEXT_ALREADY_CURRENT: return "Context already current";
            case CUDA_ERROR_MAP_FAILED: return "Map failed";
            case CUDA_ERROR_UNMAP_FAILED: return "Unmap failed";
            case CUDA_ERROR_ARRAY_IS_MAPPED: return "Array is mapped";
            case CUDA_ERROR_ALREADY_MAPPED: return "Already mapped";
            case CUDA_ERROR_NO_BINARY_FOR_GPU: return "No binary for GPU";
            case CUDA_ERROR_ALREADY_ACQUIRED: return "Already acquired";
            case CUDA_ERROR_NOT_MAPPED: return "Not mapped";
            case CUDA_ERROR_NOT_MAPPED_AS_ARRAY: return "Mapped resource not available for access as an array";
            case CUDA_ERROR_NOT_MAPPED_AS_POINTER: return "Mapped resource not available for access as a pointer";
            case CUDA_ERROR_ECC_UNCORRECTABLE: return "Uncorrectable ECC error detected";
            case CUDA_ERROR_UNSUPPORTED_LIMIT: return "CUlimit not supported by device";

            case CUDA_ERROR_INVALID_SOURCE: return "Invalid source";
            case CUDA_ERROR_FILE_NOT_FOUND: return "File not found";
            case CUDA_ERROR_SHARED_OBJECT_SYMBOL_NOT_FOUND: return "Link to a shared object failed to resolve";
            case CUDA_ERROR_SHARED_OBJECT_INIT_FAILED: return "Shared object initialization failed";

            case CUDA_ERROR_INVALID_HANDLE: return "Invalid handle";

            case CUDA_ERROR_NOT_FOUND: return "Not found";

            case CUDA_ERROR_NOT_READY: return "CUDA not ready";

            case CUDA_ERROR_LAUNCH_FAILED: return "Launch failed";
            case CUDA_ERROR_LAUNCH_OUT_OF_RESOURCES: return "Launch exceeded resources";
            case CUDA_ERROR_LAUNCH_TIMEOUT: return "Launch exceeded timeout";
            case CUDA_ERROR_LAUNCH_INCOMPATIBLE_TEXTURING: return "Launch with incompatible texturing";

            case CUDA_ERROR_HOST_MEMORY_NOT_REGISTERED: return "Host memory not registered";
            case CUDA_ERROR_NOT_PERMITTED: return "Not permitted";
            case CUDA_ERROR_NOT_SUPPORTED: return "Not supported";

            case CUDA_ERROR_UNKNOWN: return "Unknown error";

            default: return "Unknown CUDA error value";
        }
    }

    void cu_assert(CUresult result, const char *message) {
        if (result != CUDA_SUCCESS) {
            throw CuException("%s : %s : %d", message, strerror(result), result);
        }
    }
}

Cuda::Cuda(int device_id, int init_flags) {
    // Init driver
    cuInit(init_flags);

    // Get device handler
    CUresult res = cuDeviceGet(&cuDevice, device_id);
    if (res != CUDA_SUCCESS) {
        throw CuError::DeviceNotExist("Device id: %d\n%s", device_id, CuError::strerror(res));
    }

    // Create context
    res = cuCtxCreate(&cuContext, 0, cuDevice);
    if (res != CUDA_SUCCESS) {
        throw CuError::ContextCreateError("%s", CuError::strerror(res));
    }
}

Cuda::~Cuda() {
    cuCtxDestroy(cuContext);
}

CUmodule Cuda::set_default_module(CUmodule module) {
    // Set default module from existing module
    default_module = module;
    return module;
}

CUmodule Cuda::set_default_module(const char *module_name) {
    // Set default module from path
    return set_default_module(create_module(module_name));
}

CUmodule Cuda::create_module(const char *module_name) {
    // Create module from .ptx
    CUmodule cuModule = (CUmodule)0;
    CUresult res = cuModuleLoad(&cuModule, module_name);
    if (res != CUDA_SUCCESS) {
        throw CuError::ModuleLoadError("Module id: %d\n%s", res, CuError::strerror(res));
    }
    return cuModule;
}

CUfunction Cuda::get_kernel(const char *kernel_name) {
    if (default_module) {
        return get_kernel(kernel_name, default_module);
    } else {
        throw CuError::DefaultModuleNotExist();
    }
}

CUfunction Cuda::get_kernel(const char *kernel_name, CUmodule cuModule) {
    // Get kernel handler from module
    CUfunction kernel;
    CUresult res = cuModuleGetFunction(&kernel, cuModule, kernel_name);
    if (res != CUDA_SUCCESS) {
        throw CuError::KernelGetError("Kernel name: %s\n%s", kernel_name, CuError::strerror(res));
    }
    return kernel;
}

void Cuda::launch_kernel_3d(CUfunction kernel,
        uint grid_dim_x, uint grid_dim_y, uint grid_dim_z,
        uint block_dim_x, uint block_dim_y, uint block_dim_z,
        void ** args,
        uint shared_mem_bytes,
        CUstream h_stream,
        void ** extra) {

    assert(grid_dim_x > 0);
    assert(grid_dim_y > 0);
    assert(grid_dim_z > 0);
    assert(block_dim_x > 0);
    assert(block_dim_y > 0);
    assert(block_dim_z > 0);

    if (args == NULL) {
        args = new void *[0];
    }

    CUresult res = cuLaunchKernel(kernel,
            grid_dim_x, grid_dim_y, grid_dim_z,
            block_dim_x, block_dim_y, block_dim_z,
            shared_mem_bytes,
            h_stream,
            args,
            extra);
    if (res != CUDA_SUCCESS){
        throw CuError::KernelLaunchError("%s", CuError::strerror(res));
    }
}
void Cuda::launch_kernel(CUfunction kernel,
        uint grid_dim_x,
        uint block_dim_x,
        void ** args,
        uint shared_mem_bytes,
        CUstream h_stream,
        void ** extra) {
    launch_kernel_3d(kernel,
            grid_dim_x, 1, 1,
            block_dim_x, 1, 1,
            args,
            shared_mem_bytes,
            h_stream,
            extra);
}
void Cuda::launch_kernel_2d(CUfunction kernel,
        uint grid_dim_x, uint grid_dim_y,
        uint block_dim_x, uint block_dim_y,
        void ** args,
        uint shared_mem_bytes,
        CUstream h_stream,
        void ** extra) {
    launch_kernel_3d(kernel,
            grid_dim_x, grid_dim_y, 1,
            block_dim_x, block_dim_y, 1,
            args,
            shared_mem_bytes,
            h_stream,
            extra);
}

void Cuda::ctx_synchronize() {
    CUresult res = cuCtxSynchronize();
    if (res != CUDA_SUCCESS) {
        throw CuError::ContextSynchronizeError("%s", CuError::strerror(res));
    }
}
<|endoftext|>


<commit_before>#define png_infopp_NULL (png_infopp)NULL
#define int_p_NULL (int*)NULL
#include <boost/gil/extension/io/png_io.hpp>

#include "cctag/fileDebug.hpp"
#include "cctag/visualDebug.hpp"
#include "cctag/progBase/exceptions.hpp"
#include "cctag/detection.hpp"
#include "cctag/view.hpp"
#include "cctag/image.hpp"
#include "cctag/cmdline.hpp"

#ifdef WITH_CUDA
#include "cuda/device_prop.hpp"
#include "cuda/debug_macros.hpp"
#endif // WITH_CUDA

#include <boost/filesystem/convenience.hpp>
#include <boost/filesystem.hpp>
#include <boost/progress.hpp>
#include <boost/exception/all.hpp>
#include <boost/ptr_container/ptr_list.hpp>
#include <boost/archive/xml_oarchive.hpp>
#include <boost/archive/xml_iarchive.hpp>

#include <terry/sampler/all.hpp>
#include <terry/sampler/resample_subimage.hpp>

#include <opencv/cv.h>
#include <opencv2/videoio.hpp>
#include <opencv2/core/core.hpp>
#include "opencv2/opencv.hpp"

#include <sstream>
#include <iostream>
#include <string>
#include <fstream>
#include <exception>

using namespace cctag;
using boost::timer;

using namespace boost::gil;
namespace bfs = boost::filesystem;

// static const std::string kUsageString = "Usage: detection image_file.png\n";

void detection(std::size_t frameId, const cv::Mat & src, const cctag::Parameters & params, const cctag::CCTagMarkersBank & bank, std::ofstream & output, std::string debugFileName = "")
{
    POP_ENTER;

    if (debugFileName == "") {
      debugFileName = "00000";
    }

    // Process markers detection
    boost::timer t;
    boost::ptr_list<CCTag> markers;

    CCTagVisualDebug::instance().initBackgroundImage(src);
    CCTagVisualDebug::instance().setImageFileName(debugFileName);
    CCTagFileDebug::instance().setPath(CCTagVisualDebug::instance().getPath());

    cctagDetection(markers, frameId , src, params, bank, true);

    CCTagFileDebug::instance().outPutAllSessions();
    CCTagFileDebug::instance().clearSessions();
    CCTagVisualDebug::instance().outPutAllSessions();
    CCTagVisualDebug::instance().clearSessions();

    CCTAG_COUT( markers.size() << " markers.");
    CCTAG_COUT("Total time: " << t.elapsed());
    CCTAG_COUT_NOENDL("Id : ");

    int i = 0;
    output << "#frame " << frameId << '\n';
    output << markers.size() << '\n';
    BOOST_FOREACH(const cctag::CCTag & marker, markers) {
      output << marker.x() << " " << marker.y() << " " << marker.id() << " " << marker.getStatus() << '\n';
      if (i == 0) {
          CCTAG_COUT_NOENDL(marker.id() + 1);
      } else {
          CCTAG_COUT_NOENDL(", " << marker.id() + 1);
      }
      ++i;
    }
    CCTAG_COUT("");
    POP_LEAVE;
}

/*************************************************************/
/*                    Main entry                             */
/*************************************************************/
int main(int argc, char** argv)
{
  if( cmdline.parse( argc, argv ) == false ) {
    cmdline.usage( argv[0] );
    return EXIT_FAILURE;
  }

  cmdline.print( argv[0] );

  // Check input path
  if( cmdline._filename.compare("") != 0){
    if (!boost::filesystem::exists( cmdline._filename )) {
      std::cerr << std::endl
        << "The input file \""<< cmdline._filename << "\" is missing" << std::endl;
      return EXIT_FAILURE;
    }
  }else{
    std::cerr << std::endl
        << "An input file is required" << std::endl;
    cmdline.usage( argv[0] );
    return EXIT_FAILURE;
  }

#ifdef WITH_CUDA
  popart::pop_cuda_only_sync_calls( cmdline._switchSync );
#endif

  // Check the (optional) parameters path
  std::size_t nCrowns = std::atoi(cmdline._nCrowns.c_str());
  cctag::Parameters params(nCrowns);

  if( cmdline._paramsFilename != "" ) {
    if (!boost::filesystem::exists( cmdline._paramsFilename )) {
      std::cerr << std::endl
        << "The input file \""<< cmdline._paramsFilename << "\" is missing" << std::endl;
      return EXIT_FAILURE;
    }

    // Read the parameter file provided by the user
    std::ifstream ifs( cmdline._paramsFilename.c_str() );
    boost::archive::xml_iarchive ia(ifs);
    ia >> boost::serialization::make_nvp("CCTagsParams", params);
    CCTAG_COUT(params._nCrowns);
    CCTAG_COUT(nCrowns);
    assert( nCrowns == params._nCrowns );
  } else {
    // Use the default parameters and save them in defaultParameters.xml
    cmdline._paramsFilename = "defaultParameters.xml";
    std::ofstream ofs( cmdline._paramsFilename.c_str() );
    boost::archive::xml_oarchive oa(ofs);
    oa << boost::serialization::make_nvp("CCTagsParams", params);
    CCTAG_COUT("Parameter file not provided. Default parameters are used.");
  }

  CCTagMarkersBank bank(params._nCrowns);
  if ( !cmdline._cctagBankFilename.empty())
  {
    bank = CCTagMarkersBank(cmdline._cctagBankFilename);
  }

#ifdef WITH_CUDA
  if( cmdline._useCuda ) {
    params.setUseCuda( true );
  }

  if( cmdline._debugDir != "" ) {
    params.setDebugDir( cmdline._debugDir );
  }

  popart::device_prop_t deviceInfo;
  deviceInfo.print( );
#endif // WITH_CUDA

  bfs::path myPath( cmdline._filename );
  std::string ext(myPath.extension().string());

  const bfs::path subFilenamePath(myPath.filename());
  const bfs::path parentPath( myPath.parent_path() == "" ? "." : myPath.parent_path());
  std::string outputFileName;
  if (!bfs::is_directory(myPath))
  {
    CCTagVisualDebug::instance().initializeFolders( parentPath , cmdline._outputFolderName , params._nCrowns );
    outputFileName = parentPath.string() + "/" + cmdline._outputFolderName + "/cctag" + std::to_string(nCrowns) + "CC.out";
  }else
  {
    CCTagVisualDebug::instance().initializeFolders( myPath , cmdline._outputFolderName , params._nCrowns );
    outputFileName = myPath.string() + "/" + cmdline._outputFolderName + "/cctag" + std::to_string(nCrowns) + "CC.out";
  }
  std::ofstream outputFile;
  outputFile.open( outputFileName );

  if ( (ext == ".png") || (ext == ".jpg") ) {
    POP_INFO("looking at image " << myPath.string());

    // Gray scale convertion
    cv::Mat src = cv::imread(cmdline._filename);
    cv::Mat graySrc;
    cv::cvtColor( src, graySrc, CV_BGR2GRAY );

    // Upscale original image
    /*{
            rgb8_image_t simage;
            simage.recreate( 2 * image.width(), 2 * image.height() );
            rgb8_view_t osvw( view( simage ) );
            terry::resize_view( svw, osvw, terry::sampler::bicubic_sampler() );
    }*/

    // Call the CCTag detection
    detection(0, graySrc, params, bank, outputFile, myPath.stem().string());
  //detection(0, my_view, params, bank, outputFile, myPath.stem().string());
} else if (ext == ".avi" )
  {
    CCTAG_COUT("*** Video mode ***");
    POP_INFO( "looking at video " << myPath.string() );

    // open video and check
    cv::VideoCapture video( cmdline._filename.c_str() );
    if(!video.isOpened())
    {
      CCTAG_COUT("Unable to open the video : " << cmdline._filename); return -1;
    }

    // play loop
    int lastFrame = video.get(CV_CAP_PROP_FRAME_COUNT);
    std::size_t frameId = 0;
    while( video.get(CV_CAP_PROP_POS_FRAMES) < lastFrame )
    {
      cv::Mat frame;
      video >> frame;
      cv::Mat imgGray;
      cv::cvtColor( frame, imgGray, CV_BGR2GRAY );

      // Set the output folder
      std::stringstream outFileName;
      outFileName << std::setfill('0') << std::setw(5) << frameId;

      // Call the CCTag detection
      detection(frameId, imgGray, params, bank, outputFile, outFileName.str());
      ++frameId;
    }
  } else if (bfs::is_directory(myPath)) {
    CCTAG_COUT("*** Image sequence mode ***");

    std::vector<bfs::path> vFileInFolder;

    std::copy(bfs::directory_iterator(myPath), bfs::directory_iterator(), std::back_inserter(vFileInFolder)); // is directory_entry, which is
    std::sort(vFileInFolder.begin(), vFileInFolder.end());

    std::size_t frameId = 0;

    for(const auto & fileInFolder : vFileInFolder) {
      const std::string subExt(bfs::extension(fileInFolder));

      if ( (subExt == ".png") || (subExt == ".jpg") ) {
        CCTAG_COUT( "Processing image " << fileInFolder.string() );

		cv::Mat src;
    	src = cv::imread(fileInFolder.string());

        cv::Mat imgGray;
        cv::cvtColor( src, imgGray, CV_BGR2GRAY );

        // Call the CCTag detection
        detection(frameId, imgGray, params, bank, outputFile, fileInFolder.stem().string());
++frameId;
      }
    }
  }else
  {
      throw std::logic_error("Unrecognized input.");
  }
  outputFile.close();
  return 0;
}

<commit_msg>Allows to invert the input frame for projected cctag scenario.<commit_after>#define png_infopp_NULL (png_infopp)NULL
#define int_p_NULL (int*)NULL
#include <boost/gil/extension/io/png_io.hpp>

#include "cctag/fileDebug.hpp"
#include "cctag/visualDebug.hpp"
#include "cctag/progBase/exceptions.hpp"
#include "cctag/detection.hpp"
#include "cctag/view.hpp"
#include "cctag/image.hpp"
#include "cctag/cmdline.hpp"

#ifdef WITH_CUDA
#include "cuda/device_prop.hpp"
#include "cuda/debug_macros.hpp"
#endif // WITH_CUDA

#include <boost/filesystem/convenience.hpp>
#include <boost/filesystem.hpp>
#include <boost/progress.hpp>
#include <boost/exception/all.hpp>
#include <boost/ptr_container/ptr_list.hpp>
#include <boost/archive/xml_oarchive.hpp>
#include <boost/archive/xml_iarchive.hpp>

#include <terry/sampler/all.hpp>
#include <terry/sampler/resample_subimage.hpp>

#include <opencv/cv.h>
#include <opencv2/videoio.hpp>
#include <opencv2/core/core.hpp>
#include "opencv2/opencv.hpp"

#include <sstream>
#include <iostream>
#include <string>
#include <fstream>
#include <exception>

using namespace cctag;
using boost::timer;

using namespace boost::gil;
namespace bfs = boost::filesystem;

// static const std::string kUsageString = "Usage: detection image_file.png\n";

void detection(std::size_t frameId, const cv::Mat & src, const cctag::Parameters & params, const cctag::CCTagMarkersBank & bank, std::ofstream & output, std::string debugFileName = "")
{
    POP_ENTER;

    if (debugFileName == "") {
      debugFileName = "00000";
    }

    // Process markers detection
    boost::timer t;
    boost::ptr_list<CCTag> markers;

    CCTagVisualDebug::instance().initBackgroundImage(src);
    CCTagVisualDebug::instance().setImageFileName(debugFileName);
    CCTagFileDebug::instance().setPath(CCTagVisualDebug::instance().getPath());

    cctagDetection(markers, frameId , src, params, bank, true);

    CCTagFileDebug::instance().outPutAllSessions();
    CCTagFileDebug::instance().clearSessions();
    CCTagVisualDebug::instance().outPutAllSessions();
    CCTagVisualDebug::instance().clearSessions();

    CCTAG_COUT( markers.size() << " markers.");
    CCTAG_COUT("Total time: " << t.elapsed());
    CCTAG_COUT_NOENDL("Id : ");

    int i = 0;
    output << "#frame " << frameId << '\n';
    output << markers.size() << '\n';
    BOOST_FOREACH(const cctag::CCTag & marker, markers) {
      output << marker.x() << " " << marker.y() << " " << marker.id() << " " << marker.getStatus() << '\n';
      if (i == 0) {
          CCTAG_COUT_NOENDL(marker.id() + 1);
      } else {
          CCTAG_COUT_NOENDL(", " << marker.id() + 1);
      }
      ++i;
    }
    CCTAG_COUT("");
    POP_LEAVE;
}

/*************************************************************/
/*                    Main entry                             */
/*************************************************************/
int main(int argc, char** argv)
{
  if( cmdline.parse( argc, argv ) == false ) {
    cmdline.usage( argv[0] );
    return EXIT_FAILURE;
  }

  cmdline.print( argv[0] );

  // Check input path
  if( cmdline._filename.compare("") != 0){
    if (!boost::filesystem::exists( cmdline._filename )) {
      std::cerr << std::endl
        << "The input file \""<< cmdline._filename << "\" is missing" << std::endl;
      return EXIT_FAILURE;
    }
  }else{
    std::cerr << std::endl
        << "An input file is required" << std::endl;
    cmdline.usage( argv[0] );
    return EXIT_FAILURE;
  }

#ifdef WITH_CUDA
  popart::pop_cuda_only_sync_calls( cmdline._switchSync );
#endif

  // Check the (optional) parameters path
  std::size_t nCrowns = std::atoi(cmdline._nCrowns.c_str());
  cctag::Parameters params(nCrowns);

  if( cmdline._paramsFilename != "" ) {
    if (!boost::filesystem::exists( cmdline._paramsFilename )) {
      std::cerr << std::endl
        << "The input file \""<< cmdline._paramsFilename << "\" is missing" << std::endl;
      return EXIT_FAILURE;
    }

    // Read the parameter file provided by the user
    std::ifstream ifs( cmdline._paramsFilename.c_str() );
    boost::archive::xml_iarchive ia(ifs);
    ia >> boost::serialization::make_nvp("CCTagsParams", params);
    CCTAG_COUT(params._nCrowns);
    CCTAG_COUT(nCrowns);
    assert( nCrowns == params._nCrowns );
  } else {
    // Use the default parameters and save them in defaultParameters.xml
    cmdline._paramsFilename = "defaultParameters.xml";
    std::ofstream ofs( cmdline._paramsFilename.c_str() );
    boost::archive::xml_oarchive oa(ofs);
    oa << boost::serialization::make_nvp("CCTagsParams", params);
    CCTAG_COUT("Parameter file not provided. Default parameters are used.");
  }

  CCTagMarkersBank bank(params._nCrowns);
  if ( !cmdline._cctagBankFilename.empty())
  {
    bank = CCTagMarkersBank(cmdline._cctagBankFilename);
  }

#ifdef WITH_CUDA
  if( cmdline._useCuda ) {
    params.setUseCuda( true );
  }

  if( cmdline._debugDir != "" ) {
    params.setDebugDir( cmdline._debugDir );
  }

  popart::device_prop_t deviceInfo;
  deviceInfo.print( );
#endif // WITH_CUDA

  bfs::path myPath( cmdline._filename );
  std::string ext(myPath.extension().string());

  const bfs::path subFilenamePath(myPath.filename());
  const bfs::path parentPath( myPath.parent_path() == "" ? "." : myPath.parent_path());
  std::string outputFileName;
  if (!bfs::is_directory(myPath))
  {
    CCTagVisualDebug::instance().initializeFolders( parentPath , cmdline._outputFolderName , params._nCrowns );
    outputFileName = parentPath.string() + "/" + cmdline._outputFolderName + "/cctag" + std::to_string(nCrowns) + "CC.out";
  }else
  {
    CCTagVisualDebug::instance().initializeFolders( myPath , cmdline._outputFolderName , params._nCrowns );
    outputFileName = myPath.string() + "/" + cmdline._outputFolderName + "/cctag" + std::to_string(nCrowns) + "CC.out";
  }
  std::ofstream outputFile;
  outputFile.open( outputFileName );

  if ( (ext == ".png") || (ext == ".jpg") ) {
    POP_INFO("looking at image " << myPath.string());

    // Gray scale convertion
    cv::Mat src = cv::imread(cmdline._filename);
    cv::Mat graySrc;
    cv::cvtColor( src, graySrc, CV_BGR2GRAY );

    // Upscale original image
    /*{
            rgb8_image_t simage;
            simage.recreate( 2 * image.width(), 2 * image.height() );
            rgb8_view_t osvw( view( simage ) );
            terry::resize_view( svw, osvw, terry::sampler::bicubic_sampler() );
    }*/

    // Call the CCTag detection
    detection(0, graySrc, params, bank, outputFile, myPath.stem().string());
  //detection(0, my_view, params, bank, outputFile, myPath.stem().string());
} else if (ext == ".avi" )
  {
    CCTAG_COUT("*** Video mode ***");
    POP_INFO( "looking at video " << myPath.string() );

    // open video and check
    cv::VideoCapture video( cmdline._filename.c_str() );
    if(!video.isOpened())
    {
      CCTAG_COUT("Unable to open the video : " << cmdline._filename); return -1;
    }

    // play loop
    int lastFrame = video.get(CV_CAP_PROP_FRAME_COUNT);
    std::size_t frameId = 0;
    while( video.get(CV_CAP_PROP_POS_FRAMES) < lastFrame )
    {
      cv::Mat frame;
      video >> frame;
      cv::Mat imgGray;
      cv::cvtColor( frame, imgGray, CV_BGR2GRAY );

      // Set the output folder
      std::stringstream outFileName;
      outFileName << std::setfill('0') << std::setw(5) << frameId;

      // Invert the image for the projection scenario
      //cv::Mat imgGrayInverted;
      //bitwise_not ( imgGray, imgGrayInverted );

      // Call the CCTag detection
      detection(frameId, imgGray, params, bank, outputFile, outFileName.str());
      ++frameId;
    }
  } else if (bfs::is_directory(myPath)) {
    CCTAG_COUT("*** Image sequence mode ***");

    std::vector<bfs::path> vFileInFolder;

    std::copy(bfs::directory_iterator(myPath), bfs::directory_iterator(), std::back_inserter(vFileInFolder)); // is directory_entry, which is
    std::sort(vFileInFolder.begin(), vFileInFolder.end());

    std::size_t frameId = 0;

    for(const auto & fileInFolder : vFileInFolder) {
      const std::string subExt(bfs::extension(fileInFolder));

      if ( (subExt == ".png") || (subExt == ".jpg") ) {
        CCTAG_COUT( "Processing image " << fileInFolder.string() );

		cv::Mat src;
    	src = cv::imread(fileInFolder.string());

        cv::Mat imgGray;
        cv::cvtColor( src, imgGray, CV_BGR2GRAY );

        // Call the CCTag detection
        detection(frameId, imgGray, params, bank, outputFile, fileInFolder.stem().string());
++frameId;
      }
    }
  }else
  {
      throw std::logic_error("Unrecognized input.");
  }
  outputFile.close();
  return 0;
}

<|endoftext|>


<commit_before><commit_msg>Fix hang in OSX build.<commit_after><|endoftext|>


<commit_before>#include "DiskInterface.h"
#include "anyware_serial.h"

/*!
  DISK-INIT

  Initialize disk game. This just allows the Arduino to listen to DISK commands.
 */
void disk_init_action()
{
  if (global_userid < 0) {
    printError("protocol error", "DISK-INIT received without IDENTITY");
    return;
  }

  if (global_debug) {
    Serial.println("DEBUG DISK-INIT received");
  }

  do_disk_init();
}

/*!
  DISK-EXIT

  Exit disk game. Stop any currently running animation or process.
  No longer listen to DISK commands.
*/
void disk_exit_action()
{
  if (global_debug) {
    Serial.println("DEBUG DISK-EXIT received");
  }

  do_disk_exit();
}

/*!
  DISK-RESET

  Resets the game, home the disks and afterwards to into "ready" mode.
*/
void disk_reset_action()
{
  if (global_state == STATE_IDLE) return;

  if (global_debug) {
    Serial.println("DEBUG DISK-RESET received");
  }

  do_disk_reset();
}

/*!
  DISK <diskid> POS <deg> DIR <dir> USER <userid>
*/
void disk_action()
{
  if (global_state == STATE_IDLE) return;

  char *arg = sCmd.next();
  uint8_t diskid = atoi(arg);
  if (diskid > 2) {
    printError(F("protocol error"), F("Illegal diskid argument"));
    return;
  }
  Direction dir = DIR_OFF;
  int pos = -1, userid = -1;
  while (arg = sCmd.next()) {
    if (!strcmp(arg, "POS")) {
      arg = sCmd.next();
      if (arg) {
        pos = atoi(arg);
      }
    }
    if (!strcmp(arg, "DIR")) {
      arg = sCmd.next();
      if (arg) {
        int dirarg = atoi(arg);
        switch (dirarg) {
        case DIR_CW:
        case DIR_OFF:
        case DIR_CCW:
          dir = (Direction)dirarg;
          break;
        default:
          printError("protocol error", "Illegal DIR argument");
          break;
        }
      }
    }
    if (!strcmp(arg, "USER")) {
      arg = sCmd.next();
      if (arg) {
        userid = atoi(arg);
        if (userid < 0 || userid > 2) {
          printError("protocol error", "Illegal USER argument");
          userid = 0;
        }
      }
    }
  }
  if (global_debug) {
    Serial.print(F("DEBUG DISK received: "));
    Serial.print(diskid);
    Serial.print(F(" POS "));
    Serial.print(pos);
    Serial.print(F(" DIR "));
    Serial.print(dir);
    Serial.println();
  }
  do_disk(diskid, userid, pos, dir);
}

/*!
  PANEL-SET <strip> <panel> <intensity> <color> <easing>

  Only listens for strip 3 and 4
*/
void panel_set_action()
{
  char *striparg = sCmd.next();
  if (!striparg) {
    printError(F("protocol error"), F("wrong # of parameters to PANEL-SET"));
    return;
  }
  uint8_t strip = atoi(striparg);
  if (strip < 3 || strip > 4) {
    printError(F("protocol error"), F("Illegal strip argument"));
    return;
  }

  char *panelarg = sCmd.next();
  if (!panelarg) {
    printError(F("protocol error"), F("wrong # of parameters to PANEL-SET"));
    return;
  }
  uint8_t panel = atoi(panelarg);
  if (strip == 3 && panel >= 3 ||
      strip == 4 && panel >= 6) {
    printError(F("protocol error"), F("Illegal panel argument"));
    return;
  }

  char *intensityarg = sCmd.next();
  if (!intensityarg) {
    printError(F("protocol error"), F("wrong # of parameters to PANEL-SET"));
    return;
  }
  uint8_t intensity = atoi(intensityarg);
  if (intensity > 100) {
    printError(F("protocol error"), F("Illegal intensity argument"));
    return;
  }

  char *colorarg = sCmd.next();
  uint32_t color;
  if (colorarg && strcmp(colorarg, "-")) {
    if (!getColor(colorarg, color)) {
      printError(F("protocol error"), F("Illegal color argument"));
      return;
    }
  }

  char *easingarg = sCmd.next();
  AnywareEasing::EasingType easing = AnywareEasing::BINARY;
  if (easingarg && strcmp(easingarg, "-")) {
    if (!AnywareEasing::getEasing(easingarg, easing)) {
      printError(F("protocol error"), F("Illegal easing argument"));
      return;
    }
  }

  if (global_debug) {
    Serial.print(F("DEBUG PANEL-SET received: "));
    Serial.print(easing);
    // FIXME: output
    Serial.println();
  }
  do_panel_set(strip, panel, intensity, color, easing);
}

/*!
  PANEL-SENSORS <userid> <sensors>
*/
void panel_pulse_action()
{
  char *striparg = sCmd.next();
  if (!striparg) {
    printError(F("protocol error"), F("wrong # of parameters to PANEL-PULSE"));
    return;
  }
  uint8_t strip = atoi(striparg);
  if (strip < 3 || strip > 4) {
    printError(F("protocol error"), F("Illegal strip argument"));
    return;
  }

  char *panelarg = sCmd.next();
  if (!panelarg) {
    printError(F("protocol error"), F("wrong # of parameters to PANEL-PULSE"));
    return;
  }
  uint8_t panel = atoi(panelarg);
  if (strip == 3 && panel >= 3 ||
      strip == 4 && panel >= 6) {
    printError(F("protocol error"), F("Illegal panel argument"));
    return;
  }

  char *intensityarg = sCmd.next();
  if (!intensityarg) {
    printError(F("protocol error"), F("wrong # of parameters to PANEL-PULSE"));
    return;
  }
  uint8_t intensity = atoi(intensityarg);
  if (intensity > 100) {
    printError(F("protocol error"), F("Illegal intensity argument"));
    return;
  }

  char *colorarg = sCmd.next();
  uint32_t color;
  if (colorarg && strcmp(colorarg, "-")) {
    if (!getColor(colorarg, color)) {
      printError(F("protocol error"), F("Illegal color argument"));
      return;
    }
  }

  char *easingarg = sCmd.next();
  AnywareEasing::EasingType easing = AnywareEasing::BINARY;
  if (easingarg && strcmp(easingarg, "-")) {
    if (!AnywareEasing::getEasing(easingarg, easing)) {
      printError(F("protocol error"), F("Illegal easing argument"));
      return;
    }
  }

  if (global_debug) {
    Serial.print(F("DEBUG PANEL-PULSE received: "));
    // FIXME: output
    Serial.println();
  }
  do_panel_pulse(strip, panel, intensity, color, easing);
}

/*!
  PANEL-INTENSITY <strip> <intensity>
*/
void panel_intensity_action()
{
  char *striparg = sCmd.next();
  if (!striparg) {
    printError(F("protocol error"), F("wrong # of parameters to PANEL-PULSE"));
    return;
  }
  uint8_t strip = atoi(striparg);
  if (strip < 3 || strip > 4) {
    printError(F("protocol error"), F("Illegal strip argument"));
    return;
  }

  char *intensityarg = sCmd.next();
  if (!intensityarg) {
    printError(F("protocol error"), F("wrong # of parameters to PANEL-PULSE"));
    return;
  }
  uint8_t intensity = atoi(intensityarg);
  if (intensity > 100) {
    printError(F("protocol error"), F("Illegal intensity argument"));
    return;
  }

  do_panel_intensity(strip, intensity);
}

void setupCommands()
{
  setupCommonCommands();

  Serial.println(F("SUPPORTED"));
  addCommand("DISK-INIT", disk_init_action);
  addCommand("DISK-RESET", disk_reset_action);
  addCommand("DISK", disk_action);
  addCommand("DISK-EXIT", disk_exit_action);

  addCommand("PANEL-SET", panel_set_action, " [34]");
  addCommand("PANEL-PULSE", panel_pulse_action, " [34]");
  addCommand("PANEL-INTENSITY", panel_intensity_action, " [34]");
  Serial.println(F("ENDSUPPORTED"));
}
<commit_msg>Better debug output<commit_after>#include "DiskInterface.h"
#include "anyware_serial.h"

/*!
  DISK-INIT

  Initialize disk game. This just allows the Arduino to listen to DISK commands.
 */
void disk_init_action()
{
  if (global_userid < 0) {
    printError("protocol error", "DISK-INIT received without IDENTITY");
    return;
  }

  if (global_debug) {
    Serial.println("DEBUG DISK-INIT received");
  }

  do_disk_init();
}

/*!
  DISK-EXIT

  Exit disk game. Stop any currently running animation or process.
  No longer listen to DISK commands.
*/
void disk_exit_action()
{
  if (global_debug) {
    Serial.println("DEBUG DISK-EXIT received");
  }

  do_disk_exit();
}

/*!
  DISK-RESET

  Resets the game, home the disks and afterwards to into "ready" mode.
*/
void disk_reset_action()
{
  if (global_state == STATE_IDLE) return;

  if (global_debug) {
    Serial.println("DEBUG DISK-RESET received");
  }

  do_disk_reset();
}

/*!
  DISK <diskid> POS <deg> DIR <dir> USER <userid>
*/
void disk_action()
{
  if (global_state == STATE_IDLE) return;

  char *arg = sCmd.next();
  uint8_t diskid = atoi(arg);
  if (diskid > 2) {
    printError(F("protocol error"), F("Illegal diskid argument"));
    return;
  }
  Direction dir = DIR_OFF;
  int pos = -1, userid = -1;
  while (arg = sCmd.next()) {
    if (!strcmp(arg, "POS")) {
      arg = sCmd.next();
      if (arg) {
        pos = atoi(arg);
      }
    }
    if (!strcmp(arg, "DIR")) {
      arg = sCmd.next();
      if (arg) {
        int dirarg = atoi(arg);
        switch (dirarg) {
        case DIR_CW:
        case DIR_OFF:
        case DIR_CCW:
          dir = (Direction)dirarg;
          break;
        default:
          printError("protocol error", "Illegal DIR argument");
          break;
        }
      }
    }
    if (!strcmp(arg, "USER")) {
      arg = sCmd.next();
      if (arg) {
        userid = atoi(arg);
        if (userid < 0 || userid > 2) {
          printError("protocol error", "Illegal USER argument");
          userid = 0;
        }
      }
    }
  }
  if (global_debug) {
    Serial.print(F("DEBUG DISK received: "));
    Serial.print(diskid);
    Serial.print(F(" POS "));
    Serial.print(pos);
    Serial.print(F(" DIR "));
    Serial.print(dir);
    Serial.println();
  }
  do_disk(diskid, userid, pos, dir);
}

/*!
  PANEL-SET <strip> <panel> <intensity> <color> <easing>

  Only listens for strip 3 and 4
*/
void panel_set_action()
{
  char *striparg = sCmd.next();
  if (!striparg) {
    printError(F("protocol error"), F("wrong # of parameters to PANEL-SET"));
    return;
  }
  uint8_t strip = atoi(striparg);
  if (strip < 3 || strip > 4) {
    printError(F("protocol error"), F("Illegal strip argument"));
    return;
  }

  char *panelarg = sCmd.next();
  if (!panelarg) {
    printError(F("protocol error"), F("wrong # of parameters to PANEL-SET"));
    return;
  }
  uint8_t panel = atoi(panelarg);
  if (strip == 3 && panel >= 3 ||
      strip == 4 && panel >= 6) {
    printError(F("protocol error"), F("Illegal panel argument"));
    return;
  }

  char *intensityarg = sCmd.next();
  if (!intensityarg) {
    printError(F("protocol error"), F("wrong # of parameters to PANEL-SET"));
    return;
  }
  uint8_t intensity = atoi(intensityarg);
  if (intensity > 100) {
    printError(F("protocol error"), F("Illegal intensity argument"));
    return;
  }

  char *colorarg = sCmd.next();
  uint32_t color;
  if (colorarg && strcmp(colorarg, "-")) {
    if (!getColor(colorarg, color)) {
      printError(F("protocol error"), F("Illegal color argument"));
      return;
    }
  }

  char *easingarg = sCmd.next();
  AnywareEasing::EasingType easing = AnywareEasing::BINARY;
  if (easingarg && strcmp(easingarg, "-")) {
    if (!AnywareEasing::getEasing(easingarg, easing)) {
      printError(F("protocol error"), F("Illegal easing argument"));
      return;
    }
  }

  if (global_debug) {
    Serial.print(F("DEBUG PANEL-SET received: "));
    Serial.print(strip);
    Serial.print(" ");
    Serial.print(panel);
    Serial.print(" ");
    Serial.print(intensity);
    Serial.print(" ");
    Serial.print(color, HEX);
    Serial.print(" ");
    Serial.print(easing);
    Serial.println();
  }
  do_panel_set(strip, panel, intensity, color, easing);
}

/*!
  PANEL-SENSORS <userid> <sensors>
*/
void panel_pulse_action()
{
  char *striparg = sCmd.next();
  if (!striparg) {
    printError(F("protocol error"), F("wrong # of parameters to PANEL-PULSE"));
    return;
  }
  uint8_t strip = atoi(striparg);
  if (strip < 3 || strip > 4) {
    printError(F("protocol error"), F("Illegal strip argument"));
    return;
  }

  char *panelarg = sCmd.next();
  if (!panelarg) {
    printError(F("protocol error"), F("wrong # of parameters to PANEL-PULSE"));
    return;
  }
  uint8_t panel = atoi(panelarg);
  if (strip == 3 && panel >= 3 ||
      strip == 4 && panel >= 6) {
    printError(F("protocol error"), F("Illegal panel argument"));
    return;
  }

  char *intensityarg = sCmd.next();
  if (!intensityarg) {
    printError(F("protocol error"), F("wrong # of parameters to PANEL-PULSE"));
    return;
  }
  uint8_t intensity = atoi(intensityarg);
  if (intensity > 100) {
    printError(F("protocol error"), F("Illegal intensity argument"));
    return;
  }

  char *colorarg = sCmd.next();
  uint32_t color;
  if (colorarg && strcmp(colorarg, "-")) {
    if (!getColor(colorarg, color)) {
      printError(F("protocol error"), F("Illegal color argument"));
      return;
    }
  }

  char *easingarg = sCmd.next();
  AnywareEasing::EasingType easing = AnywareEasing::BINARY;
  if (easingarg && strcmp(easingarg, "-")) {
    if (!AnywareEasing::getEasing(easingarg, easing)) {
      printError(F("protocol error"), F("Illegal easing argument"));
      return;
    }
  }

  if (global_debug) {
    Serial.print(F("DEBUG PANEL-PULSE received: "));
    Serial.print(strip);
    Serial.print(" ");
    Serial.print(panel);
    Serial.print(" ");
    Serial.print(intensity);
    Serial.print(" ");
    Serial.print(color, HEX);
    Serial.print(" ");
    Serial.print(easing);
    Serial.println();
  }
  do_panel_pulse(strip, panel, intensity, color, easing);
}

/*!
  PANEL-INTENSITY <strip> <intensity>
*/
void panel_intensity_action()
{
  char *striparg = sCmd.next();
  if (!striparg) {
    printError(F("protocol error"), F("wrong # of parameters to PANEL-PULSE"));
    return;
  }
  uint8_t strip = atoi(striparg);
  if (strip < 3 || strip > 4) {
    printError(F("protocol error"), F("Illegal strip argument"));
    return;
  }

  char *intensityarg = sCmd.next();
  if (!intensityarg) {
    printError(F("protocol error"), F("wrong # of parameters to PANEL-PULSE"));
    return;
  }
  uint8_t intensity = atoi(intensityarg);
  if (intensity > 100) {
    printError(F("protocol error"), F("Illegal intensity argument"));
    return;
  }

  do_panel_intensity(strip, intensity);
}

void setupCommands()
{
  setupCommonCommands();

  Serial.println(F("SUPPORTED"));
  addCommand("DISK-INIT", disk_init_action);
  addCommand("DISK-RESET", disk_reset_action);
  addCommand("DISK", disk_action);
  addCommand("DISK-EXIT", disk_exit_action);

  addCommand("PANEL-SET", panel_set_action, " [34]");
  addCommand("PANEL-PULSE", panel_pulse_action, " [34]");
  addCommand("PANEL-INTENSITY", panel_intensity_action, " [34]");
  Serial.println(F("ENDSUPPORTED"));
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: PageListWatcher.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-16 18:13:12 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library 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
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sd.hxx"

#include "PageListWatcher.hxx"

#include "sdpage.hxx"
#include <tools/debug.hxx>
#include <svx/svdmodel.hxx>

//////////////////////////////////////////////////////////////////////////////
// #109538#

void ImpPageListWatcher::ImpRecreateSortedPageListOnDemand()
{
    // clear vectors
    maPageVectorStandard.clear();
    maPageVectorNotes.clear();
    mpHandoutPage = 0L;

    // build up vectors again
    const sal_uInt32 nPageCount(ImpGetPageCount());

    for(sal_uInt32 a(0L); a < nPageCount; a++)
    {
        SdPage* pCandidate = ImpGetPage(a);
        DBG_ASSERT(pCandidate, "ImpPageListWatcher::ImpRecreateSortedPageListOnDemand: Invalid PageList in Model (!)");

        switch(pCandidate->GetPageKind())
        {
            case PK_STANDARD:
            {
                maPageVectorStandard.push_back(pCandidate);
                break;
            }
            case PK_NOTES:
            {
                maPageVectorNotes.push_back(pCandidate);
                break;
            }
            case PK_HANDOUT:
            {
                DBG_ASSERT(!mpHandoutPage, "ImpPageListWatcher::ImpRecreateSortedPageListOnDemand: Two Handout pages in PageList of Model (!)");
                mpHandoutPage = pCandidate;
                break;
            }
        }
    }

    // set to valid
    mbPageListValid = sal_True;
}

ImpPageListWatcher::ImpPageListWatcher(const SdrModel& rModel)
:   mrModel(rModel),
    mpHandoutPage(0L),
    mbPageListValid(sal_False)
{
}

ImpPageListWatcher::~ImpPageListWatcher()
{
}

SdPage* ImpPageListWatcher::GetSdPage(PageKind ePgKind, sal_uInt32 nPgNum)
{
    SdPage* pRetval(0L);

    if(!mbPageListValid)
    {
        ImpRecreateSortedPageListOnDemand();
    }

    switch(ePgKind)
    {
        case PK_STANDARD:
        {
            if (nPgNum>=0 && nPgNum<maPageVectorStandard.size())
                pRetval = maPageVectorStandard[nPgNum];
            else
            {
                DBG_ASSERT(nPgNum <= maPageVectorStandard.size(),
                    "ImpPageListWatcher::GetSdPage(PK_STANDARD): access out of range");
                DBG_WARNING2 ("    %d  > %d",
                    nPgNum, nPgNum<maPageVectorStandard.size());
            }
            break;
        }
        case PK_NOTES:
        {
            if (nPgNum>=0 && nPgNum<maPageVectorNotes.size())
                pRetval = maPageVectorNotes[nPgNum];
            else
            {
                DBG_ASSERT(nPgNum <= maPageVectorNotes.size(),
                    "ImpPageListWatcher::GetSdPage(PK_NOTES): access out of range");
                DBG_WARNING2("    %d > %d",
                    nPgNum, nPgNum<maPageVectorNotes.size());
            }
            break;
        }
        case PK_HANDOUT:
        {
//          #11420# for models used to transfer drawing shapes via clipboard its
//          ok to not have a handout page
//          DBG_ASSERT(mpHandoutPage, "ImpPageListWatcher::GetSdPage: access to non existing handout page (!)");
            DBG_ASSERT(nPgNum == 0L, "ImpPageListWatcher::GetSdPage: access to non existing handout page (!)");
            if (nPgNum == 0)
                pRetval = mpHandoutPage;
            else
            {
                DBG_ASSERT(nPgNum == 0L,
                    "ImpPageListWatcher::GetSdPage: access to non existing handout page (!)");
            }
            break;
        }
    }

    return pRetval;
}

sal_uInt32 ImpPageListWatcher::GetSdPageCount(PageKind ePgKind)
{
    sal_uInt32 nRetval(0L);

    if(!mbPageListValid)
    {
        ImpRecreateSortedPageListOnDemand();
    }

    switch(ePgKind)
    {
        case PK_STANDARD:
        {
            nRetval = maPageVectorStandard.size();
            break;
        }
        case PK_NOTES:
        {
            nRetval = maPageVectorNotes.size();
            break;
        }
        case PK_HANDOUT:
        {
            if(mpHandoutPage)
            {
                nRetval = 1L;
            }

            break;
        }
    }

    return nRetval;
}

//////////////////////////////////////////////////////////////////////////////

sal_uInt32 ImpDrawPageListWatcher::ImpGetPageCount() const
{
    return (sal_uInt32)mrModel.GetPageCount();
}

SdPage* ImpDrawPageListWatcher::ImpGetPage(sal_uInt32 nIndex) const
{
    return (SdPage*)mrModel.GetPage((sal_uInt16)nIndex);
}

ImpDrawPageListWatcher::ImpDrawPageListWatcher(const SdrModel& rModel)
:   ImpPageListWatcher(rModel)
{
}

ImpDrawPageListWatcher::~ImpDrawPageListWatcher()
{
}

//////////////////////////////////////////////////////////////////////////////

sal_uInt32 ImpMasterPageListWatcher::ImpGetPageCount() const
{
    return (sal_uInt32)mrModel.GetMasterPageCount();
}

SdPage* ImpMasterPageListWatcher::ImpGetPage(sal_uInt32 nIndex) const
{
    return (SdPage*)mrModel.GetMasterPage((sal_uInt16)nIndex);
}

ImpMasterPageListWatcher::ImpMasterPageListWatcher(const SdrModel& rModel)
:   ImpPageListWatcher(rModel)
{
}

ImpMasterPageListWatcher::~ImpMasterPageListWatcher()
{
}
<commit_msg>INTEGRATION: CWS sdwarningsbegone (1.6.38); FILE MERGED 2006/11/22 12:41:31 cl 1.6.38.1: #i69285# warning free code changes for unxlngi6.pro<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: PageListWatcher.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: kz $ $Date: 2006-12-12 16:30:15 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library 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
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sd.hxx"

#include "PageListWatcher.hxx"

#include "sdpage.hxx"
#include <tools/debug.hxx>
#include <svx/svdmodel.hxx>

//////////////////////////////////////////////////////////////////////////////
// #109538#

void ImpPageListWatcher::ImpRecreateSortedPageListOnDemand()
{
    // clear vectors
    maPageVectorStandard.clear();
    maPageVectorNotes.clear();
    mpHandoutPage = 0L;

    // build up vectors again
    const sal_uInt32 nPageCount(ImpGetPageCount());

    for(sal_uInt32 a(0L); a < nPageCount; a++)
    {
        SdPage* pCandidate = ImpGetPage(a);
        DBG_ASSERT(pCandidate, "ImpPageListWatcher::ImpRecreateSortedPageListOnDemand: Invalid PageList in Model (!)");

        switch(pCandidate->GetPageKind())
        {
            case PK_STANDARD:
            {
                maPageVectorStandard.push_back(pCandidate);
                break;
            }
            case PK_NOTES:
            {
                maPageVectorNotes.push_back(pCandidate);
                break;
            }
            case PK_HANDOUT:
            {
                DBG_ASSERT(!mpHandoutPage, "ImpPageListWatcher::ImpRecreateSortedPageListOnDemand: Two Handout pages in PageList of Model (!)");
                mpHandoutPage = pCandidate;
                break;
            }
        }
    }

    // set to valid
    mbPageListValid = sal_True;
}

ImpPageListWatcher::ImpPageListWatcher(const SdrModel& rModel)
:   mrModel(rModel),
    mpHandoutPage(0L),
    mbPageListValid(sal_False)
{
}

ImpPageListWatcher::~ImpPageListWatcher()
{
}

SdPage* ImpPageListWatcher::GetSdPage(PageKind ePgKind, sal_uInt32 nPgNum)
{
    SdPage* pRetval(0L);

    if(!mbPageListValid)
    {
        ImpRecreateSortedPageListOnDemand();
    }

    switch(ePgKind)
    {
        case PK_STANDARD:
        {
            if( nPgNum < (sal_uInt32)maPageVectorStandard.size() )
                pRetval = maPageVectorStandard[nPgNum];
            else
            {
                DBG_ASSERT(nPgNum <= maPageVectorStandard.size(),
                    "ImpPageListWatcher::GetSdPage(PK_STANDARD): access out of range");
                DBG_WARNING2 ("    %d  > %d",
                    nPgNum, nPgNum<maPageVectorStandard.size());
            }
            break;
        }
        case PK_NOTES:
        {
            if( nPgNum < (sal_uInt32)maPageVectorNotes.size() )
                pRetval = maPageVectorNotes[nPgNum];
            else
            {
                DBG_ASSERT(nPgNum <= maPageVectorNotes.size(),
                    "ImpPageListWatcher::GetSdPage(PK_NOTES): access out of range");
                DBG_WARNING2("    %d > %d",
                    nPgNum, nPgNum<maPageVectorNotes.size());
            }
            break;
        }
        case PK_HANDOUT:
        {
//          #11420# for models used to transfer drawing shapes via clipboard its
//          ok to not have a handout page
//          DBG_ASSERT(mpHandoutPage, "ImpPageListWatcher::GetSdPage: access to non existing handout page (!)");
            DBG_ASSERT(nPgNum == 0L, "ImpPageListWatcher::GetSdPage: access to non existing handout page (!)");
            if (nPgNum == 0)
                pRetval = mpHandoutPage;
            else
            {
                DBG_ASSERT(nPgNum == 0L,
                    "ImpPageListWatcher::GetSdPage: access to non existing handout page (!)");
            }
            break;
        }
    }

    return pRetval;
}

sal_uInt32 ImpPageListWatcher::GetSdPageCount(PageKind ePgKind)
{
    sal_uInt32 nRetval(0L);

    if(!mbPageListValid)
    {
        ImpRecreateSortedPageListOnDemand();
    }

    switch(ePgKind)
    {
        case PK_STANDARD:
        {
            nRetval = maPageVectorStandard.size();
            break;
        }
        case PK_NOTES:
        {
            nRetval = maPageVectorNotes.size();
            break;
        }
        case PK_HANDOUT:
        {
            if(mpHandoutPage)
            {
                nRetval = 1L;
            }

            break;
        }
    }

    return nRetval;
}

//////////////////////////////////////////////////////////////////////////////

sal_uInt32 ImpDrawPageListWatcher::ImpGetPageCount() const
{
    return (sal_uInt32)mrModel.GetPageCount();
}

SdPage* ImpDrawPageListWatcher::ImpGetPage(sal_uInt32 nIndex) const
{
    return (SdPage*)mrModel.GetPage((sal_uInt16)nIndex);
}

ImpDrawPageListWatcher::ImpDrawPageListWatcher(const SdrModel& rModel)
:   ImpPageListWatcher(rModel)
{
}

ImpDrawPageListWatcher::~ImpDrawPageListWatcher()
{
}

//////////////////////////////////////////////////////////////////////////////

sal_uInt32 ImpMasterPageListWatcher::ImpGetPageCount() const
{
    return (sal_uInt32)mrModel.GetMasterPageCount();
}

SdPage* ImpMasterPageListWatcher::ImpGetPage(sal_uInt32 nIndex) const
{
    return (SdPage*)mrModel.GetMasterPage((sal_uInt16)nIndex);
}

ImpMasterPageListWatcher::ImpMasterPageListWatcher(const SdrModel& rModel)
:   ImpPageListWatcher(rModel)
{
}

ImpMasterPageListWatcher::~ImpMasterPageListWatcher()
{
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: TextObjectBar.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 05:17:40 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library 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
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef SD_TEXT_OBJECT_BAR_HXX
#define SD_TEXT_OBJECT_BAR_HXX

#ifndef _SFXMODULE_HXX //autogen
#include <sfx2/module.hxx>
#endif
#ifndef _SFX_SHELL_HXX //autogen
#include <sfx2/shell.hxx>
#endif

#ifndef _SD_GLOB_HXX
#include "glob.hxx"
#endif

class CommandEvent;

namespace sd {

class View;
class ViewShell;
class Window;

class TextObjectBar
    : public SfxShell
{
public:
    TYPEINFO();
    SFX_DECL_INTERFACE(SD_IF_SDDRAWTEXTOBJECTBAR);

    TextObjectBar (
        ViewShell* pSdViewShell,
        SfxItemPool& rItemPool,
        ::sd::View* pSdView);
    virtual ~TextObjectBar (void);

    void GetAttrState( SfxItemSet& rSet );
    void Execute( SfxRequest &rReq );

    virtual void Command( const CommandEvent& rCEvt );
    virtual BOOL HasUIFeature( ULONG nFeature );

private:
    SfxItemPool& rPool;
    ViewShell* pViewShell;
    ::sd::View* pView;
};

} // end of namespace sd

#endif
<commit_msg>INTEGRATION: CWS viewswitch (1.3.72); FILE MERGED 2005/11/17 13:57:58 af 1.3.72.1: #i57551# Remove HasUIFeature() method.<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: TextObjectBar.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: obo $ $Date: 2006-03-21 17:27:56 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library 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
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef SD_TEXT_OBJECT_BAR_HXX
#define SD_TEXT_OBJECT_BAR_HXX

#ifndef _SFXMODULE_HXX //autogen
#include <sfx2/module.hxx>
#endif
#ifndef _SFX_SHELL_HXX //autogen
#include <sfx2/shell.hxx>
#endif

#ifndef _SD_GLOB_HXX
#include "glob.hxx"
#endif

class CommandEvent;

namespace sd {

class View;
class ViewShell;
class Window;

class TextObjectBar
    : public SfxShell
{
public:
    TYPEINFO();
    SFX_DECL_INTERFACE(SD_IF_SDDRAWTEXTOBJECTBAR);

    TextObjectBar (
        ViewShell* pSdViewShell,
        SfxItemPool& rItemPool,
        ::sd::View* pSdView);
    virtual ~TextObjectBar (void);

    void GetAttrState( SfxItemSet& rSet );
    void Execute( SfxRequest &rReq );

    virtual void Command( const CommandEvent& rCEvt );

private:
    SfxItemPool& rPool;
    ViewShell* pViewShell;
    ::sd::View* pView;
};

} // end of namespace sd

#endif
<|endoftext|>


<commit_before>#ifndef _SDD_CONF_DEFAULT_CONFIGURATIONS_HH_
#define _SDD_CONF_DEFAULT_CONFIGURATIONS_HH_

#include <cstdint> // uint16_t, uint32_t
#include <string>

#include "sdd/values/bitset.hh"
#include "sdd/values/flat_set.hh"

namespace sdd {

/*------------------------------------------------------------------------------------------------*/

/// @brief The default base configuration.
///
/// It doesn't include the configuration of identifier and values type. These informations
/// should be given by derived configurations.
struct default_configuration
{
  /// @brief The type of an SDD variable.
  using variable_type = unsigned int;

  /// @brief The type to store the number of elements in an alpha successor function.
  using alpha_size_type = std::uint16_t;

  /// @brief The type to store the number of elements in an operation.
  using operands_size_type = std::uint32_t;

  /// @brief The initial size of the hash table that stores SDD.
  std::size_t sdd_unique_table_size;

  /// @brief The size of the cache of SDD difference operations.
  std::size_t sdd_difference_cache_size;

  /// @brief The size of the cache of SDD intersection operations.
  std::size_t sdd_intersection_cache_size;

  /// @brief The size of the cache of SDD sum (union) operations.
  std::size_t sdd_sum_cache_size;

  /// @brief The size, in bytes, of the buffer for temporary containers allocation.
  std::size_t sdd_arena_size;

  /// @brief The initial size of the hash table that stores homomorphisms.
  std::size_t hom_unique_table_size;

  /// @brief The size of the cache of homomorphism applications.
  std::size_t hom_cache_size;

  /// @brief Tell if FPU registers shoud be preserved when using Expressions.
  static constexpr bool expression_preserve_fpu_registers = false;

  /// @brief Tell if the library should clean all memory when the manager is destroyed.
  ///
  /// Useful if you have only one instance of the library and that you don't want to wait for its
  /// cleanup at your program's exit.
  bool final_cleanup;

  /// @brief Default constructor.
  ///
  /// Initialize all parameters to their default values.
  default_configuration()
    : sdd_unique_table_size(10000000)
    , sdd_difference_cache_size(500000)
    , sdd_intersection_cache_size(500000)
    , sdd_sum_cache_size(1000000)
    , sdd_arena_size(1024*1024*8)
    , hom_unique_table_size(1000000)
    , hom_cache_size(1000000)
    , final_cleanup(true)
  {}
};

/*------------------------------------------------------------------------------------------------*/

struct flat_set_default_configuration
  : public default_configuration
{
  /// @brief The size of the hash table that stores flat_set<>.
  std::size_t flat_set_unique_table_size;

  flat_set_default_configuration()
    : default_configuration()
    , flat_set_unique_table_size(5000)
  {}
};

/*------------------------------------------------------------------------------------------------*/

struct conf0
  : public default_configuration
{
  using Identifier = std::string;
  using Values     = values::bitset<64>;
};

/*------------------------------------------------------------------------------------------------*/

struct conf1
  : public flat_set_default_configuration
{
  using Identifier = std::string;
  using Values     = values::flat_set<unsigned int>;
};

/*------------------------------------------------------------------------------------------------*/

struct conf2
  : public flat_set_default_configuration
{
  using Identifier = unsigned int;
  using Values     = values::flat_set<unsigned int>;
};

/*------------------------------------------------------------------------------------------------*/

} // namespace sdd

#endif // _SDD_CONF_DEFAULT_CONFIGURATIONS_HH_
<commit_msg>Increase default arena size.<commit_after>#ifndef _SDD_CONF_DEFAULT_CONFIGURATIONS_HH_
#define _SDD_CONF_DEFAULT_CONFIGURATIONS_HH_

#include <cstdint> // uint16_t, uint32_t
#include <string>

#include "sdd/values/bitset.hh"
#include "sdd/values/flat_set.hh"

namespace sdd {

/*------------------------------------------------------------------------------------------------*/

/// @brief The default base configuration.
///
/// It doesn't include the configuration of identifier and values type. These informations
/// should be given by derived configurations.
struct default_configuration
{
  /// @brief The type of an SDD variable.
  using variable_type = unsigned int;

  /// @brief The type to store the number of elements in an alpha successor function.
  using alpha_size_type = std::uint16_t;

  /// @brief The type to store the number of elements in an operation.
  using operands_size_type = std::uint32_t;

  /// @brief The initial size of the hash table that stores SDD.
  std::size_t sdd_unique_table_size;

  /// @brief The size of the cache of SDD difference operations.
  std::size_t sdd_difference_cache_size;

  /// @brief The size of the cache of SDD intersection operations.
  std::size_t sdd_intersection_cache_size;

  /// @brief The size of the cache of SDD sum (union) operations.
  std::size_t sdd_sum_cache_size;

  /// @brief The size, in bytes, of the buffer for temporary containers allocation.
  std::size_t sdd_arena_size;

  /// @brief The initial size of the hash table that stores homomorphisms.
  std::size_t hom_unique_table_size;

  /// @brief The size of the cache of homomorphism applications.
  std::size_t hom_cache_size;

  /// @brief Tell if FPU registers shoud be preserved when using Expressions.
  static constexpr bool expression_preserve_fpu_registers = false;

  /// @brief Tell if the library should clean all memory when the manager is destroyed.
  ///
  /// Useful if you have only one instance of the library and that you don't want to wait for its
  /// cleanup at your program's exit.
  bool final_cleanup;

  /// @brief Default constructor.
  ///
  /// Initialize all parameters to their default values.
  default_configuration()
    : sdd_unique_table_size(10000000)
    , sdd_difference_cache_size(500000)
    , sdd_intersection_cache_size(500000)
    , sdd_sum_cache_size(1000000)
    , sdd_arena_size(1024*1024*16)
    , hom_unique_table_size(1000000)
    , hom_cache_size(1000000)
    , final_cleanup(true)
  {}
};

/*------------------------------------------------------------------------------------------------*/

struct flat_set_default_configuration
  : public default_configuration
{
  /// @brief The size of the hash table that stores flat_set<>.
  std::size_t flat_set_unique_table_size;

  flat_set_default_configuration()
    : default_configuration()
    , flat_set_unique_table_size(5000)
  {}
};

/*------------------------------------------------------------------------------------------------*/

struct conf0
  : public default_configuration
{
  using Identifier = std::string;
  using Values     = values::bitset<64>;
};

/*------------------------------------------------------------------------------------------------*/

struct conf1
  : public flat_set_default_configuration
{
  using Identifier = std::string;
  using Values     = values::flat_set<unsigned int>;
};

/*------------------------------------------------------------------------------------------------*/

struct conf2
  : public flat_set_default_configuration
{
  using Identifier = unsigned int;
  using Values     = values::flat_set<unsigned int>;
};

/*------------------------------------------------------------------------------------------------*/

} // namespace sdd

#endif // _SDD_CONF_DEFAULT_CONFIGURATIONS_HH_
<|endoftext|>


<commit_before>#include <ros/ros.h>
#include <sensor_msgs/Imu.h>

int main(int argc, char **argv) {
  // Initialize ROS
  ros::init(argc, argv, "test_imu");
  ros::NodeHandle nh;

  // Create a publisher object
  ros::Publisher imuPub = nh.advertise<sensor_msgs::Imu>("imu/data",1);
  // Create an Imu message object
  sensor_msgs::Imu imuMsg;
  imuMsg.header.frame_id = "base_imu";
  // Create variables for yaw rate
  double yawRate = 0;
  imuMsg.header.stamp = ros::Time::now();
  imuMsg.angular_velocity.z = yawRate;
  imuPub.publish(imuMsg);

  ros::Rate loop_rate(30);
  while (ros::ok())
  {
    yawRate = 0;
    imuMsg.header.stamp = ros::Time::now();
    imuMsg.angular_velocity.z = yawRate;
    imuPub.publish(imuMsg);
    loop_rate.sleep();
  }
  return 0;
}
<commit_msg>Use paramter to set yaw rate.<commit_after>#include <ros/ros.h>
#include <sensor_msgs/Imu.h>

int main(int argc, char **argv) {
  // Initialize ROS
  ros::init(argc, argv, "test_imu");
  ros::NodeHandle nh;

  ros::NodeHandle private_nh("~");
  // Create variables for yaw rate
  double yawRate;
  if(!private_nh.getParam("rate", yawRate)) {
    yawRate = 0;
    ROS_WARN_STREAM("No rate was recieved. Using 0.0");
  }
  else {
    ROS_WARN_STREAM("Rate is " << yawRate);
  }

  // Create a publisher object
  ros::Publisher imuPub = nh.advertise<sensor_msgs::Imu>("imu/data",1);
  // Create an Imu message object
  sensor_msgs::Imu imuMsg;
  imuMsg.header.frame_id = "base_imu";
  imuMsg.header.stamp = ros::Time::now();
  imuMsg.angular_velocity.z = yawRate;
  imuPub.publish(imuMsg);

  ros::Rate loop_rate(30);
  while (ros::ok())
  {
    imuMsg.header.stamp = ros::Time::now();
    imuMsg.angular_velocity.z = yawRate;
    imuPub.publish(imuMsg);
    loop_rate.sleep();
  }
  return 0;
}
<|endoftext|>


<commit_before>#include <stdint.h>
#include <pthread.h>

static int32_t *low_32_bits(int64_t *ptr)
{
	int32_t *low= (int32_t*)ptr;
	// Test if the machine is big endian - constant propagation at compile time
	// should eliminate this completely.
	int one = 1;
	if (*(char*)&one != 1)
	{
		low++;
	}
	return low;
}

extern "C" int __cxa_guard_acquire(int64_t *guard_object)
{
	char first_byte = (*guard_object) >> 56;
	if (1 == first_byte) { return 0; }
	int32_t *lock = low_32_bits(guard_object);
	while (!__sync_bool_compare_and_swap_4(lock, 0, 1))
	{
		// TODO: Use some of the remaining 24 bits to define a mutex to sleep
		// on.  Whether this is actually worth bothering with depends on
		// whether there is likely to be any contention.
		sched_yield();
	}
	return 1;
}

extern "C" void __cxa_guard_abort(int64_t *guard_object)
{
	int32_t *lock = low_32_bits(guard_object);
	*lock = 0;
}
extern "C" void __cxa_guard_release(int64_t *guard_object)
{
	// Set the first byte to 1
	*guard_object |= ((int64_t)1) << 57;
	__cxa_guard_abort(guard_object);
}

<commit_msg>Fix in __cxa_guard_release<commit_after>#include <stdint.h>
#include <pthread.h>

static int32_t *low_32_bits(int64_t *ptr)
{
	int32_t *low= (int32_t*)ptr;
	// Test if the machine is big endian - constant propagation at compile time
	// should eliminate this completely.
	int one = 1;
	if (*(char*)&one != 1)
	{
		low++;
	}
	return low;
}

extern "C" int __cxa_guard_acquire(int64_t *guard_object)
{
	char first_byte = (*guard_object) >> 56;
	if (1 == first_byte) { return 0; }
	int32_t *lock = low_32_bits(guard_object);
	while (!__sync_bool_compare_and_swap_4(lock, 0, 1))
	{
		// TODO: Use some of the remaining 24 bits to define a mutex to sleep
		// on.  Whether this is actually worth bothering with depends on
		// whether there is likely to be any contention.
		sched_yield();
	}
	return 1;
}

extern "C" void __cxa_guard_abort(int64_t *guard_object)
{
	int32_t *lock = low_32_bits(guard_object);
	*lock = 0;
}
extern "C" void __cxa_guard_release(int64_t *guard_object)
{
	// Set the first byte to 1
	*guard_object |= ((int64_t)1) << 56;
	__cxa_guard_abort(guard_object);
}

<|endoftext|>