text:
#include <iostream>

#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE Main
#include <boost/test/unit_test.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/algorithm/string/trim.hpp>

#include "storage_api.h"
#include "protocolparser.h"
#include "resp.h"

using namespace Akumuli;

struct ConsumerMock : DbSession {
    std::vector<aku_ParamId>     param_;
    std::vector<aku_Timestamp>   ts_;
    std::vector<double>          data_;

    virtual ~ConsumerMock() {}

    virtual aku_Status write(const aku_Sample &sample) override {
        param_.push_back(sample.paramid);
        ts_.push_back(sample.timestamp);
        data_.push_back(sample.payload.float64);
        return AKU_SUCCESS;
    }

    virtual std::shared_ptr<DbCursor> query(std::string) override {
        throw "Not implemented";
    }

    virtual std::shared_ptr<DbCursor> suggest(std::string) override {
        throw "Not implemented";
    }

    virtual std::shared_ptr<DbCursor> search(std::string) override {
        throw "Not implemented";
    }

    virtual int param_id_to_series(aku_ParamId id, char* buf, size_t sz) override {
        auto str = std::to_string(id);
        assert(str.size() <= sz);
        memcpy(buf, str.data(), str.size());
        return static_cast<int>(str.size());
    }

    virtual aku_Status series_to_param_id(const char* begin, size_t sz, aku_Sample* sample) override {
        std::string num(begin, begin + sz);
        boost::algorithm::trim(num);
        sample->paramid = boost::lexical_cast<u64>(num);
        return AKU_SUCCESS;
    }

    virtual int name_to_param_id_list(const char* begin, const char* end, aku_ParamId* ids, u32 cap) override {
        auto nelem = std::count(begin, end, '|') + 1;
        if (nelem > cap) {
            return -1*static_cast<int>(nelem);
        }
        const char* it_begin = begin;
        const char* it_end = begin;
        for (int i = 0; i < nelem; i++) {
            //move it_end
            while(*it_end != '|' && it_end < end) {
                it_end++;
            }
            std::string val(it_begin, it_end);
            ids[i] = boost::lexical_cast<u64>(val);
            it_end++;
            it_begin = it_end;
        }
        return static_cast<int>(nelem);
    }
};

void null_deleter(const char*) {}

std::shared_ptr<const char> buffer_from_static_string(const char* str) {
    return std::shared_ptr<const char>(str, &null_deleter);
}

BOOST_AUTO_TEST_CASE(Test_protocol_parse_1) {
    const char *messages = "+1\r\n:2\r\n+34.5\r\n+6\r\n:7\r\n+8.9\r\n";
    std::shared_ptr<ConsumerMock> cons(new ConsumerMock());
    RESPProtocolParser parser(cons);
    auto buf = parser.get_next_buffer();
    memcpy(buf, messages, 29);
    parser.start();
    parser.parse_next(buf, 29);
    parser.close();

    BOOST_REQUIRE_EQUAL(cons->param_[0], 1);
    BOOST_REQUIRE_EQUAL(cons->param_[1], 6);
    BOOST_REQUIRE_EQUAL(cons->ts_[0], 2);
    BOOST_REQUIRE_EQUAL(cons->ts_[1], 7);
    BOOST_REQUIRE_EQUAL(cons->data_[0], 34.5);
    BOOST_REQUIRE_EQUAL(cons->data_[1], 8.9);
}

BOOST_AUTO_TEST_CASE(Test_protocol_parser_bulk_1) {
    const char *messages = "+1|2\r\n:3\r\n*2\r\n+45.6\r\n+7.89\r\n+10|11|12\r\n:13\r\n*3\r\n+1.4\r\n+15\r\n+1.6\r\n";
    std::shared_ptr<ConsumerMock> cons(new ConsumerMock());
    RESPProtocolParser parser(cons);
    auto buf = parser.get_next_buffer();
    memcpy(buf, messages, strlen(messages));
    parser.start();
    parser.parse_next(buf, static_cast<u32>(strlen(messages)));
    parser.close();

    BOOST_REQUIRE_EQUAL(cons->param_[0], 1);
    BOOST_REQUIRE_EQUAL(cons->param_[1], 2);
    BOOST_REQUIRE_EQUAL(cons->param_[2], 10);
    BOOST_REQUIRE_EQUAL(cons->param_[3], 11);
    BOOST_REQUIRE_EQUAL(cons->param_[4], 12);
    BOOST_REQUIRE_EQUAL(cons->ts_[0], 3);
    BOOST_REQUIRE_EQUAL(cons->ts_[1], 3);
    BOOST_REQUIRE_EQUAL(cons->ts_[2], 13);
    BOOST_REQUIRE_EQUAL(cons->ts_[3], 13);
    BOOST_REQUIRE_EQUAL(cons->ts_[4], 13);
    BOOST_REQUIRE_EQUAL(cons->data_[0], 45.6);
    BOOST_REQUIRE_EQUAL(cons->data_[1], 7.89);
    BOOST_REQUIRE_EQUAL(cons->data_[2], 1.4);
    BOOST_REQUIRE_EQUAL(cons->data_[3], 15.0);
    BOOST_REQUIRE_EQUAL(cons->data_[4], 1.6);
}

BOOST_AUTO_TEST_CASE(Test_protocol_parse_2) {

    const char *message1 = "+1\r\n:2\r\n+34.5\r\n+6\r\n:7\r\n+8.9";
    const char *message2 = "\r\n+10\r\n:11\r\n+12.13\r\n+14\r\n:15\r\n+16.7\r\n";

    std::shared_ptr<ConsumerMock> cons(new ConsumerMock);
    RESPProtocolParser parser(cons);
    parser.start();

    auto buf = parser.get_next_buffer();
    memcpy(buf, message1, 27);
    parser.parse_next(buf, 27);

    BOOST_REQUIRE_EQUAL(cons->param_.size(), 1);
    // 0
    BOOST_REQUIRE_EQUAL(cons->param_[0], 1);
    BOOST_REQUIRE_EQUAL(cons->ts_[0], 2);
    BOOST_REQUIRE_EQUAL(cons->data_[0], 34.5);

    buf = parser.get_next_buffer();
    memcpy(buf, message2, 37);
    parser.parse_next(buf, 37);

    BOOST_REQUIRE_EQUAL(cons->param_.size(), 4);
    // 1
    BOOST_REQUIRE_EQUAL(cons->param_[1], 6);
    BOOST_REQUIRE_EQUAL(cons->ts_[1], 7);
    BOOST_REQUIRE_EQUAL(cons->data_[1], 8.9);
    // 2
    BOOST_REQUIRE_EQUAL(cons->param_[2], 10);
    BOOST_REQUIRE_EQUAL(cons->ts_[2], 11);
    BOOST_REQUIRE_EQUAL(cons->data_[2], 12.13);
    // 3
    BOOST_REQUIRE_EQUAL(cons->param_[3], 14);
    BOOST_REQUIRE_EQUAL(cons->ts_[3], 15);
    BOOST_REQUIRE_EQUAL(cons->data_[3], 16.7);
    parser.close();
}

BOOST_AUTO_TEST_CASE(Test_protocol_parse_error_format) {
    const char *messages = "+1\r\n:2\r\n+34.5\r\n+2\r\n:d\r\n+8.9\r\n";
    std::shared_ptr<ConsumerMock> cons(new ConsumerMock);
    RESPProtocolParser parser(cons);
    parser.start();
    auto buf = parser.get_next_buffer();
    memcpy(buf, messages, 29);
    BOOST_REQUIRE_THROW(parser.parse_next(buf, 29), RESPError);
}

BOOST_AUTO_TEST_CASE(Test_protocol_parse_dictionary_error_format) {
    {
        const char *message = "*1\r\n";
        std::shared_ptr<ConsumerMock> cons(new ConsumerMock);
        RESPProtocolParser parser(cons);
        parser.start();
        auto buf = parser.get_next_buffer();
        memcpy(buf, message, strlen(message));
        BOOST_REQUIRE_THROW(parser.parse_next(buf, strlen(message)), ProtocolParserError);
    }
    {
        const char *message = "*2\r\n:1\r\n:2\r\n";
        std::shared_ptr<ConsumerMock> cons(new ConsumerMock);
        RESPProtocolParser parser(cons);
        parser.start();
        auto buf = parser.get_next_buffer();
        memcpy(buf, message, strlen(message));
        BOOST_REQUIRE_THROW(parser.parse_next(buf, strlen(message)), ProtocolParserError);
    }
    {
        const char *message = "*2\r\n+1\r\n+2\r\n";
        std::shared_ptr<ConsumerMock> cons(new ConsumerMock);
        RESPProtocolParser parser(cons);
        parser.start();
        auto buf = parser.get_next_buffer();
        memcpy(buf, message, strlen(message));
        BOOST_REQUIRE_THROW(parser.parse_next(buf, strlen(message)), ProtocolParserError);
    }
}

template<class Protocol, class Pred, class Mock>
void find_framing_issues(const char* message, size_t msglen, size_t pivot1, size_t pivot2, Pred const& pred, std::shared_ptr<Mock> cons) {

    auto buffer1 = buffer_from_static_string(message);
    auto buffer2 = buffer_from_static_string(message + pivot1);
    auto buffer3 = buffer_from_static_string(message + pivot2);

    PDU pdu1 = {
        buffer1,
        static_cast<u32>(pivot1),
        0u
    };
    PDU pdu2 = {
        buffer2,
        static_cast<u32>(pivot2 - pivot1),
        0u
    };
    PDU pdu3 = {
        buffer3,
        static_cast<u32>(msglen - pivot2),
        0u
    };

    Protocol parser(cons);
    parser.start();
    auto buf = parser.get_next_buffer();
    memcpy(buf, message, pivot1);
    parser.parse_next(buf, pivot1);

    buf = parser.get_next_buffer();
    memcpy(buf, message + pivot1, pivot2 - pivot1);
    parser.parse_next(buf, pivot2 - pivot1);

    buf = parser.get_next_buffer();
    memcpy(buf, message + pivot2, msglen - pivot2);
    parser.parse_next(buf, msglen - pivot2);

    parser.close();

    pred(cons);
}

/**
 * This test is created to find nontrivial framing issues in protocol parser.
 * Everything works fine when PDU contains entire record (series, timestamp and value)
 * but in the real world scenario this envariant can be broken and each record can be
 * scattered between many PDUs.
 */
BOOST_AUTO_TEST_CASE(Test_protocol_parser_framing) {

    const char *message = "+1\r\n:2\r\n+34.5\r\n"
                          "+6\r\n:7\r\n+8.9\r\n"
                          "+10\r\n:11\r\n+12.13\r\n"
                          "+14\r\n:15\r\n+16.7\r\n";

    auto pred = [] (std::shared_ptr<ConsumerMock> cons) {

        BOOST_REQUIRE_EQUAL(cons->param_.size(), 4);
        // 0
        BOOST_REQUIRE_EQUAL(cons->param_[0], 1);
        BOOST_REQUIRE_EQUAL(cons->ts_[0], 2);
        BOOST_REQUIRE_CLOSE_FRACTION(cons->data_[0], 34.5, 1e-9);
        // 1
        BOOST_REQUIRE_EQUAL(cons->param_[1], 6);
        BOOST_REQUIRE_EQUAL(cons->ts_[1], 7);
        BOOST_REQUIRE_CLOSE_FRACTION(cons->data_[1], 8.9, 1e-9);
        // 2
        BOOST_REQUIRE_EQUAL(cons->param_[2], 10);
        BOOST_REQUIRE_EQUAL(cons->ts_[2], 11);
        BOOST_REQUIRE_CLOSE_FRACTION(cons->data_[2], 12.13, 1e-9);
        // 3
        BOOST_REQUIRE_EQUAL(cons->param_[3], 14);
        BOOST_REQUIRE_EQUAL(cons->ts_[3], 15);
        BOOST_REQUIRE_CLOSE_FRACTION(cons->data_[3], 16.7, 1e-9);
    };

    size_t msglen = strlen(message);

    for (int i = 0; i < 100; i++) {
        size_t pivot1 = 1 + static_cast<size_t>(rand()) % (msglen / 2);
        size_t pivot2 = 1+ static_cast<size_t>(rand()) % (msglen - pivot1 - 2) + pivot1;
        std::shared_ptr<ConsumerMock> cons(new ConsumerMock);
        find_framing_issues<RESPProtocolParser>(message, msglen, pivot1, pivot2, pred, cons);
    }
}

BOOST_AUTO_TEST_CASE(Test_protocol_parser_framing_bulk) {

    const char *message = "+1|6\r\n:2\r\n*2\r\n+34.5\r\n+8.9\r\n"
                          "+10|14|15\r\n:11\r\n*3\r\n+12.13\r\n+16.17\r\n+18.19\r\n";

    auto pred = [] (std::shared_ptr<ConsumerMock> cons) {

        BOOST_REQUIRE_EQUAL(cons->param_.size(), 5);
        // 0
        BOOST_REQUIRE_EQUAL(cons->param_[0], 1);
        BOOST_REQUIRE_EQUAL(cons->ts_[0], 2);
        BOOST_REQUIRE_CLOSE_FRACTION(cons->data_[0], 34.5, 1e-9);
        // 1
        BOOST_REQUIRE_EQUAL(cons->param_[1], 6);
        BOOST_REQUIRE_EQUAL(cons->ts_[1], 2);
        BOOST_REQUIRE_CLOSE_FRACTION(cons->data_[1], 8.9, 1e-9);
        // 2
        BOOST_REQUIRE_EQUAL(cons->param_[2], 10);
        BOOST_REQUIRE_EQUAL(cons->ts_[2], 11);
        BOOST_REQUIRE_CLOSE_FRACTION(cons->data_[2], 12.13, 1e-9);
        // 3
        BOOST_REQUIRE_EQUAL(cons->param_[3], 14);
        BOOST_REQUIRE_EQUAL(cons->ts_[3], 11);
        BOOST_REQUIRE_CLOSE_FRACTION(cons->data_[3], 16.17, 1e-9);
        // 4
        BOOST_REQUIRE_EQUAL(cons->param_[4], 15);
        BOOST_REQUIRE_EQUAL(cons->ts_[4], 11);
        BOOST_REQUIRE_CLOSE_FRACTION(cons->data_[4], 18.19, 1e-9);
    };

    size_t msglen = strlen(message);

    for (int i = 0; i < 100; i++) {
        size_t pivot1 = 1 + static_cast<size_t>(rand()) % (msglen / 2);
        size_t pivot2 = 1+ static_cast<size_t>(rand()) % (msglen - pivot1 - 2) + pivot1;
        std::shared_ptr<ConsumerMock> cons(new ConsumerMock);
        find_framing_issues<RESPProtocolParser>(message, msglen, pivot1, pivot2, pred, cons);
    }
}

BOOST_AUTO_TEST_CASE(Test_protocol_parser_framing_dict) {

    const char *message =
            // Dictionary
            "*2\r\n+111\r\n:1\r\n"
            "*2\r\n+222\r\n:2\r\n"
            // The actual messages
            ":1\r\n:42\r\n+200\r\n"
            ":2\r\n:53\r\n+300\r\n"
            ":1\r\n:43\r\n+201\r\n"
            ":2\r\n:54\r\n+301\r\n"
            ;

    auto pred = [] (std::shared_ptr<ConsumerMock> cons) {

        BOOST_REQUIRE_EQUAL(cons->param_.size(), 4);
        // 0
        BOOST_REQUIRE_EQUAL(cons->param_[0], 111);
        BOOST_REQUIRE_EQUAL(cons->ts_[0], 42);
        BOOST_REQUIRE_CLOSE_FRACTION(cons->data_[0], 200, 1e-9);
        // 1
        BOOST_REQUIRE_EQUAL(cons->param_[1], 222);
        BOOST_REQUIRE_EQUAL(cons->ts_[1], 53);
        BOOST_REQUIRE_CLOSE_FRACTION(cons->data_[1], 300, 1e-9);
        // 2
        BOOST_REQUIRE_EQUAL(cons->param_[2], 111);
        BOOST_REQUIRE_EQUAL(cons->ts_[2], 43);
        BOOST_REQUIRE_CLOSE_FRACTION(cons->data_[2], 201, 1e-9);
        // 3
        BOOST_REQUIRE_EQUAL(cons->param_[3], 222);
        BOOST_REQUIRE_EQUAL(cons->ts_[3], 54);
        BOOST_REQUIRE_CLOSE_FRACTION(cons->data_[3], 301, 1e-9);
    };

    size_t msglen = strlen(message);

    for (int i = 0; i < 100; i++) {
        size_t pivot1 = 1 + static_cast<size_t>(rand()) % (msglen / 2);
        size_t pivot2 = 1+ static_cast<size_t>(rand()) % (msglen - pivot1 - 2) + pivot1;
        std::shared_ptr<ConsumerMock> cons(new ConsumerMock);
        find_framing_issues<RESPProtocolParser>(message, msglen, pivot1, pivot2, pred, cons);
    }
}

struct NameCheckingConsumer : DbSession {
    enum { ID = 101 };

    int called_;
    int num_calls_expected_;

    std::map<u64, std::string> series;
    std::map<std::string, u64> index;
    std::vector<aku_ParamId>   ids;
    std::vector<aku_Timestamp> ts;
    std::vector<double>        xs;

    NameCheckingConsumer(std::string expected, int ncalls_expected)
        : called_(0)
        , num_calls_expected_(ncalls_expected)
    {
        series[ID] = expected;
        index[expected] = ID;
    }

    NameCheckingConsumer(std::vector<std::string> expected, int ncalls_expected)
        : called_(0)
        , num_calls_expected_(ncalls_expected)
    {
        aku_ParamId id = ID;
        for (const auto& name: expected) {
            series[id] = name;
            index[name] = id;
            id++;
        }
    }

    virtual ~NameCheckingConsumer() {
        if (num_calls_expected_ >= 0 && called_ != num_calls_expected_) {
            BOOST_FAIL("Test wasn't called");
        }
    }

    virtual aku_Status write(const aku_Sample &sample) override {
        called_++;
        ids.push_back(sample.paramid);
        ts.push_back(sample.timestamp);
        xs.push_back(sample.payload.type == AKU_PAYLOAD_FLOAT ? sample.payload.float64 : static_cast<double>(INFINITY));
        return AKU_SUCCESS;
    }

    virtual std::shared_ptr<DbCursor> query(std::string) override {
        throw "Not implemented";
    }

    virtual std::shared_ptr<DbCursor> suggest(std::string) override {
        throw "Not implemented";
    }

    virtual std::shared_ptr<DbCursor> search(std::string) override {
        throw "Not implemented";
    }

    virtual int param_id_to_series(aku_ParamId id, char* buf, size_t sz) override {
        if (series.count(id)) {
            std::string expected = series[id];
            size_t bytes_copied = std::min(sz, expected.size());
            memcpy(buf, expected.data(), bytes_copied);
            return static_cast<int>(bytes_copied);
        }
        return 0;
    }

    virtual aku_Status series_to_param_id(const char* begin, size_t sz, aku_Sample* sample) override {
        std::string name(begin, begin + sz);
        if (index.count(name)) {
            sample->paramid = index[name];
            return AKU_SUCCESS;
        }
        BOOST_FAIL("Invalid series name");
        return AKU_SUCCESS;
    }

    virtual int name_to_param_id_list(const char* begin, const char* end, aku_ParamId* ids, u32) override {
        std::string name(begin, end);
        if (index.count(name)) {
            ids[0] = index[name];
            return 1;
        }
        return 0;
    }
};

void test_series_name_parsing(const char* messages, const char* expected_tags, int n) {
    std::shared_ptr<NameCheckingConsumer> cons(new NameCheckingConsumer(expected_tags, n));
    RESPProtocolParser parser(cons);
    parser.start();
    auto buf = parser.get_next_buffer();
    size_t buflen = strlen(messages);
    memcpy(buf, messages, buflen);
    parser.parse_next(buf, buflen);
}

BOOST_AUTO_TEST_CASE(Test_protocol_parse_series_name_error_with_carriage_return) {
    const char *messages = "+test tag1=value1 tag2=value2\r\n:2000\n+34.5\r\n+test tag1=value1 tag2=value2\r\n:3000\r\n+8.9\r\n";
    test_series_name_parsing(messages, "test tag1=value1 tag2=value2", 2);
}

BOOST_AUTO_TEST_CASE(Test_protocol_parse_series_name_error_no_carriage_return) {
    const char *messages = "+test tag1=value1 tag2=value2\n:2000\n+34.5\n+test tag1=value1 tag2=value2\n:3000\n+8.9\n";
    test_series_name_parsing(messages, "test tag1=value1 tag2=value2", 2);
}

BOOST_AUTO_TEST_CASE(Test_protocol_parse_series_name_error_no_carriage_return_2) {
    const char *messages = "+trialrank2 tag1=hello tag2=check\n:1418224205000000000\n:31\n";
    test_series_name_parsing(messages, "trialrank2 tag1=hello tag2=check", 1);
}

//                                    //
//   OpenTSDB protocol parser tests   //
//                                    //

static const u64 NANOSECONDS = 1000000000;

BOOST_AUTO_TEST_CASE(Test_opentsdb_protocol_parse_1) {
    std::string messages = "put test 2 12.3 tag1=value1 tag2=value2\n";
    std::string expected_tag = "test tag1=value1 tag2=value2";
    std::shared_ptr<NameCheckingConsumer> cons(new NameCheckingConsumer(expected_tag, 1));
    OpenTSDBProtocolParser parser(cons);
    auto buf = parser.get_next_buffer();
    memcpy(buf, messages.data(), messages.size());
    parser.start();
    parser.parse_next(buf, static_cast<u32>(messages.size()));
    parser.close();

    BOOST_REQUIRE_EQUAL(cons->ids.size(), 1);
    BOOST_REQUIRE_EQUAL(cons->ids.at(0), cons->index[expected_tag]);
    BOOST_REQUIRE_EQUAL(cons->ts.at(0),  2*NANOSECONDS);
    BOOST_REQUIRE_EQUAL(cons->xs.at(0), 12.3);
}

BOOST_AUTO_TEST_CASE(Test_opentsdb_protocol_parse_2) {
    std::string messages =
        "put test 2 34.5 tag=1\n"
        "put test 7 89.0 tag=2\n"
        "put  test 10 11.1 tag=3\n"
        "put test  13 14.5 tag=4\n"
        "put test 16  17.1 tag=5\n"
        "put test 19 20.2  tag=6\n"
        "put test 22 23.2 tag=7 \n";
    std::vector<std::string> expected_names = {
        "test tag=1", "test tag=2",
        "test tag=3", "test  tag=4",  // for actual series parser "test  tag=4" and "test tag=4" is the same
        "test tag=5", "test tag=6",
        "test tag=7"
    };
    std::vector<aku_Timestamp> expected_ts = {
        2, 7, 10, 13, 16, 19, 22
    };
    std::vector<double> expected_values = {
        34.5, 89.0, 11.1, 14.5, 17.1, 20.2, 23.2
    };
    std::shared_ptr<NameCheckingConsumer> cons(new NameCheckingConsumer(expected_names, -1));
    OpenTSDBProtocolParser parser(cons);
    auto buf = parser.get_next_buffer();
    memcpy(buf, messages.data(), messages.size());
    parser.start();
    parser.parse_next(buf, static_cast<u32>(messages.size()));
    parser.close();

    BOOST_REQUIRE_EQUAL(cons->ids.size(), 7);
    for (int i = 0; i < 7; i++) {
        BOOST_REQUIRE_EQUAL(cons->ids.at(i),  cons->index[expected_names[i]]);
        BOOST_REQUIRE_EQUAL(cons->ts.at(i),  expected_ts.at(i)*NANOSECONDS);
        BOOST_REQUIRE_EQUAL(cons->xs.at(i), expected_values.at(i));
    }
}

BOOST_AUTO_TEST_CASE(Test_open_tsdb_protocol_parser_framing) {

    const char *message = "put test 10001 34.57 tag1=1 tag2=1\n"
                          "put test 10002 81.09 tag1=2 tag2=2\n"
                          "put test 10003 12.13 tag1=3 tag2=3\n"
                          "put test 10004 16.71 tag1=1 tag2=1\n";

    std::vector<std::string> expected = {
        "test tag1=1 tag2=1",
        "test tag1=2 tag2=2",
        "test tag1=3 tag2=3",
    };

    auto pred = [&] (std::shared_ptr<NameCheckingConsumer> cons) {

        BOOST_REQUIRE_EQUAL(cons->ids.size(), 4);
        // 0
        BOOST_REQUIRE_EQUAL(cons->ids[0], cons->index[expected.at(0)]);
        BOOST_REQUIRE_EQUAL(cons->ts[0], 10001*NANOSECONDS);
        BOOST_REQUIRE_CLOSE_FRACTION(cons->xs[0], 34.57, 1e-9);
        // 1
        BOOST_REQUIRE_EQUAL(cons->ids[1], cons->index[expected.at(1)]);
        BOOST_REQUIRE_EQUAL(cons->ts[1], 10002*NANOSECONDS);
        BOOST_REQUIRE_CLOSE_FRACTION(cons->xs[1], 81.09, 1e-9);
        // 2
        BOOST_REQUIRE_EQUAL(cons->ids[2], cons->index[expected.at(2)]);
        BOOST_REQUIRE_EQUAL(cons->ts[2], 10003*NANOSECONDS);
        BOOST_REQUIRE_CLOSE_FRACTION(cons->xs[2], 12.13, 1e-9);
        // 3
        BOOST_REQUIRE_EQUAL(cons->ids[3], cons->index[expected.at(0)]);
        BOOST_REQUIRE_EQUAL(cons->ts[3], 10004*NANOSECONDS);
        BOOST_REQUIRE_CLOSE_FRACTION(cons->xs[3], 16.71, 1e-9);
    };

    size_t msglen = strlen(message);

    for (int i = 0; i < 100; i++) {
        size_t pivot1 = 1 + static_cast<size_t>(rand()) % (msglen / 2);
        size_t pivot2 = 1+ static_cast<size_t>(rand()) % (msglen - pivot1 - 2) + pivot1;
        std::shared_ptr<NameCheckingConsumer> cons = std::make_shared<NameCheckingConsumer>(expected, -1);
        find_framing_issues<OpenTSDBProtocolParser>(message, msglen, pivot1, pivot2, pred, cons);
    }
}

max_stars_repo_name: adulau/Akumuli

max_issues_repo_name: adulau/Akumuli

max_forks_repo_name: adulau/Akumuli


text:
/*!
 * mhwallet.
 * main.cpp
 *
 * \date 2019
 * \author Eduard Maximovich (edward.vstock@gmail.com)
 * \link   https://github.com/edwardstock
 */

#include "minter/ledger/nanos_wallet.h"

#include <boost/program_options.hpp>
#include <exception>
#include <functional>
#include <iostream>
#include <unordered_map>

namespace po = boost::program_options;

typedef int (*action_func_t)(const boost::program_options::variables_map&);
typedef void (*action_options_func_t)(boost::program_options::options_description&);

// get address
static void action_get_address_opts(boost::program_options::options_description& options) {
    // clang-format off
    options.add_options()
        ("index,i", po::value<uint32_t>()->default_value(0), "BIP32 derivation index")
        ("silent,s", "Don't show comparison text, just return address")
        ("inline", "Print result inline without newlines etc");
    // clang-format on
}
static int action_get_address(const boost::program_options::variables_map& options) {
    minter::nanos_wallet device;
    if (!device.init()) {
        return 1;
    }

    uint32_t derivationIndex = options.at("index").as<uint32_t>();
    bool printInline = options.count("inline");
    bool silent = options.count("silent");
    auto address = device.get_address(derivationIndex, silent);

    if (printInline) {
        std::cout << address.to_string();
        return 0;
    }

    std::cout << "Address: " << address.to_string() << "\n";
    return 0;
}

// version
static void action_app_version_opts(boost::program_options::options_description& options) {
    options.add_options()("inline", "Print result inline without newlines etc");
}
static int action_app_version(const boost::program_options::variables_map& options) {
    minter::nanos_wallet device;
    if (!device.init()) {
        return 1;
    }

    bool printInline = options.count("inline");

    auto vers = device.get_app_version();
    if (printInline) {
        std::cout << vers;
        return 0;
    }

    std::cout << "Version: " << vers << std::endl;
    return 0;
}

// sign
static void action_sign_tx_opts(boost::program_options::options_description& options) {
    options.add_options()("hash", po::value<std::string>()->required(), "Incomplete transaction sha3 hash (64 byte hex string)")("index,i", po::value<uint32_t>()->default_value(0), "BIP32 derivation index")("inline", "Print result inline without newlines etc");
}
static int action_sign_tx(const boost::program_options::variables_map& options) {
    //    std::string txHash = "067ea2037c3f14e7fb1affaec93940bc5af500144f13274e131c9ae78cbbd4e1"; // this has recovery 0x1c
    //    std::string txHash = "1ee24f115b579f0f1ba7278515f8c438c2da201dc37fa44c2d9f431d94a9693e"; // this has recovery 0x1b
    //    std::string txHash = "18b91c804a8aba5e5d1f4acd83b60b74925afda8ce06b26e03575ad2f89f4bef"; // this has overflow in R component and leading zero
    minter::nanos_wallet device;
    if (!device.init()) {
        return 1;
    }

    tb::bytes_data txHash = options.at("hash").as<std::string>();
    uint32_t derivationIndex = options.at("index").as<uint32_t>();
    bool printInline = options.count("inline");

    auto address = device.get_address(0, true);
    auto sign = device.sign_tx(txHash, derivationIndex);

    tb::bytes_data outInline(65);
    outInline.write(0, sign.r);
    outInline.write(32, sign.s);
    outInline.write(64, sign.v);

    if (printInline) {
        std::cout << outInline.to_hex();
        return 0;
    }
    std::cout << "Signature result:\n";
    std::cout << "R:   " << minter::dumpHexRet(sign.r) << "\n";
    std::cout << "S:   " << minter::dumpHexRet(sign.s) << "\n";
    std::cout << "V:   " << minter::dumpHexRet(sign.v) << "\n\n";
    std::cout << "RSV: " << outInline.to_hex() << std::endl;

    return 0;
}

const static std::unordered_map<std::string, action_func_t> action_map = {
    {"get-address", &action_get_address},
    {"sign-tx", &action_sign_tx},
    {"app-version", &action_app_version},
};

const static std::unordered_map<std::string, action_options_func_t> opts_map = {
    {"get-address", &action_get_address_opts},
    {"sign-tx", &action_sign_tx_opts},
    {"app-version", &action_app_version_opts},
};

int main(int argc, char** argv) {
    std::string actions_desc = R"(Minter Ledger Wallet CLI

Usage:
 Command list:
   get-address - Resolve minter address from device

   sign-tx     - Sign passed transaction hash (must contains exact 64 byte hex string)

   app-version - Return Minter ledger application version

Options)";

    po::options_description desc(actions_desc);
    desc.add_options()("help,h", "Prints this help or use it with command name to see additional parameters")("version,v", "print version of client")("verbose", "print data transfer process");

    po::variables_map vm;

    auto handleArgs = [&vm, &argc, &argv, &desc] {
        po::store(po::parse_command_line(argc, argv, desc), vm);
        if (vm.count("help")) {
            std::cout << desc << "\n";
            return true;
        }

        HIDPP_VERBOSE = true;

        try {
            po::notify(vm);
        } catch (const std::exception& e) {
            std::cerr << "Error:\n  ";
            std::cerr << e.what() << "\n"
                      << std::endl;
            std::cout << desc << std::endl;
            return false;
        }

        return true;
    };

    if (argc == 1) {
        const auto ret = handleArgs();
        std::cout << desc << std::endl;
        return ret ? 0 : 1;
    }

    if (argc >= 2) {
        std::string cmdName = argv[1];

        if (!action_map.count(cmdName)) {
            std::cerr << "Unknown command: " << cmdName << "\n\n";
            std::cout << desc << std::endl;
            return 1;
        }

        opts_map.at(cmdName)(desc);
        if (!handleArgs()) {
            return 1;
        }
        if (vm.count("help")) {
            std::cout << desc << "\n";
            return 0;
        }

        try {
            return action_map.at(cmdName)(vm);
        } catch (const std::exception& e) {
            ML_ERR(e.what());
            return 1;
        }
    }

    if (vm.count("help")) {
        std::cout << desc << "\n";
        return 0;
    }

    return 0;
}

ext: cpp

max_stars_repo_name: MinterTeam/mhwallet

max_issues_repo_name: MinterTeam/mhwallet

max_forks_repo_name: MinterTeam/mhwallet


text:
#include <iostream>

#include <boost/logic/tribool.hpp>
#include <boost/logic/tribool_io.hpp>

int main()
{
    using namespace boost::logic;

    std::cout.setf(std::ios::boolalpha);

    boost::logic::tribool b1 = true;
    std::cout << (b1 || indeterminate) << '\n';
    std::cout << (b1 && indeterminate) << '\n';

    boost::logic::tribool b2 = false;
    std::cout << (b2 || indeterminate) << '\n';
    std::cout << (b2 && indeterminate) << '\n';

    boost::logic::tribool b3 = boost::logic::indeterminate;
    std::cout << (b3 || b3) << '\n';
    std::cout << (b3 && b3) << '\n';
}

max_stars_repo_name: cvlabmiet/master-programming

max_issues_repo_name: cvlabmiet/master-programming

max_forks_repo_name: cvlabmiet/master-programming


text:
//==============================================================================
//         Copyright 2003 - 2012   LASMEA UMR 6602 CNRS/Univ. Clermont II
//         Copyright 2009 - 2012   LRI    UMR 8623 CNRS/Univ Paris Sud XI
//
//          Distributed under the Boost Software License, Version 1.0.
//                 See accompanying file LICENSE.txt or copy at
//                     http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
#ifndef NT2_TOOLBOX_LINALG_DETAILS_UTILITY_F77_WRAPPER_HPP_INCLUDED
#define NT2_TOOLBOX_LINALG_DETAILS_UTILITY_F77_WRAPPER_HPP_INCLUDED

#include <boost/preprocessor/cat.hpp>

// INTERNAL ONLY
// This macro can be ifdef'ed to produce the correct symbol output for the
// FORTRAN library in use, adding or not the underscore to FORTRAN routine names
// By default we generate Name_
#ifndef NT2_F77NAME
#define NT2_F77NAME(NAME) BOOST_PP_CAT(NAME,_)
#endif

// INTERNAL ONLY
// This macro can be ifdef'ed to produce the correct symbol output for the
// FORTRAN library in use, setting the proper type to use integer type for
// BLAS/LAPACK
#ifndef NT2_F77INT
#define NT2_F77INT nt2::int32_t
#endif

// INTERNAL ONLY
// This macro can be ifdef'ed to produce the correct symbol output for the
// FORTRAN library in use, setting the proper type to use complex type for
// BLAS/LAPACK
#ifndef NT2_F77COMPLEX
#define NT2_F77COMPLEX void
#endif

// INTERNAL ONLY
// Type of long int required by BLAS/LAPACK
typedef NT2_F77INT      nt2_la_int;

// INTERNAL ONLY
// Type used by BLAS/LAPACK to pass array of complex
typedef NT2_F77COMPLEX  nt2_la_complex;

// INTERNAL ONLY
// Type used by BLAS/LAPACK to pass select elements
namespace nt2 { namespace details
{
  inline nt2_la_int selectall(void* ) { return true; }
  inline nt2_la_int selectall2( const void*, const  void* ) { return true; }
  typedef nt2_la_int selectall_t(void*) ;
  typedef nt2_la_int selectall2_t(const void*, const void*);
} }

#endif

ext: hpp


text:
////////////////////////////////////////////////////////////////////////////////
/// @brief test suite for PathEnumerator class
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2004-2012 triagens GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
///     http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is triAGENS GmbH, Cologne, Germany
///
/// @author Michael Hackstein
/// @author Copyright 2015, ArangoDB GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////

#include "Basics/Common.h"

#define BOOST_TEST_INCLUDED
#include <boost/test/unit_test.hpp>

#include "Basics/AttributeNameParser.h"
#include "Basics/Exceptions.h"

using namespace arangodb;
using namespace arangodb::basics;

// -----------------------------------------------------------------------------
// --SECTION--                                                 setup / tear-down
// -----------------------------------------------------------------------------

struct AttributeNameParserSetup {
  AttributeNameParserSetup () {
    BOOST_TEST_MESSAGE("setup AttributeNameParser");
  }

  ~AttributeNameParserSetup () {
    BOOST_TEST_MESSAGE("tear-down AttributeNameParser");
  }
};

// -----------------------------------------------------------------------------
// --SECTION--                                                        test suite
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @brief setup
////////////////////////////////////////////////////////////////////////////////

BOOST_FIXTURE_TEST_SUITE (AttributeNameParserTest, AttributeNameParserSetup)

////////////////////////////////////////////////////////////////////////////////
/// @brief test_simpleString
////////////////////////////////////////////////////////////////////////////////

BOOST_AUTO_TEST_CASE (test_simpleString) {
  std::string input = "test";
  std::vector<AttributeName> result;

  TRI_ParseAttributeString(input, result);

  BOOST_CHECK_EQUAL(result.size(), static_cast<size_t>(1));
  BOOST_CHECK_EQUAL(result[0].name, input);
  BOOST_CHECK_EQUAL(result[0].shouldExpand, false);
}

////////////////////////////////////////////////////////////////////////////////
/// @brief test_subAttribute
////////////////////////////////////////////////////////////////////////////////

BOOST_AUTO_TEST_CASE (test_subAttribute) {
  std::string input = "foo.bar";
  std::vector<AttributeName> result;

  TRI_ParseAttributeString(input, result);

  BOOST_CHECK_EQUAL(result.size(), static_cast<size_t>(2));
  BOOST_CHECK_EQUAL(result[0].name, "foo");
  BOOST_CHECK_EQUAL(result[0].shouldExpand, false);
  BOOST_CHECK_EQUAL(result[1].name, "bar");
  BOOST_CHECK_EQUAL(result[1].shouldExpand, false);
}

////////////////////////////////////////////////////////////////////////////////
/// @brief test_subsubAttribute
////////////////////////////////////////////////////////////////////////////////

BOOST_AUTO_TEST_CASE (test_subsubAttribute) {
  std::string input = "foo.bar.baz";
  std::vector<AttributeName> result;

  TRI_ParseAttributeString(input, result);

  BOOST_CHECK_EQUAL(result.size(), static_cast<size_t>(3));
  BOOST_CHECK_EQUAL(result[0].name, "foo");
  BOOST_CHECK_EQUAL(result[0].shouldExpand, false);
  BOOST_CHECK_EQUAL(result[1].name, "bar");
  BOOST_CHECK_EQUAL(result[1].shouldExpand, false);
  BOOST_CHECK_EQUAL(result[2].name, "baz");
  BOOST_CHECK_EQUAL(result[2].shouldExpand, false);
}

////////////////////////////////////////////////////////////////////////////////
/// @brief test_expandAttribute
////////////////////////////////////////////////////////////////////////////////

BOOST_AUTO_TEST_CASE (test_expandAttribute) {
  std::string input = "foo[*]";
  std::vector<AttributeName> result;

  TRI_ParseAttributeString(input, result);

  BOOST_CHECK_EQUAL(result.size(), static_cast<size_t>(1));
  BOOST_CHECK_EQUAL(result[0].name, "foo");
  BOOST_CHECK_EQUAL(result[0].shouldExpand, true);
}

////////////////////////////////////////////////////////////////////////////////
/// @brief test_expandSubAttribute
////////////////////////////////////////////////////////////////////////////////

BOOST_AUTO_TEST_CASE (test_expandSubAttribute) {
  std::string input = "foo.bar[*]";
  std::vector<AttributeName> result;

  TRI_ParseAttributeString(input, result);

  BOOST_CHECK_EQUAL(result.size(), static_cast<size_t>(2));
  BOOST_CHECK_EQUAL(result[0].name, "foo");
  BOOST_CHECK_EQUAL(result[0].shouldExpand, false);
  BOOST_CHECK_EQUAL(result[1].name, "bar");
  BOOST_CHECK_EQUAL(result[1].shouldExpand, true);
}

////////////////////////////////////////////////////////////////////////////////
/// @brief test_expandedSubAttribute
////////////////////////////////////////////////////////////////////////////////

BOOST_AUTO_TEST_CASE (test_expandedSubAttribute) {
  std::string input = "foo[*].bar";
  std::vector<AttributeName> result;

  TRI_ParseAttributeString(input, result);

  BOOST_CHECK_EQUAL(result.size(), static_cast<size_t>(2));
  BOOST_CHECK_EQUAL(result[0].name, "foo");
  BOOST_CHECK_EQUAL(result[0].shouldExpand, true);
  BOOST_CHECK_EQUAL(result[1].name, "bar");
  BOOST_CHECK_EQUAL(result[1].shouldExpand, false);
}

////////////////////////////////////////////////////////////////////////////////
/// @brief test_invalidAttributeAfterExpand
////////////////////////////////////////////////////////////////////////////////

BOOST_AUTO_TEST_CASE (test_invalidAttributeAfterExpand) {
  std::string input = "foo[*]bar";
  std::vector<AttributeName> result;

  try {
    TRI_ParseAttributeString(input, result);
    BOOST_FAIL("Expected the function to throw");
  } catch (Exception& e) {
    BOOST_CHECK_EQUAL(e.code(), TRI_ERROR_ARANGO_ATTRIBUTE_PARSER_FAILED);
  }
}

////////////////////////////////////////////////////////////////////////////////
/// @brief test_nonClosing[
////////////////////////////////////////////////////////////////////////////////

BOOST_AUTO_TEST_CASE (test_nonClosingBracket) {
  std::string input = "foo[*bar";
  std::vector<AttributeName> result;

  try {
    TRI_ParseAttributeString(input, result);
    BOOST_FAIL("Expected the function to throw");
  } catch (Exception& e) {
    BOOST_CHECK_EQUAL(e.code(), TRI_ERROR_ARANGO_ATTRIBUTE_PARSER_FAILED);
  }
}

////////////////////////////////////////////////////////////////////////////////
/// @brief test_nonClosing[2
////////////////////////////////////////////////////////////////////////////////

BOOST_AUTO_TEST_CASE (test_nonClosingBracket2) {
  std::string input = "foo[ * ].baz";
  std::vector<AttributeName> result;

  try {
    TRI_ParseAttributeString(input, result);
    BOOST_FAIL("Expected the function to throw");
  } catch (Exception& e) {
    BOOST_CHECK_EQUAL(e.code(), TRI_ERROR_ARANGO_ATTRIBUTE_PARSER_FAILED);
  }
}

////////////////////////////////////////////////////////////////////////////////
/// @brief test_nonAsterisk
////////////////////////////////////////////////////////////////////////////////

BOOST_AUTO_TEST_CASE (test_nonAsterisk) {
  std::string input = "foo[0]";
  std::vector<AttributeName> result;

  try {
    TRI_ParseAttributeString(input, result);
    BOOST_FAIL("Expected the function to throw");
  } catch (Exception& e) {
    BOOST_CHECK_EQUAL(e.code(), TRI_ERROR_ARANGO_ATTRIBUTE_PARSER_FAILED);
  }
}

////////////////////////////////////////////////////////////////////////////////
/// @brief test_nonAsterisk
////////////////////////////////////////////////////////////////////////////////

BOOST_AUTO_TEST_CASE (test_nonAsterisk2) {
  std::string input = "foo[0].value";
  std::vector<AttributeName> result;

  try {
    TRI_ParseAttributeString(input, result);
    BOOST_FAIL("Expected the function to throw");
  } catch (Exception& e) {
    BOOST_CHECK_EQUAL(e.code(), TRI_ERROR_ARANGO_ATTRIBUTE_PARSER_FAILED);
  }
}

////////////////////////////////////////////////////////////////////////////////
/// @brief test_reverseTransform
////////////////////////////////////////////////////////////////////////////////

BOOST_AUTO_TEST_CASE (test_reverseTransform) {
  std::string input = "foo[*].bar.baz[*]";
  std::vector<AttributeName> result;
  TRI_ParseAttributeString(input, result);

  std::string output = "";
  TRI_AttributeNamesToString(result, output);
  BOOST_CHECK_EQUAL(output, input);
}

////////////////////////////////////////////////////////////////////////////////
/// @brief test_reverseTransformSimple
////////////////////////////////////////////////////////////////////////////////

BOOST_AUTO_TEST_CASE (test_reverseTransformSimple) {
  std::string input = "i";
  std::vector<AttributeName> result;
  TRI_ParseAttributeString(input, result);

  std::string output = "";
  TRI_AttributeNamesToString(result, output);
  BOOST_CHECK_EQUAL(output, input);
}

////////////////////////////////////////////////////////////////////////////////
/// @brief test_reverseTransformSimpleMultiAttributes
////////////////////////////////////////////////////////////////////////////////

BOOST_AUTO_TEST_CASE (test_reverseTransformSimpleMultiAttributes) {
  std::string input = "a.j";
  std::vector<AttributeName> result;
  TRI_ParseAttributeString(input, result);

  std::string output = "";
  TRI_AttributeNamesToString(result, output);
  BOOST_CHECK_EQUAL(output, input);
}
////////////////////////////////////////////////////////////////////////////////
/// @brief test_reverseTransformToPidPath
////////////////////////////////////////////////////////////////////////////////

BOOST_AUTO_TEST_CASE (test_reverseTransformToPidPath) {
  std::string input = "foo[*].bar.baz[*]";
  std::string expected = "foo.bar.baz";
  std::vector<AttributeName> result;
  TRI_ParseAttributeString(input, result);

  std::string output = "";
  TRI_AttributeNamesToString(result, output, true);
  BOOST_CHECK_EQUAL(output, expected);
}

////////////////////////////////////////////////////////////////////////////////
/// @brief generate tests
////////////////////////////////////////////////////////////////////////////////

BOOST_AUTO_TEST_SUITE_END()

// Local Variables:
// mode: outline-minor
// outline-regexp: "^\\(/// @brief\\|/// {@inheritDoc}\\|/// @addtogroup\\|// --SECTION--\\|/// @\\}\\)"
// End:

max_stars_repo_name: mikestaub/arangodb

max_issues_repo_name: mikestaub/arangodb

max_forks_repo_name: mikestaub/arangodb


text:
// Copyright (c) 2019 Graphcore Ltd. All rights reserved.
#define BOOST_TEST_MODULE ConstExprAddTest

#include <boost/test/unit_test.hpp>
#include <filereader.hpp>
#include <popart/builder.hpp>
#include <popart/dataflow.hpp>
#include <popart/devicemanager.hpp>
#include <popart/half.hpp>
#include <popart/inputshapeinfo.hpp>
#include <popart/ir.hpp>
#include <popart/names.hpp>
#include <popart/ndarraywrapper.hpp>
#include <popart/op/identity.hpp>
#include <popart/op/l1.hpp>
#include <popart/session.hpp>
#include <popart/sgd.hpp>
#include <popart/tensor.hpp>
#include <popart/tensordata.hpp>
#include <popart/tensors.hpp>
#include <popart/testdevice.hpp>

#include <math.h>

using namespace popart;

BOOST_AUTO_TEST_CASE(ConstExprTest_Add0) {

  // The compute graph :
  //
  // data  -----------------------------|
  //                                    |
  //                                    |
  //                                    |- RESHAPE ---> output
  //                                    |
  // shape0 -------|                    |
  //               |                    |
  //               |- ADD - outshape ---|
  //               |
  // shape1 -------|

  // We will reshape a tensor from rank-4:
  Shape inShape = {2, 5, 3, 4};
  // to rank-2: {10, 12},
  // Note above that the total number elements of the tensor remains 120

  // where the output shape {10, 12} will be the sum of two tensors,
  // 1)
  Shape shape0 = {7, 4};
  // 2)
  Shape shape1 = {3, 8};

  Shape outShapeSize = {static_cast<int64_t>(shape0.size())};
  TensorInfo inInfo{"FLOAT", inShape};

  ConstVoidData out0ShapeData = {shape0.data(), {"INT64", outShapeSize}};
  ConstVoidData out1ShapeData = {shape1.data(), {"INT64", outShapeSize}};

  // Build an onnx model
  auto builder = Builder::create();
  auto aiOnnx  = builder->aiOnnxOpset9();
  // The two fixed-point tensors which are Constants
  auto shape0Id   = aiOnnx.constant(out0ShapeData, "out0ShapeData");
  auto shape1Id   = aiOnnx.constant(out1ShapeData, "out1ShapeData");
  auto inId       = builder->addInputTensor(inInfo);
  auto outShapeId = aiOnnx.add({shape0Id, shape1Id});
  auto outId      = aiOnnx.reshape({inId, outShapeId});
  auto l1         = builder->aiGraphcoreOpset1().l1loss({outId}, 0.1);

  auto proto      = builder->getModelProto();
  auto modelProto = io::getModelFromString(proto);

  // Create the IR, adding outId as an anchor
  auto art       = AnchorReturnType("All");
  auto dataFlow  = DataFlow(1, {{outId, art}});
  auto optimizer = ConstSGD(0.01);
  auto device    = createTestDevice(TEST_TARGET);

  Ir ir;
  ir.prepare({modelProto,
              InputShapeInfo(),
              dataFlow,
              l1,
              &optimizer,
              *device,
              {}, // no SessionOptions
              Patterns::create({"PostNRepl"}).enableRuntimeAsserts(false)});

  // Check the ir
  // 1) that the Reshape Op is present,
  BOOST_CHECK(ir.opsOfType(Onnx::AiOnnx::OpSet9::Reshape).size() == 1);
  // 2) that the shape of the output tensor is as specified.
  Shape outShape;
  for (int i = 0; i < outShapeSize[0]; ++i) {
    outShape.push_back(shape0[i] + shape1[i]);
  }
  BOOST_CHECK(ir.getMainGraphTensors().get(outId)->info.shape() == outShape);
}

BOOST_AUTO_TEST_CASE(ConstExprTest_Add1) {
  // Testing ConstExpr folding on broadcast adds of
  // initializers and constants

  // The compute graph :
  //
  // w0 --|
  //      |--[bc-add]-- a0 --|
  // w1 --|                  |
  //                         |--[bc-add]-- a2 -|
  // c0 --|                  |                 |
  //      |--[bc-add]-- a1 --|                 |-- [matmul] -- o
  // c1 --|                                    |
  //                                           |
  // i1 ---------------------------------------|
  //

  // weights
  TensorInfo w0Shape{"FLOAT", std::vector<int64_t>{1, 3}};
  float w0Vals[1 * 3]  = {0};
  ConstVoidData w0Data = {w0Vals, w0Shape};

  TensorInfo w1Shape{"FLOAT", std::vector<int64_t>{3, 3}};
  float w1Vals[3 * 3]  = {1};
  ConstVoidData w1Data = {w1Vals, w1Shape};

  // consts
  TensorInfo c0Shape{"FLOAT", std::vector<int64_t>{1, 3}};
  float c0Vals[1 * 3]  = {2};
  ConstVoidData c0Data = {c0Vals, c0Shape};

  TensorInfo c1Shape{"FLOAT", std::vector<int64_t>{1}};
  float c1Vals[1]      = {3};
  ConstVoidData c1Data = {c1Vals, c1Shape};

  // input
  TensorInfo inputInfo{"FLOAT", std::vector<int64_t>{3, 4}};

  // Build an onnx model
  auto builder = Builder::create();
  auto aiOnnx  = builder->aiOnnxOpset9();

  auto w0Id = builder->addInitializedInputTensor(w0Data);
  auto w1Id = builder->addInitializedInputTensor(w1Data);
  auto a0   = aiOnnx.add({w0Id, w1Id}, "a0");

  auto c0Id = aiOnnx.constant(c0Data, "c0Data");
  auto c1Id = aiOnnx.constant(c1Data, "c1Data");
  auto a1   = aiOnnx.add({c0Id, c1Id}, "a1");

  auto a2      = aiOnnx.add({a0, a1}, "a2");
  auto inputId = builder->addInputTensor(inputInfo);
  auto outId   = aiOnnx.matmul({a2, inputId});
  auto l1      = builder->aiGraphcoreOpset1().l1loss({outId}, 0.1);

  auto proto      = builder->getModelProto();
  auto modelProto = io::getModelFromString(proto);

  // Create the IR, adding outId as an anchor
  auto art       = AnchorReturnType("All");
  auto dataFlow  = DataFlow(1, {{outId, art}});
  auto optimizer = ConstSGD(0.01);
  auto device    = createTestDevice(TEST_TARGET);

  Ir ir;
  ir.prepare({modelProto,
              InputShapeInfo(),
              dataFlow,
              {}, // no loss
              {}, // no optimizer
              *device,
              {}, // no SessionOptions
              Patterns::create({"PostNRepl"}).enableRuntimeAsserts(false)});

  // Check that the Add Op is has been removed from the IR
  // by ConstExpr folding
  // TODO: this test will give a false pass if the model is using
  // a newer opset. Fix when T6274 is complete
  BOOST_CHECK(ir.opsOfType(Onnx::AiOnnx::OpSet9::Add).size() == 0);
}

BOOST_AUTO_TEST_CASE(ConstExprTest_Add2) {
  // Testing ConstExpr folding on an input tensor whose consumer
  // has another input that cannot be removed by ConstExpr folding

  // Model from the builder:
  //
  // v0 ----|
  //        |--[add]-- a0 --|
  //        |               |
  // c0 --|-|               |--[add]-- o
  //      |                 |
  //      |--[add]---- a1 --|
  // c1 --|
  //
  // Expected outcome after ConstExpr folding :
  //
  // v0 ---|
  //       |--[add]-- a0 --|
  // c0 ---|               |--[add]-- o
  //                       |
  // a1 -------------------|
  //

  // consts
  TensorInfo c0Shape{"FLOAT", std::vector<int64_t>{2, 2}};
  float c0Vals[2 * 2]  = {2};
  ConstVoidData c0Data = {c0Vals, c0Shape};

  TensorInfo c1Shape{"FLOAT", std::vector<int64_t>{2, 2}};
  float c1Vals[2 * 2]  = {3};
  ConstVoidData c1Data = {c1Vals, c1Shape};

  // input
  TensorInfo inputInfo{"FLOAT", std::vector<int64_t>{2, 2}};

  // Build an onnx model
  auto builder = Builder::create();
  auto aiOnnx  = builder->aiOnnxOpset9();

  auto v0Id = builder->addInputTensor(inputInfo);
  auto c0Id = aiOnnx.constant(c0Data, "c0Data");
  auto c1Id = aiOnnx.constant(c1Data, "c1Data");

  auto a0 = aiOnnx.add({v0Id, c0Id}, "a0");
  auto a1 = aiOnnx.add({c0Id, c1Id}, "a1");

  auto o = aiOnnx.add({a0, a1}, "o");
  builder->addOutputTensor(o);

  auto proto      = builder->getModelProto();
  auto modelProto = io::getModelFromString(proto);

  // Create the IR, adding outId as an anchor
  auto art      = AnchorReturnType("All");
  auto dataFlow = DataFlow(1, {{o, art}});
  auto device   = createTestDevice(TEST_TARGET);

  Ir ir;
  ir.prepare({modelProto,
              InputShapeInfo(),
              dataFlow,
              {}, // no loss
              {}, // no optimizer
              *device,
              {}, // no SessionOptions
              Patterns::create({"PostNRepl"}).enableRuntimeAsserts(false)});

  // Check that the producer of a1 Add Op is has been removed from the IR
  // by ConstExpr folding
  BOOST_CHECK(ir.opsOfType(Onnx::AiOnnx::OpSet9::Add).size() == 2);
}

template <typename T> void ConstExprTest_Add_Type(std::string type) {

  // The compute graph :
  //
  // data  -----------------------------|
  //                                    |
  //                                    |
  //                                    |- ADD ---> output
  //                                    |
  // shape0 -------|                    |
  //               |                    |
  //               |- ADD - outshape ---|
  //               |
  // shape1 -------|

  Shape inShape = {2, 2};

  T input1_raw[] = {(T)1.2f, 2, 3, 4};
  std::vector<T> input1(input1_raw, std::end(input1_raw));

  T input2_raw[] = {(T)1.7f, 2, 3, 4};
  std::vector<T> input2(input2_raw, std::end(input2_raw));

  Shape outShapeSize = {2, 2};
  TensorInfo inInfo{type, inShape};

  ConstVoidData out0ShapeData = {input1.data(), {type, outShapeSize}};
  ConstVoidData out1ShapeData = {input2.data(), {type, outShapeSize}};

  T output_raw[4];
  popart::NDArrayWrapper<T> output(output_raw, {2, 2});

  // Build an onnx model
  auto builder = Builder::create();
  auto aiOnnx  = builder->aiOnnxOpset9();
  // The two fixed-point tensors which are Constants
  auto shape0Id   = aiOnnx.constant(out0ShapeData, "out0ShapeData");
  auto shape1Id   = aiOnnx.constant(out1ShapeData, "out1ShapeData");
  auto inId       = builder->addInputTensor(inInfo);
  auto outShapeId = aiOnnx.add({shape0Id, shape1Id});
  auto outId      = aiOnnx.add({inId, outShapeId});
  builder->addOutputTensor(outId);

  std::map<popart::TensorId, popart::IArray &> anchors = {{outId, output}};

  auto proto = builder->getModelProto();

  auto art      = AnchorReturnType("All");
  auto dataFlow = DataFlow(1, {{outId, art}});

  auto device = popart::createTestDevice(TEST_TARGET);

  auto session = popart::InferenceSession::createFromOnnxModel(
      proto,
      dataFlow,
      device,
      InputShapeInfo(),
      {}, // no SessionOptions
      Patterns::create({"PostNRepl"}).enableRuntimeAsserts(false));

  T rawInputData[4] = {(T)1.1f, 2, 3, 4};
  popart::NDArrayWrapper<T> inData(rawInputData, {2, 2});
  std::map<popart::TensorId, popart::IArray &> inputs = {{inId, inData}};

  session->prepareDevice();
  popart::StepIO stepio(inputs, anchors);
  session->run(stepio);

  // Check the ir
  popart::logging::ir::err("input1 : {}", input1[0]);
  popart::logging::ir::err("input2 : {}", input2[0]);
  popart::logging::ir::err("indata : {}", inData[0]);
  popart::logging::ir::err("output : {}", output[0]);

  BOOST_CHECK((input1[0] + input2[0] + inData[0]) == output[0]);
}

BOOST_AUTO_TEST_CASE(ConstExprTest_Div0) {

  // The compute graph :
  //
  // data  -----------------------------|
  //                                    |
  //                                    |
  //                                    |- RESHAPE ---> output
  //                                    |
  // shape0 -------|                    |
  //               |                    |
  //               |- ADD - outshape ---|
  //               |
  // shape1 -------|

  // We will reshape a tensor from rank-4:
  Shape inShape = {2, 2, 2};
  // to rank-2: {2, 4},
  // Note above that the total number elements of the tensor remains 120

  // where the output shape {2, 4} will be the sum of two tensors,
  // 1)
  Shape shape0 = {4, 12};
  // 2)
  Shape shape1 = {2, 3};

  Shape outShapeSize = {static_cast<int64_t>(shape0.size())};
  TensorInfo inInfo{"FLOAT", inShape};

  ConstVoidData out0ShapeData = {shape0.data(), {"INT64", outShapeSize}};
  ConstVoidData out1ShapeData = {shape1.data(), {"INT64", outShapeSize}};

  // Build an onnx model
  auto builder = Builder::create();
  auto aiOnnx  = builder->aiOnnxOpset9();
  // The two fixed-point tensors which are Constants
  auto shape0Id   = aiOnnx.constant(out0ShapeData, "out0ShapeData");
  auto shape1Id   = aiOnnx.constant(out1ShapeData, "out1ShapeData");
  auto inId       = builder->addInputTensor(inInfo);
  auto outShapeId = aiOnnx.div({shape0Id, shape1Id});
  auto outId      = aiOnnx.reshape({inId, outShapeId});
  auto l1         = builder->aiGraphcoreOpset1().l1loss({outId}, 0.1);

  auto proto      = builder->getModelProto();
  auto modelProto = io::getModelFromString(proto);

  // Create the IR, adding outId as an anchor
  auto art       = AnchorReturnType("All");
  auto dataFlow  = DataFlow(1, {{outId, art}});
  auto optimizer = ConstSGD(0.01);
  auto device    = createTestDevice(TEST_TARGET);

  Ir ir;
  ir.prepare({modelProto,
              InputShapeInfo(),
              dataFlow,
              l1,
              &optimizer,
              *device,
              {}, // no SessionOptions
              Patterns::create({"PostNRepl"}).enableRuntimeAsserts(false)});

  // Check the ir
  // 1) that the Reshape Op is present,
  BOOST_CHECK(ir.opsOfType(Onnx::AiOnnx::OpSet9::Reshape).size() == 1);
  // 2) that the shape of the output tensor is as specified.
  Shape outShape;
  for (int i = 0; i < outShapeSize[0]; ++i) {
    outShape.push_back(shape0[i] / shape1[i]);
  }
  BOOST_CHECK(ir.getMainGraphTensors().get(outId)->info.shape() == outShape);
}

BOOST_AUTO_TEST_CASE(ConstExprTest_Add_Types) {
  // ConstExprTest_Add_Type<uint32_t>("UINT32");
  // ConstExprTest_Add_Type<uint64_t>("UINT64");
  ConstExprTest_Add_Type<int32_t>("INT32");
  // ConstExprTest_Add_Type<int64_t>("INT64");
  ConstExprTest_Add_Type<popart::float16_t>("FLOAT16");
  ConstExprTest_Add_Type<float>("FLOAT");
  // ConstExprTest_Add_Type("DOUBLE");
}

template <typename T> std::string getTypeString();

template <> std::string getTypeString<int64_t>() { return "INT64"; }
template <> std::string getTypeString<float16_t>() { return "FLOAT16"; }
template <> std::string getTypeString<float_t>() { return "FLOAT"; }

template <typename T>
void ConstExprTest_Elementwise_Test(
    std::vector<T> in0,
    std::vector<T> in1,
    std::vector<T> output,
    std::function<TensorId(std::unique_ptr<popart::Builder> &builder,
                           const std::vector<TensorId> &args)> elementWiseFn) {

  // The compute graph :
  //
  // data  -----------------------------|
  //                                    |
  //                                    |
  //                                    |- ADD ---> output
  //                                    |
  // shape0 -------|                    |
  //               |                    |
  //               |- OP - outshape ----|
  //               |
  // shape1 -------|

  std::vector<T> data = {42, 42};
  Shape dataShape     = {static_cast<int64_t>(data.size())};
  TensorInfo dataInfo{getTypeString<T>(), dataShape};

  Shape in0Shape        = {static_cast<int64_t>(in0.size())};
  ConstVoidData in0Data = {in0.data(), {getTypeString<T>(), in0Shape}};

  Shape in1Shape        = {static_cast<int64_t>(in1.size())};
  ConstVoidData in1Data = {in1.data(), {getTypeString<T>(), in1Shape}};

  // Build an onnx model
  auto builder = Builder::create();
  auto aiOnnx  = builder->aiOnnxOpset10();
  // The two fixed-point tensors which are Constants
  auto in0Id      = aiOnnx.constant(in0Data, "in0Data");
  auto in1Id      = aiOnnx.constant(in1Data, "in1Data");
  auto dataId     = builder->addInputTensor(dataInfo);
  auto outShapeId = elementWiseFn(builder, {in0Id, in1Id});

  auto outId = aiOnnx.add({dataId, outShapeId});
  auto l1    = builder->aiGraphcoreOpset1().l1loss({outId}, 0.1);

  auto proto      = builder->getModelProto();
  auto modelProto = io::getModelFromString(proto);

  // Create the IR, adding outId as an anchor
  auto art       = AnchorReturnType("All");
  auto dataFlow  = DataFlow(1, {{outId, art}});
  auto optimizer = ConstSGD(0.01);
  auto device    = createTestDevice(TEST_TARGET);

  Ir ir;
  ir.prepare({modelProto,
              InputShapeInfo(),
              dataFlow,
              l1,
              &optimizer,
              *device,
              {}, // no SessionOptions
              Patterns::create({"PostNRepl"}).enableRuntimeAsserts(false)});

  // Check the ir
  // 1) that the Add Op is present,
  BOOST_CHECK(ir.opsOfType(Onnx::AiOnnx::OpSet9::Add).size() == 1);
  // 2) that the value of the output tensor is as specified.
  T *p = static_cast<T *>(
      ir.getMainGraphTensors().get(outShapeId)->tensorData()->data());
  for (int i = 0; i < output.size(); ++i) {
    BOOST_CHECK(p[i] == output[i]);
  }
}

BOOST_AUTO_TEST_CASE(ConstExprTest_Elementwise) {
  ConstExprTest_Elementwise_Test<int64_t>(
      {4, 12},
      {2, 3},
      {2, 4},
      [](std::unique_ptr<popart::Builder> &builder,
         const std::vector<TensorId> &args) -> TensorId {
        return builder->aiOnnxOpset10().div(args);
      });

  ConstExprTest_Elementwise_Test<int64_t>(
      {4, 12},
      {2}, // Will be broadcast to {2, 2}
      {2, 6},
      [](std::unique_ptr<popart::Builder> &builder,
         const std::vector<TensorId> &args) -> TensorId {
        return builder->aiOnnxOpset10().div(args);
      });

  ConstExprTest_Elementwise_Test<float16_t>(
      {8.0, 18.0},
      {4.0, 3.0},
      {2.0, 6.0},
      [](std::unique_ptr<popart::Builder> &builder,
         const std::vector<TensorId> &args) -> TensorId {
        return builder->aiOnnxOpset10().div(args);
      });

  ConstExprTest_Elementwise_Test<float_t>(
      {10.0, 21.0},
      {4.0, 5.0},
      {2.5, 4.2},
      [](std::unique_ptr<popart::Builder> &builder,
         const std::vector<TensorId> &args) -> TensorId {
        return builder->aiOnnxOpset10().div(args);
      });

  ConstExprTest_Elementwise_Test<int64_t>(
      {4, 12},
      {2, 3},
      {6, 15},
      [](std::unique_ptr<popart::Builder> &builder,
         const std::vector<TensorId> &args) -> TensorId {
        return builder->aiOnnxOpset10().add(args);
      });

  ConstExprTest_Elementwise_Test<int64_t>(
      {4, 12},
      {2, 3},
      {2, 9},
      [](std::unique_ptr<popart::Builder> &builder,
         const std::vector<TensorId> &args) -> TensorId {
        return builder->aiOnnxOpset10().sub(args);
      });

  ConstExprTest_Elementwise_Test<float_t>(
      {4.1, 101},
      {0.1, 50.5},
      {4.0, 50.5},
      [](std::unique_ptr<popart::Builder> &builder,
         const std::vector<TensorId> &args) -> TensorId {
        return builder->aiOnnxOpset10().sub(args);
      });

  ConstExprTest_Elementwise_Test<int64_t>(
      {4, 12},
      {2, 3},
      {8, 36},
      [](std::unique_ptr<popart::Builder> &builder,
         const std::vector<TensorId> &args) -> TensorId {
        return builder->aiOnnxOpset10().mul(args);
      });

  ConstExprTest_Elementwise_Test<float16_t>(
      {4., 12},
      {0.5, 1.5},
      {2.0, 18},
      [](std::unique_ptr<popart::Builder> &builder,
         const std::vector<TensorId> &args) -> TensorId {
        return builder->aiOnnxOpset10().mul(args);
      });

  ConstExprTest_Elementwise_Test<int64_t>(
      {4, -12},
      {-3, 8},
      {1, -4},
      [](std::unique_ptr<popart::Builder> &builder,
         const std::vector<TensorId> &args) -> TensorId {
        return builder->aiGraphcoreOpset1().fmod(args);
      });
}


text:
/* This file is part of VoltDB.
 * Copyright (C) 2008-2020 VoltDB Inc.
 *
 * This file contains original code and/or modifications of original code.
 * Any modifications made by VoltDB Inc. are licensed under the following
 * terms and conditions:
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 */
/* Copyright (C) 2008 by H-Store Project
 * Brown University
 * Massachusetts Institute of Technology
 * Yale University
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
 * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 */

#include <sstream>
#include <iostream>
#include <boost/shared_ptr.hpp>
#include "harness.h"
#include "common/common.h"
#include "common/serializeio.h"
#include "common/debuglog.h"
#include "common/tabletuple.h"
#include "storage/temptable.h"
#include "storage/tablefactory.h"
#include "storage/tableiterator.h"
#include "common/ValueFactory.hpp"

#define TUPLES 20

using namespace std;
using namespace voltdb;

#define NUM_OF_COLUMNS 6
ValueType col_types[NUM_OF_COLUMNS] = {
    ValueType::tTINYINT,
    ValueType::tBIGINT,
    ValueType::tBIGINT,
    ValueType::tBIGINT,
    ValueType::tVARCHAR,
    ValueType::tDOUBLE
};

class TableSerializeTest : public Test {
    public:
        TableSerializeTest() :
          columnNames(NUM_OF_COLUMNS)
        {
            this->database_id = 1000;

            std::vector<voltdb::ValueType> columnTypes;
            std::vector<int32_t> columnSizes;
            std::vector<bool> columnAllowNull(NUM_OF_COLUMNS, false);
            for (int ctr = 0; ctr < NUM_OF_COLUMNS; ctr++) {
                char name[16];
                if (ctr == 0) ::snprintf(name, 16, "id");
                else ::snprintf(name, 16, "val%02d", ctr);
                columnNames[ctr] = name;
                int size = (col_types[ctr] != ValueType::tVARCHAR ? 8 : 20);
                columnSizes.push_back(static_cast<int32_t>(size));
                columnTypes.push_back(col_types[ctr]);
            }
            voltdb::TupleSchema *schema = voltdb::TupleSchema::createTupleSchemaForTest(columnTypes, columnSizes, columnAllowNull);
            table_ = TableFactory::buildTempTable("temp_table", schema, columnNames, NULL);

            for (int64_t i = 1; i <= TUPLES; ++i) {
                TableTuple &tuple = table_->tempTuple();
                tuple.setNValue(0, ValueFactory::getTinyIntValue(static_cast<int8_t>(i)));
                tuple.setNValue(1, ValueFactory::getBigIntValue(static_cast<int16_t>(i % 2)));
                tuple.setNValue(2, ValueFactory::getBigIntValue(static_cast<int32_t>(i % 3)));
                tuple.setNValue(3, ValueFactory::getBigIntValue(static_cast<int64_t>(i % 5)));
                ostringstream str;
                str << "varchar string:" << (i % 7);
                NValue stringValue = ValueFactory::getStringValue(str.str());
                tuple.setNValueAllocateForObjectCopies(4, stringValue);
                stringValue.free();
                tuple.setNValue(5, ValueFactory::getDoubleValue(3.14f * static_cast<double>(i)));
                table_->insertTuple(tuple);
            }

        }
        virtual ~TableSerializeTest() {
            table_->deleteAllTempTupleDeepCopies();
            delete table_;
        }
    protected:
        CatalogId database_id;
        CatalogId table_id;
        TempTable* table_;
        std::vector<std::string> columnNames;
};

TEST_F(TableSerializeTest, RoundTrip) {
    // print out the first table
    /*TableTuple tuple(table_.get());
    TableIterator iter = table_->iterator();
    VOLT_DEBUG("TABLE 1");
    while (iter.next(tuple)) {
        VOLT_DEBUG(" %s", tuple.debug(table_.get()).c_str());
    }*/
    // Serialize the table
    CopySerializeOutput serialize_out;
    table_->serializeTo(serialize_out);
    size_t size = serialize_out.size();

    // Deserialize the table: verify that it matches the existing table
    ReferenceSerializeInputBE serialize_in(serialize_out.data() + sizeof(int32_t), serialize_out.size() - sizeof(int32_t));
    TempTableLimits limits;
    TupleSchema *schema = TupleSchema::createTupleSchema(table_->schema());
    TempTable* deserialized = TableFactory::buildTempTable("foo", schema, columnNames, &limits);
    deserialized->loadTuplesFrom(serialize_in, NULL);
    int colnum = table_->columnCount();
    EXPECT_EQ(colnum, deserialized->columnCount());
    for (int i = 0; i < colnum; ++i) {
        EXPECT_EQ(table_->columnName(i), deserialized->columnName(i));
    }

    // Serialize the table a second time, verify that it
    CopySerializeOutput serialize_out2;
    deserialized->serializeTo(serialize_out2);
    size_t size2 = serialize_out2.size();
    ASSERT_EQ(size, size2);
    const void *data1 = serialize_out.data();
    const void *data2 = serialize_out2.data();
    EXPECT_EQ(0, ::memcmp(data1, data2, size));
    deserialized->deleteAllTempTupleDeepCopies();
    delete deserialized;
}

TEST_F(TableSerializeTest, NullStrings) {
    std::vector<std::string> columnNames(1);
    std::vector<voltdb::ValueType> columnTypes(1, voltdb::ValueType::tVARCHAR);
    std::vector<int32_t> columnSizes(1, 20);
    std::vector<bool> columnAllowNull(1, false);
    voltdb::TupleSchema *schema = voltdb::TupleSchema::createTupleSchemaForTest(columnTypes, columnSizes, columnAllowNull);
    columnNames[0] = "";
    table_->deleteAllTempTupleDeepCopies();
    delete table_;
    table_ = TableFactory::buildTempTable("temp_table", schema, columnNames, NULL);

    TableTuple& tuple = table_->tempTuple();
    tuple.setNValue(0, ValueFactory::getNullStringValue());
    table_->insertTuple(tuple);

    // Serialize the table
    CopySerializeOutput serialize_out;
    table_->serializeTo(serialize_out);

    // Deserialize the table: verify that it matches the existing table
    ReferenceSerializeInputBE serialize_in(serialize_out.data() + sizeof(int32_t), serialize_out.size() - sizeof(int32_t));
    TempTableLimits limits;
    schema = TupleSchema::createTupleSchema(table_->schema());
    Table* deserialized = TableFactory::buildTempTable("foo", schema, columnNames, &limits);
    deserialized->loadTuplesFrom(serialize_in, NULL);

    EXPECT_EQ(1, deserialized->activeTupleCount());
    EXPECT_EQ(1, table_->activeTupleCount());
    EXPECT_EQ(1, deserialized->columnCount());
    EXPECT_EQ(1, table_->columnCount());
    EXPECT_EQ("", table_->columnName(0));
    EXPECT_EQ("", deserialized->columnName(0));
    EXPECT_EQ(ValueType::tVARCHAR, table_->schema()->columnType(0));
    EXPECT_EQ(ValueType::tVARCHAR, deserialized->schema()->columnType(0));
    EXPECT_EQ(false, table_->schema()->columnIsInlined(0));

    TableIterator iter = deserialized->iterator();
    TableTuple t(deserialized->schema());
    int count = 0;
    while (iter.next(t)) {
        const TupleSchema::ColumnInfo *columnInfo = tuple.getSchema()->getColumnInfo(0);
        EXPECT_EQ(ValueType::tVARCHAR, columnInfo->getVoltType());
        const TupleSchema::ColumnInfo *tcolumnInfo = t.getSchema()->getColumnInfo(0);
        EXPECT_EQ(ValueType::tVARCHAR, tcolumnInfo->getVoltType());
        EXPECT_TRUE(tuple.getNValue(0).isNull());
        EXPECT_TRUE(t.getNValue(0).isNull());
        EXPECT_TRUE(ValueFactory::getNullStringValue().op_equals(tuple.getNValue(0)).isTrue());
        EXPECT_TRUE(ValueFactory::getNullStringValue().op_equals(t.getNValue(0)).isTrue());
        count += 1;
    }
    EXPECT_EQ(1, count);
    delete deserialized;
}

int main() {
    return TestSuite::globalInstance()->runAll();
}

max_stars_repo_name: OpenMPDK/SMDK


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

#define BOOST_TEST_MAIN

#define BOOST_TEST_MODULE basebead_test

// Standard includes
#include <string>

// Third party includes
#include <boost/test/tools/floating_point_comparison.hpp>
#include <boost/test/unit_test.hpp>

// Local VOTCA includes
#include "votca/csg/basebead.h"
#include "votca/csg/molecule.h"
#include "votca/csg/topology.h"

using namespace std;
using namespace votca::csg;
using namespace votca::tools;

class TestBead : public BaseBead {
 public:
  TestBead() : BaseBead(){};
};

BOOST_AUTO_TEST_SUITE(basebead_test)

BOOST_AUTO_TEST_CASE(test_basebead_constructor) { TestBead basebead; }

BOOST_AUTO_TEST_CASE(test_basebead_getters_setters) {

  TestBead basebead;
  BOOST_CHECK_CLOSE(basebead.getMass(), 0.0, 1e-5);
  BOOST_CHECK(!basebead.HasPos());

  basebead.setId(0);
  BOOST_CHECK_EQUAL(basebead.getId(), 0);

  basebead.setName("Bead1");
  string name = "Bead1";
  BOOST_CHECK(name == basebead.getName());

  basebead.setMass(1.0);
  BOOST_CHECK_CLOSE(basebead.getMass(), 1.0, 1e-5);

  Eigen::Vector3d xyz(-1.3, 2.9, 9.2);
  basebead.setPos(xyz);
  BOOST_CHECK(basebead.HasPos());
  Eigen::Vector3d xyz2 = basebead.getPos();
  Eigen::Vector3d xyz_ref = xyz;

  BOOST_CHECK_EQUAL(xyz2.isApprox(xyz_ref, 1e-5), true);

  Eigen::Vector3d xyz3 = basebead.Pos();

  BOOST_CHECK_EQUAL(xyz3.isApprox(xyz_ref, 1e-5), true);

  Topology top;
  basebead.setMoleculeId(0);
  BOOST_CHECK_EQUAL(basebead.getMoleculeId(), 0);
}
BOOST_AUTO_TEST_SUITE_END()

ext: cc

max_stars_repo_name: BuildJet/csg

max_issues_repo_name: BuildJet/csg

max_forks_repo_name: BuildJet/csg


text:
//==============================================================================
//         Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II
//         Copyright 2009 - 2011 LRI    UMR 8623 CNRS/Univ Paris Sud XI
//
//          Distributed under the Boost Software License, Version 1.0.
//                 See accompanying file LICENSE.txt or copy at
//                     http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
#ifndef NT2_TOOLBOX_TRIGONOMETRIC_FUNCTIONS_SIMD_COMMON_FAST_SINCOSD_HPP_INCLUDED
#define NT2_TOOLBOX_TRIGONOMETRIC_FUNCTIONS_SIMD_COMMON_FAST_SINCOSD_HPP_INCLUDED
#include <nt2/toolbox/trigonometric/functions/fast_sincosd.hpp>
#include <nt2/sdk/meta/as_floating.hpp>
#include <nt2/sdk/simd/meta/is_real_convertible.hpp>
#include <boost/fusion/tuple.hpp>
#include <nt2/sdk/meta/strip.hpp>
#include <nt2/toolbox/trigonometric/functions/simd/common/impl/trigo.hpp>

/////////////////////////////////////////////////////////////////////////////
// reference based Implementation
/////////////////////////////////////////////////////////////////////////////
namespace nt2 { namespace ext
{
  NT2_FUNCTOR_IMPLEMENTATION_IF(nt2::tag::fast_sincosd_, boost::simd::tag::simd_,(A0)(A1)(X),
                             (boost::mpl::equal_to<nt2::meta::cardinal_of<A0>,
                                                     nt2::meta::cardinal_of<A1> >),
                             ((simd_ < arithmetic_<A0>,X > ))
                             ((simd_ < floating_<A1>,X > ))
                             ((simd_ < floating_<A1>,X > ))
                             )
  {
    typedef int result_type;
    inline result_type operator()(A0 const& a0,A1 & a1,A1 & a2) const
    {
      a1 = impl::trig_base <A1,degree_tag,
                       tag::not_simd_type>::sincosa(tofloat(a0),a2);
      return 0;
    }
  };

  NT2_FUNCTOR_IMPLEMENTATION_IF(nt2::tag::fast_sincosd_, boost::simd::tag::simd_,(A0)(A1)(X),
                                (boost::mpl::equal_to<nt2::meta::cardinal_of<A0>,
                                                 nt2::meta::cardinal_of<A1>
                                        >
                                ),
                                ((simd_ < arithmetic_<A0>,X > ))
                                ((simd_ < floating_<A1>,X > ))
                             )
  {
    typedef A1 result_type;
    inline result_type operator()(A0 const& a0,A1 & a2) const
    {
      return impl::trig_base <A1,degree_tag,fast_tag,
                       tag::simd_type>::sincosa(tofloat(a0),a2);
    }
  };
  /////////////////////////////////////////////////////////////////////////////
  // Implementation when type  is arithmetic_
  /////////////////////////////////////////////////////////////////////////////
  NT2_FUNCTOR_IMPLEMENTATION(nt2::tag::fast_sincosd_, boost::simd::tag::simd_,
                               (A0)(X),
                               ((simd_<arithmetic_<A0>,X>))
                              )
  {
      typedef typename meta::as_floating<A0>::type  rtype;
      typedef boost::fusion::tuple<rtype, rtype> result_type;

    NT2_FUNCTOR_CALL_REPEAT(1)
    {
      result_type res;
      typedef typename  boost::fusion::result_of::value_at_c<result_type,0>::type type;
      boost::fusion::at_c<0>(res) = impl::trig_base < type,degree_tag
        ,  tag::simd_type, clipped_pio4_
        >::sincosa( tofloat(a0)
                    , boost::fusion::at_c<1>(res)
                    );
      return res;
    }
  };
} }
#endif


text:
//
//  TFibioTransport.h
//  fibio
//
//  Created by Chen Xu on 14/11/12.
//  Copyright (c) 2014 0d0a.com. All rights reserved.
//

#ifndef fibio_thrift_hpp
#define fibio_thrift_hpp

#include <boost/asio/read.hpp>
#include <boost/asio/write.hpp>
#include <fibio/iostream.hpp>
#include <thrift/transport/TVirtualTransport.h>
#include <thrift/transport/TServerTransport.h>
#include <thrift/server/TServer.h>

namespace apache {
namespace thrift {
namespace server {

template <typename Stream, bool buffered>
class TFibioServer;

} // End of namespace server

namespace transport {
namespace detail {

template <bool buffered>
struct io_ops;

template <>
struct io_ops<true>
{
    template <typename Stream>
    static uint32_t read(fibio::stream::iostream<Stream>& s, uint8_t* buf, uint32_t len)
    {
        if (!s) {
            throw TTransportException(TTransportException::NOT_OPEN, "Cannot read.");
        }
        s.read((char*)buf, len);
        if (s.gcount() < len) {
            throw TTransportException(TTransportException::END_OF_FILE, "No more data to read.");
        }
        return len;
    }

    template <typename Stream>
    static void write(fibio::stream::iostream<Stream>& s, const uint8_t* buf, uint32_t len)
    {
        if (!s) throw TTransportException(TTransportException::NOT_OPEN, "Cannot write.");
        s.write((const char*)buf, len);
    }

    template <typename Stream>
    static bool peek(fibio::stream::iostream<Stream>& s)
    {
        if (!s) return false;
        return s.peek() != fibio::stream::iostream<Stream>::traits_type::eof();
    }
};

template <>
struct io_ops<false>
{
    template <typename Stream>
    static uint32_t read(fibio::stream::iostream<Stream>& s, uint8_t* buf, uint32_t len)
    {
        boost::system::error_code ec;
        uint32_t ret = boost::asio::async_read(
            s.stream_descriptor(), boost::asio::buffer(buf, len), fibio::asio::yield[ec]);
        if (ec)
            throw TTransportException(TTransportException::END_OF_FILE, "No more data to read.");
        return ret;
    }

    template <typename Stream>
    static void write(fibio::stream::iostream<Stream>& s, const uint8_t* buf, uint32_t len)
    {
        boost::system::error_code ec;
        boost::asio::async_write(
            s.stream_descriptor(), boost::asio::buffer(buf, len), fibio::asio::yield[ec]);
        if (ec) throw TTransportException(TTransportException::NOT_OPEN, "Cannot write.");
    }

    template <typename Stream>
    static bool peek(fibio::stream::iostream<Stream>& s)
    {
        return true;
    }
};

} // End of namespace detail

template <typename Stream, bool buffered>
class TFibioTransport : public TVirtualTransport<TFibioTransport<Stream, buffered>>
{
public:
    typedef fibio::stream::iostream<Stream> fibio_stream;
    typedef fibio::stream::stream_traits<fibio_stream> traits_type;
    typedef typename traits_type::endpoint_type endpoint_type;
    typedef fibio::stream::listener<fibio_stream> listener_type;

    TFibioTransport(const std::string& access_point)
    : ep_(fibio::stream::detail::make_endpoint<endpoint_type>(access_point))
    , stream_obj_(new fibio_stream)
    , stream_(*stream_obj_)
    {
    }

    virtual bool isOpen() override { return stream_.is_open(); }

    virtual bool peek() override { return detail::io_ops<buffered>::peek(stream_); }

    virtual void open() override { stream_.connect(ep_); }

    virtual void close() override { stream_.close(); }

    virtual void flush() override
    {
        if (buffered) stream_.flush();
    }

    uint32_t read(uint8_t* buf, uint32_t len)
    {
        return detail::io_ops<buffered>::read(stream_, buf, len);
    }

    void write(const uint8_t* buf, uint32_t len)
    {
        return detail::io_ops<buffered>::write(stream_, buf, len);
    }

private:
    friend class server::TFibioServer<Stream, buffered>;

    TFibioTransport(fibio_stream& s) : stream_obj_(), stream_(s) {}

    endpoint_type ep_;
    std::unique_ptr<fibio_stream> stream_obj_;
    fibio_stream& stream_;
};

typedef TFibioTransport<boost::asio::ip::tcp::socket, true> TFibioTCPBufferedTransport;
typedef TFibioTransport<boost::asio::local::stream_protocol::socket, true>
    TFibioLocalBufferedTransport;
typedef TFibioTransport<boost::asio::ip::tcp::socket, false> TFibioTCPTransport;
typedef TFibioTransport<boost::asio::local::stream_protocol::socket, false> TFibioLocalTransport;

} // End of namespace transport

namespace server {

template <typename Stream, bool buffered>
class TFibioServer : public TServer
{
public:
    typedef fibio::stream::iostream<Stream> fibio_stream;
    typedef fibio::stream::stream_traits<fibio_stream> traits_type;
    typedef typename traits_type::endpoint_type endpoint_type;
    typedef fibio::stream::listener<fibio_stream> listener_type;
    typedef transport::TFibioTransport<Stream, buffered> transport_type;

    template <typename Processor>
    TFibioServer(const boost::shared_ptr<Processor>& processor,
                 const std::string& access_point,
                 const boost::shared_ptr<TProtocolFactory>& protocolFactory,
                 THRIFT_OVERLOAD_IF(Processor, TProcessor))
    : TServer(processor,
              boost::shared_ptr<TServerTransport>(), // Not used
              boost::shared_ptr<TTransportFactory>(new TTransportFactory),
              protocolFactory)
    , listener_(access_point)
    {
    }

    virtual void serve() override
    {
        if (eventHandler_) {
            eventHandler_->preServe();
        }
        listener_.start([this](fibio_stream& s) {
            boost::shared_ptr<transport_type> client(new transport_type(s));
            boost::shared_ptr<TProtocol> inputProtocol = inputProtocolFactory_->getProtocol(client);
            boost::shared_ptr<TProtocol> outputProtocol
                = outputProtocolFactory_->getProtocol(client);
            boost::shared_ptr<TProcessor> processor
                = getProcessor(inputProtocol, outputProtocol, client);
            void* connectionContext = NULL;
            if (eventHandler_) {
                connectionContext = eventHandler_->createContext(inputProtocol, outputProtocol);
            }
            for (;;) {
                try {
                    if (eventHandler_) {
                        eventHandler_->processContext(connectionContext, client);
                    }
                    if (!processor->process(inputProtocol, outputProtocol, connectionContext) ||
                        // Peek ahead, is the remote side closed?
                        !inputProtocol->getTransport()->peek()) {
                        break;
                    }
                } catch (transport::TTransportException& ttx) {
                    break;
                }
            }
            if (eventHandler_) {
                eventHandler_->deleteContext(connectionContext, inputProtocol, outputProtocol);
            }
        });
        listener_.join();
    }

    virtual void stop() override { listener_.stop(); }

private:
    listener_type listener_;
};

typedef TFibioServer<boost::asio::ip::tcp::socket, true> TFibioTCPBufferedServer;
typedef TFibioServer<boost::asio::local::stream_protocol::socket, true> TFibioLocalBufferedServer;
typedef TFibioServer<boost::asio::ip::tcp::socket, false> TFibioTCPServer;
typedef TFibioServer<boost::asio::local::stream_protocol::socket, false> TFibioLocalServer;

} // End of namespace server
} // End of namespace thrift
} // End of namespace apache

#endif /* defined(fibio_thrift_hpp) */

max_stars_repo_name: cnsuhao/fibio

max_issues_repo_name: cnsuhao/fibio

max_forks_repo_name: cnsuhao/fibio


text:
/*
 * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
#define BOOST_TEST_MAIN

#define BOOST_TEST_MODULE polararsite_test

// Third party includes
#include <boost/test/unit_test.hpp>

// Local VOTCA includes
#include "votca/xtp/polarsite.h"

using namespace votca::xtp;

BOOST_AUTO_TEST_SUITE(polararsite_test)

BOOST_AUTO_TEST_CASE(constructors_test) { PolarSite ps(1, "ps1"); }

BOOST_AUTO_TEST_CASE(getters_test) {
  PolarSite ps(1, "ps2");
  BOOST_CHECK_EQUAL(ps.getId(), 1);
  BOOST_CHECK_EQUAL(ps.getElement(), "ps2");
}

BOOST_AUTO_TEST_CASE(multipole_test) {
  PolarSite ps(1, "ps2");
  Vector9d multipole = Vector9d::Zero(9);
  multipole << 1, 2, 3, 4, 8, 7, 2, 3.3, -0.5;
  ps.setMultipole(multipole, 2);
  bool check_mpoles = multipole.isApprox(ps.Q(), 0.0001);
  BOOST_CHECK_EQUAL(check_mpoles, true);

  BOOST_CHECK_EQUAL(ps.getRank(), 2);
}

BOOST_AUTO_TEST_CASE(translate_test) {
  PolarSite ps(1, "ps2");
  Eigen::Vector3d shift;
  shift << 0, 0, 5;
  ps.Translate(shift);
  BOOST_CHECK_EQUAL(shift.isApprox(ps.getPos(), 1e-5), true);
}

BOOST_AUTO_TEST_CASE(rotation_test) {
  PolarSite ps(1, "ps2", Eigen::Vector3d::UnitY());

  Eigen::Matrix3d R = Eigen::Matrix3d::Zero();  // Rotation around z axes
  R << 0, -1, 0, 1, 0, 0, 0, 0, 1;

  Vector9d multipoles = Vector9d::Zero(9);
  multipoles << 1, 1, 0, 0, 0, 1, 0, 0,
      0;  // q=1, mu_x=1 and Q_21c=1 the rest is 0
  ps.setMultipole(multipoles, 2);
  ps.Rotate(R, Eigen::Vector3d::Zero());
  bool equalpos = ps.getPos().isApprox(Eigen::Vector3d(-1, 0, 0), 1e-5);
  if (!equalpos) {
    std::cout << "Result " << std::endl;
    std::cout << ps.getPos() << std::endl;
    std::cout << "Reference" << std::endl;
    std::cout << Eigen::Vector3d(-1, 0, 0) << std::endl;
  }
  BOOST_CHECK_EQUAL(equalpos, true);

  Eigen::VectorXd rotmultipoles = Eigen::VectorXd::Zero(9);
  rotmultipoles << 1, 0, 1, 0, 0, 0, 1, 0, 0;  // q=1, mu_y=1 and Q_21s=1 is 0
  bool equalmultipoles = rotmultipoles.isApprox(ps.Q(), 1e-5);
  if (!equalmultipoles) {
    std::cout << "Result " << std::endl;
    std::cout << ps.Q() << std::endl;
    std::cout << "Reference" << std::endl;
    std::cout << rotmultipoles << std::endl;
  }
  BOOST_CHECK_EQUAL(equalmultipoles, true);
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: fossabot/xtp

max_issues_repo_name: fossabot/xtp

max_forks_repo_name: fossabot/xtp


text: #include <boost/graph/chrobak_payne_drawing.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
/*
 * Sarus
 *
 * Copyright (c) 2018-2020, ETH Zurich. All rights reserved.
 *
 * Please, refer to the LICENSE file in the root directory.
 * SPDX-License-Identifier: BSD-3-Clause
 *
 */

#include <sstream>
// boost library must be included before CppUTest
#include <boost/filesystem.hpp>

#include "common/Error.hpp"
#include "common/Logger.hpp"
#include "common/Utility.hpp"
#include "common/Lockfile.hpp"
#include "test_utility/unittest_main_function.hpp"

using namespace sarus;

TEST_GROUP(CLIArgumentsTestGroup) {
};

TEST(CLIArgumentsTestGroup, serialize) {
    auto args = common::CLIArguments{"command", "arg0", "arg1"};

    std::stringstream os;
    os << args;

    CHECK_EQUAL(os.str(), std::string{"[\"command\", \"arg0\", \"arg1\"]"});
};

TEST(CLIArgumentsTestGroup, deserialize) {
    std::stringstream is("[\"command\", \"arg0\", \"arg1\"]");

    common::CLIArguments args;
    is >> args;

    auto expected = common::CLIArguments{"command", "arg0", "arg1"};
    CHECK(args == expected);
};

SARUS_UNITTEST_MAIN_FUNCTION();

max_stars_repo_name: pozsa/sarus

max_issues_repo_name: pozsa/sarus

max_forks_repo_name: pozsa/sarus


text:
/**************************************************************
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 *
 *************************************************************/

#ifndef INCLUDED_SLIDESHOW_USERPAINTOVERLAY_HXX
#define INCLUDED_SLIDESHOW_USERPAINTOVERLAY_HXX

#include <basegfx/polygon/b2dpolypolygon.hxx>

#include "unoview.hxx"
#include "rgbcolor.hxx"

#include <boost/utility.hpp>
#include <boost/shared_ptr.hpp>
#include <vector>

/* Definition of UserPaintOverlay class */

namespace slideshow
{
    namespace internal
    {
        class EventMultiplexer;
        struct SlideShowContext;

        class PaintOverlayHandler;
        typedef ::boost::shared_ptr< class UserPaintOverlay > UserPaintOverlaySharedPtr;
        typedef ::std::vector< ::cppcanvas::PolyPolygonSharedPtr> PolyPolygonVector;
		/** Slide overlay, which can be painted into by the user.

			This class registers itself at the EventMultiplexer,
			listening for mouse clicks and moves. When the mouse is
			dragged, a hand sketching in the selected color is shown.
		*/
		class UserPaintOverlay : private boost::noncopyable
		{
		public:
            /** Create a UserPaintOverlay

            	@param rStrokeColor
                Color to use for drawing

                @param nStrokeWidth
                Width of the stroked path
             */
            static UserPaintOverlaySharedPtr create( const RGBColor&          rStrokeColor,
                                                     double                   nStrokeWidth,
                                                     const SlideShowContext&  rContext,
                                                     const PolyPolygonVector& rPolygons,
													 bool					  bActive);
            ~UserPaintOverlay();
            PolyPolygonVector getPolygons();
            void drawPolygons();

			void update_settings( bool bUserPaintEnabled, RGBColor const& aUserPaintColor, double dUserPaintStrokeWidth );

		private:
			UserPaintOverlay( const RGBColor&          rStrokeColor,
                              double                   nStrokeWidth,
                              const SlideShowContext&  rContext,
                              const PolyPolygonVector& rPolygons,
							  bool					  bActive );

            ::boost::shared_ptr<PaintOverlayHandler>	mpHandler;
            EventMultiplexer&							mrMultiplexer;
		};
    }
}

#endif /* INCLUDED_SLIDESHOW_USERPAINTOVERLAY_HXX */

ext: hxx

max_stars_repo_name: Grosskopf/openoffice

max_issues_repo_name: Grosskopf/openoffice

max_forks_repo_name: Grosskopf/openoffice


text:
#ifndef ERRORHANDLING_HPP
#define ERRORHANDLING_HPP

/**
 * @file errorhandling.hpp
 * File containing primitives for error handling.
 */

#include <exception>

#include <boost/current_function.hpp>
#include <boost/exception/all.hpp>
#include <boost/stacktrace.hpp>

/**
 * Base class for exceptions used by this application.
 */
class basic_error
    : public virtual std::exception
    , public virtual boost::exception {
public:
    const char *what() const noexcept override;
protected:
    basic_error() = default;
    basic_error(const char *what);
    basic_error(const basic_error &) = default;
    virtual ~basic_error() override = default;
private:
    const char *mWhat = "";
};

/**
 * Exception thrown by ASSERT statements.
 *
 * It always represents a software bug since the ASSERT must only be used to
 * validate internal assumptions of the application.
 */
struct assertion_error : virtual basic_error {
    assertion_error() = default;
    assertion_error(const char *what);
    assertion_error(const assertion_error &) = default;
};

/**
 * Exception thrown for unexpected system errors.
 *
 * Unexpected system errors refers to errors that are not expected to occur on
 * proper operating systems. A proper operating system is an operating system
 * where system calls, libraries and other interfaces are working as specified.
 *
 * In some cases, limited resources or unsupported system configurations can
 * also be expressed with this exception. For example, it might be a valid use
 * case when the process could not be forked, although it might be caused by
 * limited resources.
 *
 * Due to the surprising nature of such exceptions, they should be handled as
 * serious error. Applications are advised to shut down itself or the module
 * causing the exception.
 */
struct os_error : virtual basic_error {
    os_error() = default;
    os_error(const char *what);
    os_error(const os_error &) = default;
};

/**
 * Exception thrown for unexpected errors regarding to system files.
 *
 * As specialization of os_error, this exception should only be used for
 * unexpected problems and handled as serious error.
 *
 * Note that this exception should be used for invalid system files but not for
 * system errors regarding to user files.
 */
struct os_file_error : virtual os_error {
    os_file_error() = default;
    os_file_error(const char *what);
    os_file_error(const os_file_error &) = default;
};

/**
 * Namespace containing types of additional information for exceptions.
 */
namespace errinfo {
    ///@name General
    ///@{
        /**
         * Another exception that has caused this one.
         */
        using cause     = boost::errinfo_nested_exception;
    ///@}
    ///@name API related
    ///@{
        /**
         * The system error code (`errno`) provided by an API.
         */
        using errnum    = boost::errinfo_errno;
        /**
         * The name of the API function that has caused the error.
         */
        using function  = boost::errinfo_api_function;
    ///@}
    ///@name File related
    ///@{
        /**
         * The name of the file which has been processed when the error
         * occurred.
         */
        using filename  = boost::errinfo_file_name;
        /**
         * The line of the file that has been processed when the error occurred.
         */
        using line      = boost::errinfo_at_line;
    ///@}
    ///@name Localization (Automatically added by THROW macro)
    ///@{
        /**
         * The stacktrace of the exception.
         */
        using trace     = boost::error_info<struct tag_trace,
                          boost::stacktrace::stacktrace>;
        /**
         * The function which has thrown the exception.
         */
        using srcfunc   = boost::throw_function;
        /**
         * The file where the exception has been thrown.
         */
        using srcfile   = boost::throw_file;
        /**
         * The line where the exception has been thrown.
         */
        using srcline   = boost::throw_line;
    ///@}
}

/**
 * A small utility function to crop “&” and “std::” from a string.
 */
const char *crop_ampersand_and_stdnamespace(const char *) noexcept;

/**
 * Throws the given exception and adds basic information.
 *
 * This macro should be used to thorw exceptions within this application. In
 * addition to throwing the given exception, the following information is added
 * to it:
 *
 *  -  errinfo::trace
 *  -  errinfo::srcfunc
 *  -  errinfo::srcfile
 *  -  errinfo::srcline
 */
#define THROW(exception)                                                \
        throw (exception)                                               \
            << errinfo::trace(boost::stacktrace::stacktrace())          \
            << errinfo::srcfunc(BOOST_CURRENT_FUNCTION)                 \
            << errinfo::srcfile(__FILE__)                               \
            << errinfo::srcline(static_cast<int>(__LINE__))

#define ASSERT(condition)                                               \
        (static_cast<bool>(condition)                                   \
         ? void (0)                                                     \
         : THROW(assertion_error("Assertion Error: " #condition)))

/**
 * Throws an os_error with the given message.
 *
 * In addition to the error message, the name of the given function and the
 * current `errno` value is attached to the exception.
 *
 * ```{.cpp}
 * while (read(fd, buf, sizeof(buf)) < 0) {
 *     if (errno != EINTR) {
 *         OSERROR(read, "`read()' failed on internal pipe");
 *     }
 * }
 * ```
 *
 * For some cases, you might want to use ::OSCHECK instead.
 */
#define OSERROR(fun, message)                                           \
        THROW(os_error(message))                                        \
            << errinfo::function(crop_ampersand_and_stdnamespace(#fun)) \
            << errinfo::errnum(errno)

/**
 * Calls the given function and throws os_error on failure.
 *
 * This macro is intended as shorthand for ::OSERROR. It calls the function
 * given as first argument with the argument list given as second argument.
 * Then, the return value is validated against the condition given as third
 * argument. If the validation fails, an os_error is thrown. Otherwise, the
 * macro resolves to the return value.
 *
 * ```{.cpp}
 * pid_t child_pid = OSCHECK(fork,(), >= 0);
 * ```
 */
#define OSCHECK(fun, args, cond) ([&](const char *_oscheck_funcname) {  \
        const auto _oscheck_ret = fun args ;                            \
        if (!(_oscheck_ret cond)) {                                     \
            OSERROR(fun, "`"#fun"()' has surprisingly failed")          \
                << errinfo::srcfunc(_oscheck_funcname);                 \
        }                                                               \
        return _oscheck_ret;                                            \
}(BOOST_CURRENT_FUNCTION))

#endif // ERRORHANDLING_HPP

max_stars_repo_name: xgme-team/lan-torrent-server

max_issues_repo_name: xgme-team/lan-torrent-server

max_forks_repo_name: xgme-team/lan-torrent-server