text:
// test_aead_filters.cpp -- Test sodium::aead_{encrypt,decrypt}_filter
//
// ISC License
//
// Copyright (C) 2018 Farid Hajji <farid@hajji.name>
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE sodium::aead_filters Test
#include <boost/test/included/unit_test.hpp>

#include "aead_decrypt_filter.h"
#include "aead_encrypt_filter.h"
#include "common.h"

#include <algorithm>
#include <stdexcept>
#include <string>

#ifndef NDEBUG
#include <iostream>
#endif // ! NDEBUG

#include <boost/iostreams/device/array.hpp>
#include <boost/iostreams/filtering_stream.hpp>

using sodium::aead_decrypt_filter;
using sodium::aead_encrypt_filter;
using chars = sodium::chars;
using aead = sodium::aead<chars>; // NOT bytes!

namespace io = boost::iostreams;

struct SodiumFixture
{
    SodiumFixture()
    {
        BOOST_REQUIRE(sodium_init() != -1);
        // BOOST_TEST_MESSAGE("SodiumFixture(): sodium_init() successful.");
    }
    ~SodiumFixture()
    {
        // BOOST_TEST_MESSAGE("~SodiumFixture(): teardown -- no-op.");
    }
};

bool
test_of_correctness_combined_output_filter(const std::string& header,
                                           const std::string& plaintext)
{
    aead_encrypt_filter::key_type key;     // Create a random key
    aead_encrypt_filter::nonce_type nonce; // Create a random nonce
    aead crypt{ std::move(key) };

    chars headerblob{ header.cbegin(), header.cend() };

    aead_encrypt_filter encrypt_filter{ crypt,
                                        nonce,
                                        headerblob }; // COPY crypt to...
    aead_decrypt_filter decrypt_filter{ std::move(crypt),
                                        nonce,
                                        headerblob }; // ... reuse here.

    chars plainblob{ plaintext.cbegin(), plaintext.cend() };
    chars decrypted(2 * plaintext.size()); // because of both writes below

    try {
        io::array_sink sink{ decrypted.data(), decrypted.size() };
        io::filtering_ostream os{};
        os.push(encrypt_filter); // first encrypt
        os.push(decrypt_filter); // then decrypt again
        os.push(sink);           // and store result in sink/derypted.

        os.write(plainblob.data(), plainblob.size());
        os.write(plainblob.data(),
                 plainblob.size()); // simulate multiple writes
        os.flush();

        os.pop();
    } catch (std::exception& /* e */) {
        // decryption failed for some reason

#ifndef NDEBUG
        std::cerr
          << "test_of_correctness_combined_output_filter(): decryption failed"
          << std::endl;
#endif // ! NDEBUG

        return false;
    }

    // sink (i.e. decrypted) has been hopefully filled with decrypted text

    // because we've sent plainblob TWICE with os.write() to the sink,
    // decrypted == (plainblob || plainblob).

    return std::equal(decrypted.cbegin(),
                      decrypted.cbegin() + plaintext.size(),
                      plainblob.cbegin()) &&
           std::equal(decrypted.cbegin() + plaintext.size(),
                      decrypted.cend(),
                      plainblob.cbegin());
}

bool
test_of_correctness_combined_input_filter(const std::string& header,
                                          const std::string& plaintext)
{
    chars headerblob{ header.cbegin(), header.cend() };
    chars plainblob{ plaintext.cbegin(), plaintext.cend() };
    chars plainblob2{ plainblob };
    std::copy(
      plainblob.cbegin(),
      plainblob.cend(),
      std::back_inserter(plainblob2)); // plainblob2 = (plainblob || plainblob)

    aead_encrypt_filter::key_type key;     // Create a random key
    aead_encrypt_filter::nonce_type nonce; // Create a random nonce

    aead crypt{ std::move(key) };

    aead_encrypt_filter encrypt_filter{ crypt, nonce, headerblob };
    aead_decrypt_filter decrypt_filter{ std::move(crypt), nonce, headerblob };

    chars decrypted(2 * plaintext.size()); // because of plainblob2 above

    io::array_source source{ plainblob2.data(), plainblob2.size() };
    io::filtering_istream is{};

    is.push(decrypt_filter); // ... then decrypt again
    is.push(encrypt_filter); // first encrypt...
    is.push(source);         // data from source / plainblob2

    // fetch decrypted text from the filter chain:
    is.read(decrypted.data(), decrypted.size());

    is.pop();

    BOOST_CHECK(is); // decrypting encrypted text MUST succeed!

    // decrypted has been hopefully filled with decrypted text

    // because we've sent plainblob2,
    // decrypted == (plainblob || plainblob).

    return decrypted == plainblob2;
}

bool
test_of_correctness_output_filter(const std::string& header,
                                  const std::string& plaintext,
                                  bool falsify_header = false,
                                  bool falsify_ciphertext = false,
                                  bool falsify_mac = false,
                                  bool falsify_key = false,
                                  bool falsify_nonce = false)
{
    chars headerblob{ header.cbegin(), header.cend() };
    chars plainblob{ plaintext.cbegin(), plaintext.cend() };

    // create a falsified header (only for non-empty headers)
    chars headerblob2 = headerblob;
    if (!headerblob2.empty())
        ++headerblob2[0];

    // 1. encrypt plaintext into ciphertext

    aead_encrypt_filter::key_type key;      // Create a random key
    aead_decrypt_filter::key_type key2;     // Create another random key
    aead_encrypt_filter::nonce_type nonce;  // Create a random nonce
    aead_decrypt_filter::nonce_type nonce2; // Create another random nonce

    aead crypt{ std::move(key) };
    aead crypt2{ std::move(key2) };

    aead_encrypt_filter encrypt_filter{ crypt, nonce, headerblob };
    aead_decrypt_filter decrypt_filter{
        (falsify_key ? std::move(crypt2) : std::move(crypt)),
        (falsify_nonce ? nonce2 : nonce),
        (falsify_header ? headerblob2 : headerblob)
    };

    chars ciphertext(aead_encrypt_filter::MACSIZE + plaintext.size());

    io::array_sink sink1{ ciphertext.data(), ciphertext.size() };
    io::filtering_ostream os1{};
    os1.push(encrypt_filter); // encrypt
    os1.push(sink1);          // then store result in sink/ciphertext.

    os1.write(plainblob.data(), plainblob.size());

    os1.pop();

    // sink1 (i.e. ciphertext) contains (MAC || ciphertext)

    BOOST_CHECK_EQUAL(ciphertext.size(),
                      aead_encrypt_filter::MACSIZE + plainblob.size());

    if (!plaintext.empty() && falsify_ciphertext) {
        // ciphertext is of the form: (MAC || actual_ciphertext)
        ++ciphertext[aead_encrypt_filter::MACSIZE]; // falsify ciphertext
    }

    if (falsify_mac) {
        // ciphertext is of the form: (MAC || actual_ciphertext)
        ++ciphertext[0]; // falsify MAC
    }

    // 2. now, (attempt to) decrypt ciphertext into decrypted:

    chars decrypted(ciphertext.size() - aead_decrypt_filter::MACSIZE);
    try {
        io::array_sink sink2{ decrypted.data(), decrypted.size() };
        io::filtering_ostream os2{};
        os2.push(decrypt_filter); // (attempt to) decrypt
        os2.push(sink2);          // then store result in sink/ciphertext.

        os2.write(ciphertext.data(), ciphertext.size());

        os2.pop();

        // sink2 (i.e. decrypted) has been hopefully filled with decrypted text

        BOOST_CHECK_EQUAL(decrypted.size(), plainblob.size());
    } catch (std::exception& /* e */) {
        // decryption failed. This is expected if and only if we falsified
        // the ciphertext OR we falsified the MAC
        // OR we falsified the key
        // OR we falsified the nonce
        // OR we falsified the header (or any combination of those)

#ifndef NDEBUG
        std::cerr << "test_of_correctness_output_filter(): decryption failed"
                  << std::endl;
#endif // ! NDEBUG

        return falsify_header || falsify_ciphertext || falsify_mac ||
               falsify_key || falsify_nonce;
    }

    // decryption succeeded and plainblob == decrypted if and only if
    // we don't falsify the ciphertext nor the MAC,
    // nor the key nor the nonce
    // not the header.

#ifndef NDEBUG
    std::cerr << "test_of_correctness_output_filter(): decryption succeeded"
              << std::endl;
#endif // ! NDEBUG

    return !falsify_ciphertext && !falsify_mac && !falsify_key &&
           !falsify_nonce && !falsify_header && (plainblob == decrypted);
}

bool
test_of_correctness_input_filter(const std::string& header,
                                 const std::string& plaintext,
                                 bool falsify_header = false,
                                 bool falsify_ciphertext = false,
                                 bool falsify_mac = false,
                                 bool falsify_key = false,
                                 bool falsify_nonce = false)
{
    chars headerblob{ header.cbegin(), header.cend() };

    // create a falsified header (only for non-empty headers)
    chars headerblob2 = headerblob;
    if (!headerblob2.empty())
        ++headerblob2[0];

    chars plainblob{ plaintext.cbegin(), plaintext.cend() };

    // 1. encrypt plaintext into ciphertext

    aead crypt;  // create a cryptor with a random key
    aead crypt2; // create a cryptor with another random key
    aead_encrypt_filter::nonce_type nonce;  // Create a random nonce
    aead_decrypt_filter::nonce_type nonce2; // Create another random nonce

    aead_encrypt_filter encrypt_filter{ crypt, nonce, headerblob };
    aead_decrypt_filter decrypt_filter{
        (falsify_key ? std::move(crypt2) : std::move(crypt)),
        (falsify_nonce ? nonce2 : nonce),
        (falsify_header ? headerblob2 : headerblob)
    };

    chars ciphertext(aead_encrypt_filter::MACSIZE + plaintext.size());

    io::array_source source1{ plainblob.data(), plainblob.size() };
    io::filtering_istream is1{};
    is1.push(encrypt_filter); // encrypt data...
    is1.push(source1);        // from source1 / plainblob.

    // fetch ciphertext by reading into variable ciphertext
    is1.read(ciphertext.data(), ciphertext.size());

    is1.pop();

    // variable ciphertext contains (MAC || ciphertext)

    BOOST_CHECK_EQUAL(ciphertext.size(),
                      aead_encrypt_filter::MACSIZE + plainblob.size());

#ifndef NDEBUG
    std::string ciphertext_string{ ciphertext.cbegin(), ciphertext.cend() };
    std::cerr << "t-o-c-i-f() ciphertext={" << ciphertext_string
              << "} size=" << ciphertext.size() << std::endl;
#endif // ! NDEBUG

    // 2. falsify ciphertext if asked

    if (!plaintext.empty() && falsify_ciphertext) {
        // ciphertext is of the form: (MAC || actual_ciphertext)
        ++ciphertext[aead_encrypt_filter::MACSIZE]; // falsify ciphertext
    }

    // 3. falsify mac if asked

    if (falsify_mac) {
        // ciphertext is of the form: (MAC || actual_ciphertext)
        ++ciphertext[0]; // falsify MAC
    }

    // 4. falsify header if asked
    // see above, alreay submitted to decrypt_filter.

    // 5. now try to decrypt ciphertext into decrypted

    chars decrypted(ciphertext.size() - aead_decrypt_filter::MACSIZE);

    io::array_source source2{ ciphertext.data(), ciphertext.size() };
    io::filtering_istream is2{};
    // is2.exceptions(std::ios_base::failbit | std::ios_base::failbit);
    std::streamsize n{};

    is2.push(decrypt_filter); // (attempt to) decrypt
    is2.push(source2);        // from source2 / ciphertext.

    // read decrypted result into decrypted variable
    is2.read(decrypted.data(), decrypted.size());

    n = is2.gcount();

    is2.pop();

#ifndef NDEBUG
    std::string decrypted_string{ decrypted.cbegin(), decrypted.cend() };
    std::cerr << "decrypted={" << decrypted_string << "}, size=" << n
              << std::endl;
#endif // ! NDEBUG

    if (is2) {
        // decrypted variable has been hopefully filled with decrypted text
        BOOST_CHECK(is2);
        BOOST_CHECK_EQUAL(n, plainblob.size());
        BOOST_CHECK_EQUAL(decrypted.size(), plainblob.size());

        // decryption succeeded and plainblob == decrypted if and only if
        // we don't falsify the ciphertext nor the MAC,
        // nor the key nor the nonce,
        // nor the header.

#ifndef NDEBUG
        std::cerr << "test_of_correctness_input_filter() decryption succeeded"
                  << std::endl;
#endif // ! NDEBUG

        return !falsify_ciphertext && !falsify_mac && !falsify_key &&
               !falsify_nonce && !falsify_header && (plainblob == decrypted);
    } else {
        // decryption failed. This is expected if and only if we falsified
        // the ciphertext OR we falsified the MAC
        // OR we falsified the key
        // OR we falsified the nonce
        // OR we falsified the header (or any combination of those)

#ifndef NDEBUG
        std::cerr << "test_of_correctness_input_filter() decryption failed"
                  << std::endl;
#endif // ! NDEBUG

        return falsify_header || falsify_ciphertext || falsify_mac ||
               falsify_key || falsify_nonce;
    }

    // NOTREACHED (hopefully)

#ifndef NDEBUG
    std::cerr << "falling off the cliff!" << std::endl;
#endif // ! NDEBUG

    return false;
}

void
length_test_output_filter(const std::string& header,
                          const std::string& plaintext)
{
    chars headerblob{ header.cbegin(), header.cend() };

    // create a filter with a random key / random nonce cryptor.
    // multiple use of std::move semantics behing the curtain.
    aead_encrypt_filter encrypt_filter{ aead(),
                                        aead_encrypt_filter::nonce_type(),
                                        headerblob };

    chars plainblob{ plaintext.cbegin(), plaintext.cend() };
    chars ciphertext(aead_encrypt_filter::MACSIZE + plainblob.size());

    io::array_sink sink{ ciphertext.data(), ciphertext.size() };
    io::filtering_ostream os{};
    os.push(encrypt_filter); // first encrypt
    os.push(sink);           // and store result in sink/ciphertext.

    os.write(plainblob.data(), plainblob.size());
    os.flush();

    os.pop();

    // sink (i.e. ciphertext) has been hopefully filled with (MAC || ciphertext)

    BOOST_CHECK_EQUAL(ciphertext.size(),
                      aead_encrypt_filter::MACSIZE + plaintext.size());
}

void
length_test_input_filter(const std::string& header,
                         const std::string& plaintext)
{
    chars headerblob{ header.cbegin(), header.cend() };
    chars plainblob{ plaintext.cbegin(), plaintext.cend() };

    aead_encrypt_filter::key_type key;     // Create a random key
    aead_encrypt_filter::nonce_type nonce; // Create a random nonce

    aead_encrypt_filter encrypt_filter{ aead(std::move(key)),
                                        nonce,
                                        headerblob };

    chars ciphertext(aead_encrypt_filter::MACSIZE + plainblob.size());

    io::array_source source{ plainblob.data(), plainblob.size() };
    io::filtering_istream is{};
    is.push(encrypt_filter); // encrypt data...
    is.push(source);         // ... from source plainblob

    // read produced ciphertext and store it here:
    is.read(ciphertext.data(), ciphertext.size());

    is.pop();

    // ciphertext has been hopefully filled with (MAC || ciphertext)

    BOOST_CHECK_EQUAL(ciphertext.size(),
                      aead_encrypt_filter::MACSIZE + plaintext.size());
}

BOOST_FIXTURE_TEST_SUITE(sodium_test_suite, SodiumFixture)

BOOST_AUTO_TEST_CASE(sodium_test_aead_filters_size_full_output_filter)
{
    std::string header{ "the header" };
    std::string plaintext{ "the quick brown fox jumps over the lazy dog" };
    length_test_output_filter(header, plaintext);
}

BOOST_AUTO_TEST_CASE(sodium_test_aead_filters_size_empty_output_filter)
{
    std::string header{ "the header" };
    std::string plaintext{};
    length_test_output_filter(header, plaintext);
}

BOOST_AUTO_TEST_CASE(sodium_test_aead_filters_size_empty_header_output_filter)
{
    std::string header{};
    std::string plaintext{ "the quick brown fox jumps over the lazy dog" };
    length_test_output_filter(header, plaintext);
}

BOOST_AUTO_TEST_CASE(sodium_test_aead_filters_size_empty_both_output_filter)
{
    std::string header{};
    std::string plaintext{};
    length_test_output_filter(header, plaintext);
}

BOOST_AUTO_TEST_CASE(sodium_test_aead_filters_size_full_input_filter)
{
    std::string header{ "the header" };
    std::string plaintext{ "the quick brown fox jumps over the lazy dog" };
    length_test_input_filter(header, plaintext);
}

BOOST_AUTO_TEST_CASE(sodium_test_aead_filters_size_empty_input_filter)
{
    std::string header{ "the header" };
    std::string plaintext{};
    length_test_input_filter(header, plaintext);
}

BOOST_AUTO_TEST_CASE(sodium_test_aead_filters_size_empty_header_input_filter)
{
    std::string header{};
    std::string plaintext{ "the quick brown fox jumps over the lazy dog" };
    length_test_input_filter(header, plaintext);
}

BOOST_AUTO_TEST_CASE(sodium_test_aead_filters_size_empty_both_input_filter)
{
    std::string header{};
    std::string plaintext{};
    length_test_input_filter(header, plaintext);
}

BOOST_AUTO_TEST_CASE(
  sodium_test_aead_filters_correctness_combined_full_output_filter)
{
    std::string header{ "the header" };
    std::string plaintext{ "the quick brown fox jumps over the lazy dog" };
    auto result = test_of_correctness_combined_output_filter(header, plaintext);

    // Test must succeed
    BOOST_CHECK(result);
}

BOOST_AUTO_TEST_CASE(
  sodium_test_aead_filters_correctness_combined_empty_output_filter)
{
    std::string header{ "the header" };
    std::string plaintext{};
    auto result = test_of_correctness_combined_output_filter(header, plaintext);

    // Test must succeed
    BOOST_CHECK(result);
}

BOOST_AUTO_TEST_CASE(
  sodium_test_aead_filters_correctness_combined_empty_header_output_filter)
{
    std::string header{};
    std::string plaintext{ "the quick brown fox jumps over the lazy dog" };
    auto result = test_of_correctness_combined_output_filter(header, plaintext);

    // Test must succeed
    BOOST_CHECK(result);
}

BOOST_AUTO_TEST_CASE(
  sodium_test_aead_filters_correctness_combined_empty_both_output_filter)
{
    std::string header{};
    std::string plaintext{};
    auto result = test_of_correctness_combined_output_filter(header, plaintext);

    // Test must succeed
    BOOST_CHECK(result);
}

BOOST_AUTO_TEST_CASE(
  sodium_test_aead_filters_correctness_combined_full_input_filter)
{
    std::string header{ "the header" };
    std::string plaintext{ "the quick brown fox jumps over the lazy dog" };
    auto result = test_of_correctness_combined_input_filter(header, plaintext);

    // Test must succeed
    BOOST_CHECK(result);
}

BOOST_AUTO_TEST_CASE(
  sodium_test_aead_filters_correctness_combined_empty_input_filter)
{
    std::string header{ "the header" };
    std::string plaintext{};
    auto result = test_of_correctness_combined_input_filter(header, plaintext);

    // Test must succeed
    BOOST_CHECK(result);
}

BOOST_AUTO_TEST_CASE(
  sodium_test_aead_filters_correctness_combined_empty_header_input_filter)
{
    std::string header{};
    std::string plaintext{ "the quick brown fox jumps over the lazy dog" };
    auto result = test_of_correctness_combined_input_filter(header, plaintext);

    // Test must succeed
    BOOST_CHECK(result);
}

BOOST_AUTO_TEST_CASE(
  sodium_test_aead_filters_correctness_combined_empty_both_input_filter)
{
    std::string header{};
    std::string plaintext{};
    auto result = test_of_correctness_combined_input_filter(header, plaintext);

    // Test must succeed
    BOOST_CHECK(result);
}

BOOST_AUTO_TEST_CASE(sodium_test_aead_filters_correctness_full_output_filter)
{
    std::string header{ "the header" };
    std::string plaintext{ "the quick brown fox jumps over the lazy dog" };
    auto result = test_of_correctness_output_filter(header, plaintext);

    // Test must succeed
    BOOST_CHECK(result);
}

BOOST_AUTO_TEST_CASE(
  sodium_test_aead_filters_correctness_falsify_header_full_output_filter)
{
    std::string header{ "the header" };
    std::string plaintext{ "the quick brown fox jumps over the lazy dog" };
    auto result = test_of_correctness_output_filter(
      header, plaintext, true, false, false, false, false);

    // Test must succeed, we falsified the header but caught it!
    BOOST_CHECK(result);
}

BOOST_AUTO_TEST_CASE(
  sodium_test_aead_filters_correctness_falsify_ciphertext_full_output_filter)
{
    std::string header{ "the header" };
    std::string plaintext{ "the quick brown fox jumps over the lazy dog" };
    auto result = test_of_correctness_output_filter(
      header, plaintext, false, true, false, false, false);

    // Test must succeed, we falsified the ciphertext but caught it!
    BOOST_CHECK(result);
}

BOOST_AUTO_TEST_CASE(
  sodium_test_aead_filters_correctness_falsify_mac_full_output_filter)
{
    std::string header{ "the header" };
    std::string plaintext{ "the quick brown fox jumps over the lazy dog" };
    auto result = test_of_correctness_output_filter(
      header, plaintext, false, false, true, false, false);

    // Test must succeed, we falsified the MAC but caught it!
    BOOST_CHECK(result);
}

BOOST_AUTO_TEST_CASE(
  sodium_test_aead_filters_correctness_falsify_key_full_output_filter)
{
    std::string header{ "the header" };
    std::string plaintext{ "the quick brown fox jumps over the lazy dog" };
    auto result = test_of_correctness_output_filter(
      header, plaintext, false, false, false, true, false);

    // Test must succeed, we falsified the key but caught it!
    BOOST_CHECK(result);
}

BOOST_AUTO_TEST_CASE(
  sodium_test_aead_filters_correctness_falsify_nonce_full_output_filter)
{
    std::string header{ "the header" };
    std::string plaintext{ "the quick brown fox jumps over the lazy dog" };
    auto result = test_of_correctness_output_filter(
      header, plaintext, false, false, false, false, true);

    // Test must succeed, we falsified the nonce but caught it!
    BOOST_CHECK(result);
}

BOOST_AUTO_TEST_CASE(sodium_test_aead_filters_correctness_full_input_filter)
{
    std::string header{ "the header" };
    std::string plaintext{ "the quick brown fox jumps over the lazy dog" };
    auto result = test_of_correctness_input_filter(header, plaintext);

    // Test must succeed
    BOOST_CHECK(result);
}

BOOST_AUTO_TEST_CASE(
  sodium_test_aead_filters_correctness_falsify_header_full_input_filter)
{
    std::string header{ "the header" };
    std::string plaintext{ "the quick brown fox jumps over the lazy dog" };
    auto result = test_of_correctness_input_filter(
      header, plaintext, true, false, false, false, false);

    // Test must succeed, we falsified the header but caught it!
    BOOST_CHECK(result);
}

BOOST_AUTO_TEST_CASE(
  sodium_test_aead_filters_correctness_falsify_ciphertext_full_input_filter)
{
    std::string header{ "the header" };
    std::string plaintext{ "the quick brown fox jumps over the lazy dog" };
    auto result = test_of_correctness_input_filter(
      header, plaintext, false, true, false, false, false);

    // Test must succeed, we falsified the ciphertext but caught it!
    BOOST_CHECK(result);
}

BOOST_AUTO_TEST_CASE(
  sodium_test_aead_filters_correctness_falsify_mac_full_input_filter)
{
    std::string header{ "the header" };
    std::string plaintext{ "the quick brown fox jumps over the lazy dog" };
    auto result = test_of_correctness_input_filter(
      header, plaintext, false, false, true, false, false);

    // Test must succeed, we falsified the MAC but caught it!
    BOOST_CHECK(result);
}

BOOST_AUTO_TEST_CASE(
  sodium_test_aead_filters_correctness_falsify_key_full_input_filter)
{
    std::string header{ "the header" };
    std::string plaintext{ "the quick brown fox jumps over the lazy dog" };
    auto result = test_of_correctness_input_filter(
      header, plaintext, false, false, false, true, false);

    // Test must succeed, we falsified the key but caught it!
    BOOST_CHECK(result);
}

BOOST_AUTO_TEST_CASE(
  sodium_test_aead_filters_correctness_falsify_nonce_full_input_filter)
{
    std::string header{ "the header" };
    std::string plaintext{ "the quick brown fox jumps over the lazy dog" };
    auto result = test_of_correctness_input_filter(
      header, plaintext, false, false, false, false, true);

    // Test must succeed, we falsified the nonce but caught it!
    BOOST_CHECK(result);
}

BOOST_AUTO_TEST_SUITE_END()


text:
#include "HandScanner.h"

#ifdef LC_INCLUDE_HAND_TRACKING

#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
#include <opencv2/core/types_c.h>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/features2d/features2d.hpp>
#include <opencv2/opencv.hpp>
#include <opencv2/video/background_segm.hpp>
#include <boost/filesystem.hpp>
#include <Python.h>
#include <numpy/ndarrayobject.h>
#include <boost/python.hpp>
#include <Common/CommonClasses.h>

PyObject *HDPyModule, *HDPyDict, *HDPyFunc;

#if PY_MAJOR_VERSION >= 3
int
#else
void
#endif
init_numpy()
{
	import_array();
}

std::array<cv::Point2f, 4> fromNDArrayToPoints(PyObject* o) {
	std::array<cv::Point2f, 4> result;
	result.fill(cv::Point2f(0, 0));
	bool allowND = true;
	if (PyArray_Check(o)) {
		PyArrayObject* oarr = (PyArrayObject*)o;

		float* m = new float[8];
		bool needcopy = false, needcast = false;
		int typenum = NPY_FLOAT;
		int ndims = PyArray_NDIM(oarr);
		const npy_intp* _sizes = PyArray_DIMS(oarr);
		const npy_intp* _strides = PyArray_STRIDES(oarr);

		for (int i = ndims - 1; i >= 0 && !needcopy; i--) {
			// these checks handle cases of
			//  a) multi-dimensional (ndims > 2) arrays, as well as simpler 1- and 2-dimensional cases
			//  b) transposed arrays, where _strides[] elements go in non-descending order
			//  c) flipped arrays, where some of _strides[] elements are negative
			if ((i == ndims - 1 && (size_t)_strides[i] != 9)
				|| (i < ndims - 1 && _strides[i] < _strides[i + 1]))
				needcopy = true;
		}

		if (needcopy) {

			if (needcast) {
				o = PyArray_Cast(oarr, NPY_FLOAT);
				oarr = (PyArrayObject*)o;
			}
			else {
				oarr = PyArray_GETCONTIGUOUS(oarr);
				o = (PyObject*)oarr;
			}

			_strides = PyArray_STRIDES(oarr);
		}

		// handle degenerate case
		if (ndims == 0) {
			ndims++;
		}

		if (ndims > 2 && !allowND) {
			// ERR
		}
		else {
			std::memcpy(m, PyArray_DATA(oarr), sizeof(float) * 8);
			/*float xS = Resolutions::OUTPUT_WIDTH / 300;
			float yS = Resolutions::OUTPUT_HEIGHT / 200;
			result[0] = cv::Point2f((m[1] * xS) * Resolutions::OUTPUT_WIDTH, (m[0] * yS) * Resolutions::OUTPUT_HEIGHT);
			result[1] = cv::Point2f((m[3] * xS) * Resolutions::OUTPUT_WIDTH, (m[2] * yS) * Resolutions::OUTPUT_HEIGHT);
			result[2] = cv::Point2f((m[5] * xS) * Resolutions::OUTPUT_WIDTH, (m[4] * yS) * Resolutions::OUTPUT_HEIGHT);
			result[3] = cv::Point2f((m[7] * xS) * Resolutions::OUTPUT_WIDTH, (m[6] * yS) * Resolutions::OUTPUT_HEIGHT);*/
			if (m[2] < 0.98)
			{
				result[0] = cv::Point2f(m[1] * Resolutions::OUTPUT_WIDTH, m[0] * Resolutions::OUTPUT_HEIGHT);
				result[1] = cv::Point2f(m[3] * Resolutions::OUTPUT_WIDTH, m[2] * Resolutions::OUTPUT_HEIGHT);
			}
			if (m[6] < 0.98)
			{
				result[2] = cv::Point2f(m[5] * Resolutions::OUTPUT_WIDTH, m[4] * Resolutions::OUTPUT_HEIGHT);
				result[3] = cv::Point2f(m[7] * Resolutions::OUTPUT_WIDTH, m[6] * Resolutions::OUTPUT_HEIGHT);
			}

			if (!needcopy) {
				Py_INCREF(o);
			}
			delete[] m;
		}
	}
	return result;
}

HandScanner::HandScanner()
{
	capacity = MAX_TARGETS_COUNT;
	inputSize = cv::Size(200, 200);
	inputMean = cv::Scalar(0, 0, 0);
	inputSwapRB = true;
	detectedPoints.fill(cv::Point2f(0, 0));

	available = true;

#if !defined(_DEBUG)
	Py_SetPath(L".\\python36.zip");
#else
	Py_SetPath(L"C:\\Python\\3.6.8\\Lib");
#endif
	Py_SetProgramName(L"LiveCam");
	Py_InitializeEx(0);
	init_numpy();
	PyRun_SimpleString("import sys\n");
	PyRun_SimpleString("sys.path.append('./')\n");
	PyRun_SimpleString("import detect\n");
	PyObject *pName = PyUnicode_DecodeFSDefault("detect");
	HDPyModule = PyImport_Import(pName);
	if (HDPyModule != nullptr)
	{
		HDPyDict = PyModule_GetDict(HDPyModule);
		HDPyFunc = PyDict_GetItemString(HDPyDict, "get_hands");
	}
	Py_DECREF(pName);
}

HandScanner::~HandScanner()
{
	available = false;
	if (HDPyModule != nullptr)
	{
		Py_XDECREF(HDPyModule);
	}
	Py_XDECREF(HDPyDict);
	Py_XDECREF(HDPyFunc);
	Py_Finalize();
}

void HandScanner::start()
{
}

void HandScanner::stop()
{
}

void HandScanner::setRefFrame(cv::Mat frame, int x, int y)
{}

cv::Mat HandScanner::prepScanFrame(cv::Mat frame)
{
	if (!frame.empty())
	{
		cv::Mat scanFrame;
		cv::Size preSize(300, 178);
		cv::resize(frame, scanFrame, preSize);
		return scanFrame;
	}
	return frame;
}

cv::Mat HandScanner::prepKeypointsFrame(cv::Mat frame)
{
	return frame;
}

std::vector<cv::Rect> HandScanner::scan(cv::Mat frame)
{
	std::vector<cv::Rect> detectedHands;

	scanCounter++;
	if (available)
	{
		available = false;
		if (HDPyFunc != nullptr && PyCallable_Check(HDPyFunc))
		{
			PyObject *pArgs, *pValue;
			pArgs = PyTuple_New(1);
			npy_intp dimensions[3] = { frame.rows, frame.cols, frame.channels() };
			pValue = PyArray_SimpleNewFromData(frame.dims + 1, (npy_intp*)&dimensions, NPY_UINT8, frame.data);
			PyTuple_SetItem(pArgs, 0, pValue);
			PyObject *pResult = PyObject_CallObject(HDPyFunc, pArgs);
			Py_XDECREF(pArgs);

			if (pResult != nullptr) {
				std::array<cv::Point2f, 4> _points = fromNDArrayToPoints(pResult);
				detectedHands.push_back(cv::Rect(_points[0], _points[1]));
				detectedHands.push_back(cv::Rect(_points[2], _points[3]));
				detectedPoints[0] = _points[0];
				detectedPoints[1] = _points[1];
				detectedPoints[2] = _points[2];
				detectedPoints[3] = _points[3];
				Py_XDECREF(pResult);
				available = true;
			}
			else
			{
				Py_XDECREF(pResult);
			}
		}
	}
	else
	{
		delayCounter++;
		if (delayCounter > 200)
		{
			delayCounter = 0;
			scanCounter = 0;
			available = true;
		}
	}

	return detectedHands;
}

void HandScanner::asyncScan()
{

}

void HandScanner::keypoints(TargetHoldingStruct &target, std::array<cv::Point2f, TARGET_DETAIL_MODIFIER>& data)
{
	cv::Rect newRect = target.rect;

	constexpr float cx = 1.3;
	constexpr float cy = 0.85;

	int diffX = newRect.width*cx - newRect.width;
	int diffY = newRect.height*cy - newRect.height;

	newRect.width *= cx;
	newRect.height *= 1.0;
	newRect.x -= diffX * 0.5;
	newRect.y -= diffY;

	target.lastKnownRect = target.rect;
	target.rect = newRect;

	if (newRect.x < 0 || newRect.x + newRect.width >= Resolutions::INPUT_ACTUAL_WIDTH
		|| newRect.y < 0 || newRect.y + newRect.height >= Resolutions::INPUT_ACTUAL_HEIGHT)
	{
		target.visible = false;
		return;
	}

	for (size_t i = 0; i < detectedPoints.size(); i++) {
		cv::Point2f pnt = detectedPoints[i];
		data[i] = pnt;
	}
}

void HandScanner::scale(double newscale)
{
	activescale = newscale;
}

#endif

ext: cpp

max_stars_repo_name: KanSmith/LiveCam

max_issues_repo_name: KanSmith/LiveCam

max_forks_repo_name: KanSmith/LiveCam


text:
/*==============================================================================
  Copyright (c) 2016 Matt Calabrese

  Distributed under the Boost Software License, Version 1.0. (See accompanying
  file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
==============================================================================*/

//[access_tuple
/*`
[heading Description]

This tutorial introduces an __ArgumentProvider__ that expands out a variant to
a reference to the currectly active field of that variant.

[heading Prereq Tutorials]

This tutorial should be able to be understood without reading any other
tutorials in this documentation.

[heading Introduction]

*/
#include <boost/variant/variant.hpp>
#include <boost_ext/call/call.hpp>
#include <boost_ext/call/prov/to_constant_in_range.hpp>

#include <iostream>

struct output_t
{
  template< class Os >
  constexpr Os& operator ()( Os& os ) const
  {
    return os;
  }

  template< class Os, class H, class... T >
  constexpr Os& operator ()( Os& os, const H& head, const T&... tail ) const
  {
    os << head;
    return (*this)( os, tail... );
  }
} constexpr output = {};

int main()
{
  namespace prov = boost_ext::prov;

  decltype( auto ) result
    = boost_ext::call
      ( output, std::cout
              , prov::to_constant_in_range< std::size_t, 0, 2 >( 1 )
      );
//<-
  (void)result;
  //return result != 5;
//->
}
/*`
[heading Related References]

* __Primary_call_overload__
* __prov_access_tuple__
*/
//]

max_stars_repo_name: mattcalabrese/argot

max_issues_repo_name: mattcalabrese/argot

max_forks_repo_name: mattcalabrese/argot


text:
/**
 * @file    FilesystemUtilities.cpp
 * @author  Marvin Smith
 * @date    2/15/2014
 */
#include "FilesystemUtilities.hpp"

#include <boost/filesystem.hpp>
#include <boost/regex.hpp>

#include <vector>

namespace bf=boost::filesystem;

namespace LLNMS{
namespace UTILITIES{

/**
 * Run a standard system command and grab the output
*/
bool run_command( const std::string& command, std::string& message ){

    /// create output message
    message="";

    // run the command on the file descriptor
    FILE* pipe = popen(command.c_str(), "r");
    if( !pipe ){
        message = "command failed to run.";
        return false;
    }
    else{

        // create our output
        char buffer[128];

        // iterate over the stream output
        while(!feof(pipe)) {
            if(fgets(buffer, 128, pipe) != NULL)
                message += buffer;
        }
        pclose(pipe);

    }

    return true;
}

/**
 * Check if a path is a directory
*/
bool is_directory( const std::string& pathname ){
    if( bf::exists( bf::path( pathname ) ) == false ){
        return false;
    }
    return bf::is_directory( bf::path( pathname ));
}

/**
 * Check if a path exists
*/
bool exists( const std::string& pathname ){
    return bf::exists( bf::path( pathname ));
}

/**
 * Get a list of files in a directory
 */
std::vector<std::string> list_contents( const std::string& pathname, const std::string& pattern ){

    // create an output container
    std::vector<std::string> output;

    // build a regex from the pattern input
    boost::regex expression(pattern);

    // make sure if the path does not exist, then return
    if( boost::filesystem::exists( pathname ) == false ){
        return output;
    }

    // if the path is not a directory, then return nothing
    if( boost::filesystem::is_directory( pathname ) == false ){
        return output;
    }

    // iterate over the directory
    boost::filesystem::path dirpath( pathname );
    boost::filesystem::directory_iterator beg_iter( dirpath );
    boost::filesystem::directory_iterator end_iter;

    for( ; beg_iter != end_iter; beg_iter++ ){

        if( boost::filesystem::is_regular_file( beg_iter->status())){

            // compare with the pattern
            if( boost::regex_match( beg_iter->path().string(), expression ) == true ){
                output.push_back( beg_iter->path().string() );
            }
        }

    }

    return output;
}
} /// End of UTILITIES Namespace
} /// End of LLNMS Namespace

max_stars_repo_name: marvins/LLNMS

max_issues_repo_name: marvins/LLNMS

max_forks_repo_name: marvins/LLNMS


text:
#include "local_ads/campaign.hpp"
#include "local_ads/campaign_serialization.hpp"

// This header should be included due to a python compilation error.
// pyport.h overwrites defined macros and replaces it with its own.
// However, in the OS X c++ libraries, these are not macros but functions,
// hence the error. See https://bugs.python.org/issue10910
#include <locale>

#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wreorder"
#pragma GCC diagnostic ignored "-Wunused-local-typedefs"
#if defined(__clang__)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunused-local-typedef"
#endif

#include "pyhelpers/vector_uint8.hpp"
#include "pyhelpers/vector_list_conversion.hpp"

#include <boost/python.hpp>
#include <boost/python/enum.hpp>
#include <boost/python/suite/indexing/vector_indexing_suite.hpp>

#if defined(__clang__)
#pragma clang diagnostic pop
#endif
#pragma GCC diagnostic pop

using namespace local_ads;

namespace
{
std::vector<uint8_t> PySerialize(boost::python::list const & cs, Version const version)
{
  auto const campaigns = python_list_to_std_vector<Campaign>(cs);
  return Serialize(campaigns, version);
}

boost::python::list PyDeserialize(std::vector<uint8_t> const & blob)
{
  auto const campaigns = Deserialize(blob);
  return std_vector_to_python_list(campaigns);
}
}  // namespace

BOOST_PYTHON_MODULE(pylocal_ads)
{
  using namespace boost::python;

  // Register the to-python converters.
  to_python_converter<std::vector<uint8_t>, vector_uint8t_to_str>();
  vector_uint8t_from_python_str();

  class_<Campaign>("Campaign", init<uint32_t, uint16_t, uint8_t, uint8_t, uint8_t>())
      .def(init<uint32_t, uint16_t, uint8_t>())
      .def_readonly("m_featureId", &Campaign::m_featureId)
      .def_readonly("m_iconId", &Campaign::m_iconId)
      .def_readonly("m_daysBeforeExpired", &Campaign::m_daysBeforeExpired)
      .def_readonly("m_minZoomLevel", &Campaign::m_minZoomLevel)
      .def_readonly("m_priority", &Campaign::m_priority);

  class_<std::vector<Campaign>>("CampaignList")
      .def(vector_indexing_suite<std::vector<Campaign>>());

  enum_<Version>("Version")
      .value("UNKNOWN", Version::Unknown)
      .value("V1", Version::V1)
      .value("V2", Version::V2)
      .value("LATEST", Version::Latest)
      .export_values();

  def("serialize", PySerialize);
  def("deserialize", PyDeserialize);
}

max_stars_repo_name: Barysman/omim

max_issues_repo_name: Barysman/omim

max_forks_repo_name: maksimandrianov/omim


text:
/**
 * UnscentedKalmanFilterX.hpp
 * @author koide
 * 16/02/01
 **/
#ifndef KKL_UNSCENTED_KALMAN_FILTER_X_HPP
#define KKL_UNSCENTED_KALMAN_FILTER_X_HPP

#include <random>
#include <Eigen/Dense>
#include <kalman/kalman_filter.hpp>

/**
 * @brief Unscented Kalman Filter class
 * @param T        scaler type
 * @param System   system class to be estimated
 */
template<typename T, class System>
class UnscentedKalmanFilterX  : public KalmanFilter<T, System>
{
  typedef Eigen::Matrix<T, Eigen::Dynamic, 1> VectorXt;    //列向量
  typedef Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> MatrixXt;
  using KalmanFilter<T, System>::state_dim;
  using KalmanFilter<T, System>::N;
  using KalmanFilter<T, System>::input_dim;
  using KalmanFilter<T, System>::measurement_dim;
  using KalmanFilter<T, System>::M;
  using KalmanFilter<T, System>::mean;
  using KalmanFilter<T, System>::cov;
  using KalmanFilter<T, System>::system;
  using KalmanFilter<T, System>::process_noise;
  using KalmanFilter<T, System>::measurement_noise;
  using KalmanFilter<T, System>::kalman_gain;
public:
  /**
   * @brief constructor
   * @param system               system to be estimated
   * @param state_dim            state vector dimension
   * @param input_dim            input vector dimension
   * @param measurement_dim      measurement vector dimension
   * @param process_noise        process noise covariance (state_dim x state_dim)
   * @param measurement_noise    measurement noise covariance (measurement_dim x measuremend_dim)
   * @param mean                 initial mean
   * @param cov                  initial covariance
   */
  UnscentedKalmanFilterX(const System& _system, int _state_dim, int _input_dim, int _measurement_dim,
                         const MatrixXt& _process_noise, const MatrixXt& _measurement_noise,
                         const VectorXt& _mean, const MatrixXt& _cov):
    KalmanFilter<T, System>(_system, _state_dim, _input_dim, _measurement_dim, _process_noise, _measurement_noise, _mean, _cov),
    S(2 * state_dim + 1),
    lambda(1)
  {
    weights.resize(S, 1);
    sigma_points.resize(S, N);
    ext_weights.resize(2 * (N + M) + 1, 1);
    ext_sigma_points.resize(2 * (N + M) + 1, N + M);
    expected_measurements.resize(2 * (N + M) + 1, M);

    // initialize weights for unscented filter
    weights[0] = lambda / (N + lambda);
    for (int i = 1; i < 2 * N + 1; i++) {
      weights[i] = 1 / (2 * (N + lambda));
    }

    // weights for extended state space which includes error variances
    ext_weights[0] = lambda / (N + M + lambda);
    for (int i = 1; i < 2 * (N + M) + 1; i++) {
      ext_weights[i] = 1 / (2 * (N + M + lambda));
    }
  }

  /**
   * @brief predict  预测函数
   * @param control  input vector
   */
  virtual void predict(const VectorXt& control) override
  {
    // calculate sigma points
    this->ensurePositiveFinite(cov);
    computeSigmaPoints(mean, cov, sigma_points); //根据上一时刻的均值和方差计算sigma点
    for (int i = 0; i < S; i++) {
      sigma_points.row(i) = system.f(sigma_points.row(i), control); //根据系统方程传播sigma点
    }

    const auto& Q = process_noise; //系统噪声|过程噪声

    // unscented transform
    VectorXt mean_pred(mean.size());
    MatrixXt cov_pred(cov.rows(), cov.cols());

    mean_pred.setZero();
    cov_pred.setZero();
    for (int i = 0; i < S; i++) {
      mean_pred += weights[i] * sigma_points.row(i);   //传播后的sigma点集均值
    }
    for (int i = 0; i < S; i++) {
      VectorXt diff = sigma_points.row(i).transpose() - mean_pred;
      cov_pred += weights[i] * diff * diff.transpose(); //传播后的sigma点集方差
    }
    cov_pred += Q;                                      //加上过程噪声

    //得到预测值和预测协方差
    mean = mean_pred;
    cov = cov_pred;
  }

  /**
   * @brief correct      校正函数
   * @param measurement  观测值
   */
  virtual void correct(const VectorXt& measurement) override
  {
    // create extended state space which includes error variances
    VectorXt ext_mean_pred = VectorXt::Zero(N + M, 1);
    MatrixXt ext_cov_pred = MatrixXt::Zero(N + M, N + M);
    ext_mean_pred.topLeftCorner(N, 1) = VectorXt(mean);
    ext_cov_pred.topLeftCorner(N, N) = MatrixXt(cov);
    ext_cov_pred.bottomRightCorner(M, M) = measurement_noise;

    this->ensurePositiveFinite(ext_cov_pred);
    computeSigmaPoints(ext_mean_pred, ext_cov_pred, ext_sigma_points); //根据预测均值和协方差以及测量噪声计算sigma点
                                                                       //此时测量误差并未添加到sigama主体,而是存放于拓展部分

    // unscented transform
    expected_measurements.setZero();
    for (int i = 0; i < ext_sigma_points.rows(); i++) {
      expected_measurements.row(i) = system.h(ext_sigma_points.row(i).transpose().topLeftCorner(N, 1));     //观测方程传播sigama点集
      expected_measurements.row(i) += VectorXt(ext_sigma_points.row(i).transpose().bottomRightCorner(M, 1));//添加测量噪声
    }

    VectorXt expected_measurement_mean = VectorXt::Zero(M);
    for (int i = 0; i < ext_sigma_points.rows(); i++) {
      expected_measurement_mean += ext_weights[i] * expected_measurements.row(i);  //传播后的sigama点集均值
    }
    MatrixXt expected_measurement_cov = MatrixXt::Zero(M, M);
    for (int i = 0; i < ext_sigma_points.rows(); i++) {
      VectorXt diff = expected_measurements.row(i).transpose() - expected_measurement_mean;
      expected_measurement_cov += ext_weights[i] * diff * diff.transpose();        //传播后的sigama点集协方差
    }

    // calculated transformed covariance
    MatrixXt sigma = MatrixXt::Zero(N + M, M);
    for (int i = 0; i < ext_sigma_points.rows(); i++) {
      auto diffA = (ext_sigma_points.row(i).transpose() - ext_mean_pred);
      auto diffB = (expected_measurements.row(i).transpose() - expected_measurement_mean);
      sigma += ext_weights[i] * (diffA * diffB.transpose());
    }

    kalman_gain = sigma * expected_measurement_cov.inverse();                       //计算卡尔曼增益

    VectorXt ext_mean = ext_mean_pred + kalman_gain * (measurement - expected_measurement_mean); //最优估计
    MatrixXt ext_cov = ext_cov_pred - kalman_gain * expected_measurement_cov * kalman_gain.transpose();    //最优估计的协方差

    mean = ext_mean.topLeftCorner(N, 1);
    cov = ext_cov.topLeftCorner(N, N);
  }

  const MatrixXt& getSigmaPoints() const { return sigma_points; }
  EIGEN_MAKE_ALIGNED_OPERATOR_NEW

private:
  T lambda;
  const int S; //sigma点个数
  VectorXt weights;
  MatrixXt sigma_points;
  VectorXt ext_weights;
  MatrixXt ext_sigma_points;
  MatrixXt expected_measurements;

private:
  /**
   * @brief compute sigma points
   * @param mean          mean
   * @param cov           covariance
   * @param sigma_points  calculated sigma points
   */
  void computeSigmaPoints(const VectorXt& mean, const MatrixXt& cov, MatrixXt& sigma_points) {
    const int n = mean.size();
    assert(cov.rows() == n && cov.cols() == n);

    Eigen::LLT<MatrixXt> llt;   //Cholesky分解，将对称正定矩阵表示成一个下三角矩阵L和其转置的乘积的分解 M = L*L.transpose()
    llt.compute((n + lambda) * cov);
    MatrixXt l = llt.matrixL();

    sigma_points.row(0) = mean;
    for (int i = 0; i < n; i++) {
      sigma_points.row(1 + i * 2) = mean + l.col(i);
      sigma_points.row(1 + i * 2 + 1) = mean - l.col(i);
    }
  }
};

#endif

ext: hpp


text:
/*
 * Tree.cpp
 *
 *  Created on: Sep 20, 2012
 *      Author: Chris
 *
 *   TODO: pruning of tree
 */

#include <iostream>
#include <cmath>
#include <boost/make_shared.hpp>

#include "LUtils.h"
#include "IOHelper.h"
#include "Tree.h"
#include "Node.h"

//Binary tree
Tree::Tree(int n, bool p, bool r, double w, int seed) :
		min_node(n), probability(p), regression(r), w1(w), rseed(seed) {
	root = boost::make_shared<Node>(0, 0.0);
	tree_size = 0;
	max_depth = 100;
	tnodecount = 0;
	entropy_loss = false;
	rng.setSeed(rseed);
}

//most important information
void Tree::printInfo() {
	cout << endl;
	if (regression) {
		cout << "REGRESSION Tree";
	} else {
		cout << "CLASSIFICATION Tree";
	}
	if (probability)
		cout << " - Returning class probabilities";
	cout << " - Minimum node size: " << min_node << endl;
}

//in future use interface mlmodel
//void Tree::train(const Eigen::MatrixXd &X, const Eigen::VectorXd &y, const bool verbose){};
//Eigen::VectorXd Tree::predict(const Eigen::MatrixXd &Xtest, const bool verbose){};

// creates recursively the tree, uses subset of features
void Tree::train(DataFrame &dataframe, const vector<int> &featList,
		const int nrFeat, const bool verbose) {
	//select features randomly
	if (verbose) cout<<"Training tree with random seed:"<<rng.seed<<endl;
	vector<int> featsubset = LUtils::sample(rng, nrFeat, dataframe.nrcols - 1,
			false);
	DataFrame::FeatureResult featResult = dataframe.findBestFeature(featsubset,
			entropy_loss);
	//Create a new root node
	root->feature = featResult.opt_feat;
	root->splitvalue = featResult.opt_split;
	root->impurity = featResult.loss;
	root->nameFeature = dataframe.header.at(featResult.opt_feat);
	root->nrsamples = dataframe.nrrows;
	createBranch(root, dataframe, nrFeat, verbose);
}

void Tree::train(DataFrame &dataframe, const bool verbose) {
	vector<int> featList(dataframe.nrcols - 1);
	for (unsigned i = 0; i < featList.size(); ++i) {
		featList[i] = i;
	}
	train(dataframe, featList, featList.size(), verbose);
}

//recursively insert nodes
void Tree::createBranch(boost::shared_ptr<Node> parentNode, DataFrame &dfsplit,
		const int nrFeat, bool verbose) {

	vector<int> featsubset = LUtils::sample(rng, nrFeat, dfsplit.nrcols - 1,
			false);

	if (verbose) {
		cout << "Feature subset: ";
		for (unsigned i = 0; i < featsubset.size(); ++i) {
			cout << " " << dfsplit.header[featsubset[i]];
		}
		cout << endl;
	}

	DataFrame leftDF;
	DataFrame rightDF;
	dfsplit.splitFrame(parentNode->splitvalue, parentNode->feature, leftDF,
			rightDF);
	tree_size++;
	//LEFT BRANCH
	if (verbose && leftDF.nrrows > 0) {
		cout << "...Creating left branch: Feature: "
				<< dfsplit.header[parentNode->feature] << " Value:"
				<< parentNode->splitvalue << " n:" << leftDF.nrrows
				<< " with prediction:" << leftDF.cm << endl;
		//leftDF.printSummary();
	}
	if (leftDF.nrrows == 0) {
		//happens if one of the nodes is "practically" pure
		if (verbose) {
			cout << "No data in left node, right node:" << rightDF.nrrows
					<< endl;
			cout << "Left node: Parent node is terminal." << endl;
		}
		parentNode->isTerminal = true;
		tnodecount++;
		return;
	} else if (leftDF.nrrows <= min_node || parentNode->depth + 1 > max_depth
			|| leftDF.distinct[leftDF.classCol] < 2) {
		if (verbose)
			cout << "Terminal node, cm: " << leftDF.cm << endl;
		boost::shared_ptr<Node> left = boost::make_shared<Node>(
				parentNode->depth + 1, leftDF.cm);
		left->isTerminal = true;
		left->nrsamples = leftDF.nrrows;
		parentNode->left = left;
		tnodecount++;
	} else {
		DataFrame::FeatureResult featResulta = leftDF.findBestFeature(
				featsubset, entropy_loss);
		boost::shared_ptr<Node> left = boost::make_shared<Node>(
				featResulta.opt_feat, featResulta.opt_split, featResulta.loss,
				parentNode->depth + 1, leftDF.header[featResulta.opt_feat],
				leftDF.nrrows, leftDF.cm);
		parentNode->left = left;
		createBranch(left, leftDF, nrFeat, verbose);
	}

	//RIGHT BRANCH
	if (verbose && rightDF.nrrows > 0) {
		cout << "...Creating right branch: Feature: "
				<< dfsplit.header[parentNode->feature] << " Value:"
				<< parentNode->splitvalue << " n:" << rightDF.nrrows
				<< " with prediction:" << rightDF.cm << endl;
		//rightDF.printSummary();
	}
	if (rightDF.nrrows == 0) {
		//happens if one of the nodes is "practically" pure
		if (verbose) {
			cout << "No data in right node,  left node:" << leftDF.nrrows
					<< endl;
			cout << "Right node: Parent node is terminal." << endl;
		}
		parentNode->isTerminal = true;
		tnodecount++;
		return;
	} else if (rightDF.nrrows <= min_node || parentNode->depth + 1 > max_depth
			|| rightDF.distinct[rightDF.classCol] < 2) {
		if (verbose)
			cout << "Terminal node, cm: " << rightDF.cm << endl;
		boost::shared_ptr<Node> right = boost::make_shared<Node>(
				parentNode->depth + 1, rightDF.cm);
		right->isTerminal = true;

		right->nrsamples = rightDF.nrrows;
		parentNode->right = right;
		tnodecount++;
	} else {
		DataFrame::FeatureResult featResultb = rightDF.findBestFeature(
				featsubset, entropy_loss);
		if (verbose)
			cout << "Terminal node, cm: " << rightDF.cm << endl;
		boost::shared_ptr<Node> right = boost::make_shared<Node>(
				featResultb.opt_feat, featResultb.opt_split, featResultb.loss,
				parentNode->depth + 1, rightDF.header[featResultb.opt_feat],
				rightDF.nrrows, rightDF.cm);
		parentNode->right = right;
		createBranch(right, rightDF, nrFeat, verbose);

	}
	//if we reach this point, we should return
	return;
}

void Tree::showTree(const bool verbose) {
	cout << endl << "###Printing Tree Structure" << endl;
	root->showChildren(verbose);
}

string Tree::tree2string() {
	//cout << endl << "###Printing Simpified Tree Structure" << endl;
	stringstream ss;
	ss << "# rftree"<<endl;
	ss << "2 " << root->feature << " " << root->splitvalue << endl;
	vector<boost::shared_ptr<Node> > parentnodes;
	parentnodes.push_back(root);
	//we have to re-sort the binary tree
	for (int i = 1; i < 5; ++i) {
		vector<boost::shared_ptr<Node> > actualnodes;
		int n_nodes = pow(2, i);
		//cout << "LEVEL:" << i << " NR NODES:" << n_nodes << endl;
		for (int j = 0; j < n_nodes; ++j) {
			boost::shared_ptr<Node> parent = parentnodes[j / 2];
			if (parent->isTerminal) {
							continue;
						}
			boost::shared_ptr<Node> node;
			int id = pow(2, i) + j;
			if (j % 2 == 0) {
				node = parent->left;
			} else {
				node = parent->right;
			}
			if (!node->isTerminal) {
				int leftid = 2 * id;
				ss << leftid << " " << node->feature << " "
						<< node->splitvalue << endl;
				actualnodes.push_back(node);
			} else {
				ss << "0 NA " << node->cm << endl;
				actualnodes.push_back(node);
			}
		}
		parentnodes = actualnodes;
	}
	return ss.str();
}

//prediction for external data
Eigen::VectorXd Tree::predict(DataFrame &testSet, const bool verbose) {
//starting at root level, then call makePredictions recursively
	double pi = 0.0;
	Eigen::VectorXd p(testSet.nrrows);
	for (int obs = 0; obs < testSet.nrrows; obs++) {
		//in some rare case we do have a terminal node at the 0th level
		if (root->isTerminal) {
			pi = root->cm;
		} else if (testSet.matrix(obs, root->feature) < root->splitvalue) {
			//makePrediction leftDF
			pi = makePrediction(testSet, root->left, obs, verbose);
		} else {
			//makePrediction rightDF
			pi = makePrediction(testSet, root->right, obs, verbose);
		}
		if (!probability && !regression) {
			//cout<<"Rounding "<<pi<<" to "<<LUtils::round(pi)<<endl;
			pi = LUtils::round(pi);
		}
		p(obs) = pi;
		if (verbose) {
			cout << "p(" << obs << "): " << p(obs) << " order:"
					<< testSet.order[obs] <<endl;
		}

	}
//original order for p
	Eigen::VectorXd tmp(testSet.nrrows);
	int idx_orig = 0;
	for (int i = 0; i < testSet.nrrows; i++) {
		idx_orig = testSet.order.at(i);
		tmp(idx_orig) = p(i);
	}
	for (int i = 0; i < testSet.nrrows; i++) {
		p(i) = tmp(i);
	}
//after prediction we have to re-establish the original order
	testSet.restoreOrder();
	if (verbose)
		cout << "###Tree size:" << tree_size + 1 << " nodes." << endl;
	return p;

}

//make prediction for a certain row, recursive until terminal node is reached
double Tree::makePrediction(const DataFrame &testset,
		const boost::shared_ptr<Node> localNode, const int obs,
		const bool verbose) {
	double t = 0.0;
	if (localNode->isTerminal) {
		if (verbose) {
			cout << " cm(Node" << localNode->nodeID << "):";
		}
		return localNode->cm;
	}
	if (testset.matrix(obs, localNode->feature) < localNode->splitvalue) {
		//makePrediction leftDF
		t = makePrediction(testset, localNode->left, obs, verbose);
	} else {
		//makePrediction rightDF
		t = makePrediction(testset, localNode->right, obs, verbose);
	}
//if we reach this end we go upwards again...
	return t;
}

Tree::~Tree() {
}


text:
#include <gtest/gtest.h>

#include <boost/fiber/all.hpp>

class TestAsync : public ::testing::Test
{
};

TEST_F(TestAsync, FibersHello)
{
    int i = 1;

    boost::fibers::fiber f([&i] { i=2; });
    f.join();

    ASSERT_EQ(i, 2);
}

ext: cc

max_stars_repo_name: ryanolson/yais

max_issues_repo_name: ryanolson/yais

max_forks_repo_name: ryanolson/yais


text:
//
// detail/config.hpp
// ~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2010 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//

#ifndef BOOST_ASIO_DETAIL_CONFIG_HPP
#define BOOST_ASIO_DETAIL_CONFIG_HPP

#include <boost/config.hpp>

// Default to a header-only implementation. The user must specifically request
// separate compilation by defining either BOOST_ASIO_SEPARATE_COMPILATION or
// BOOST_ASIO_DYN_LINK (as a DLL/shared library implies separate compilation).
#if !defined(BOOST_ASIO_HEADER_ONLY)
# if !defined(BOOST_ASIO_SEPARATE_COMPILATION)
#  if !defined(BOOST_ASIO_DYN_LINK)
#   define BOOST_ASIO_HEADER_ONLY
#  endif // !defined(BOOST_ASIO_DYN_LINK)
# endif // !defined(BOOST_ASIO_SEPARATE_COMPILATION)
#endif // !defined(BOOST_ASIO_HEADER_ONLY)

#if defined(BOOST_ASIO_HEADER_ONLY)
# define BOOST_ASIO_DECL inline
#else // defined(BOOST_ASIO_HEADER_ONLY)
# if defined(BOOST_HAS_DECLSPEC)
// We need to import/export our code only if the user has specifically asked
// for it by defining BOOST_ASIO_DYN_LINK.
#  if defined(BOOST_ASIO_DYN_LINK)
// Export if this is our own source, otherwise import.
#   if defined(BOOST_ASIO_SOURCE)
#    define BOOST_ASIO_DECL __declspec(dllexport)
#   else // defined(BOOST_ASIO_SOURCE)
#    define BOOST_ASIO_DECL __declspec(dllimport)
#   endif // defined(BOOST_ASIO_SOURCE)
#  endif // defined(BOOST_ASIO_DYN_LINK)
# endif // defined(BOOST_HAS_DECLSPEC)
#endif // defined(BOOST_ASIO_HEADER_ONLY)

// If BOOST_ASIO_DECL isn't defined yet define it now.
#if !defined(BOOST_ASIO_DECL)
# define BOOST_ASIO_DECL
#endif // !defined(BOOST_ASIO_DECL)

// Windows: target OS version.
#if defined(BOOST_WINDOWS) || defined(__CYGWIN__)
# if !defined(_WIN32_WINNT) && !defined(_WIN32_WINDOWS)
#  if defined(_MSC_VER) || defined(__BORLANDC__)
#   pragma message( \
  "Please define _WIN32_WINNT or _WIN32_WINDOWS appropriately. For example:\n"\
  "- add -D_WIN32_WINNT=0x0501 to the compiler command line; or\n"\
  "- add _WIN32_WINNT=0x0501 to your project's Preprocessor Definitions.\n"\
  "Assuming _WIN32_WINNT=0x0501 (i.e. Windows XP target).")
#  else // defined(_MSC_VER) || defined(__BORLANDC__)
#   warning Please define _WIN32_WINNT or _WIN32_WINDOWS appropriately.
#   warning For example, add -D_WIN32_WINNT=0x0501 to the compiler command line.
#   warning Assuming _WIN32_WINNT=0x0501 (i.e. Windows XP target).
#  endif // defined(_MSC_VER) || defined(__BORLANDC__)
#  define _WIN32_WINNT 0x0501
# endif // !defined(_WIN32_WINNT) && !defined(_WIN32_WINDOWS)
# if defined(_MSC_VER)
#  if defined(_WIN32) && !defined(WIN32)
#   if !defined(_WINSOCK2API_)
#    define WIN32 // Needed for correct types in winsock2.h
#   else // !defined(_WINSOCK2API_)
#    error Please define the macro WIN32 in your compiler options
#   endif // !defined(_WINSOCK2API_)
#  endif // defined(_WIN32) && !defined(WIN32)
# endif // defined(_MSC_VER)
# if defined(__BORLANDC__)
#  if defined(__WIN32__) && !defined(WIN32)
#   if !defined(_WINSOCK2API_)
#    define WIN32 // Needed for correct types in winsock2.h
#   else // !defined(_WINSOCK2API_)
#    error Please define the macro WIN32 in your compiler options
#   endif // !defined(_WINSOCK2API_)
#  endif // defined(__WIN32__) && !defined(WIN32)
# endif // defined(__BORLANDC__)
# if defined(__CYGWIN__)
#  if !defined(__USE_W32_SOCKETS)
#   error You must add -D__USE_W32_SOCKETS to your compiler options.
#  endif // !defined(__USE_W32_SOCKETS)
# endif // defined(__CYGWIN__)
#endif // defined(BOOST_WINDOWS) || defined(__CYGWIN__)

// Windows: minimise header inclusion.
#if defined(BOOST_WINDOWS) || defined(__CYGWIN__)
# if !defined(BOOST_ASIO_NO_WIN32_LEAN_AND_MEAN)
#  if !defined(WIN32_LEAN_AND_MEAN)
#   define WIN32_LEAN_AND_MEAN
#  endif // !defined(WIN32_LEAN_AND_MEAN)
# endif // !defined(BOOST_ASIO_NO_WIN32_LEAN_AND_MEAN)
#endif // defined(BOOST_WINDOWS) || defined(__CYGWIN__)

// Windows: suppress definition of "min" and "max" macros.
#if defined(BOOST_WINDOWS) || defined(__CYGWIN__)
# if !defined(BOOST_ASIO_NO_NOMINMAX)
#  if !defined(NOMINMAX)
#   define NOMINMAX 1
#  endif // !defined(NOMINMAX)
# endif // !defined(BOOST_ASIO_NO_NOMINMAX)
#endif // defined(BOOST_WINDOWS) || defined(__CYGWIN__)

// Windows: IO Completion Ports.
#if defined(BOOST_WINDOWS) || defined(__CYGWIN__)
# if defined(_WIN32_WINNT) && (_WIN32_WINNT >= 0x0400)
#  if !defined(UNDER_CE)
#   if !defined(BOOST_ASIO_DISABLE_IOCP)
#    define BOOST_ASIO_HAS_IOCP 1
#   endif // !defined(BOOST_ASIO_DISABLE_IOCP)
#  endif // !defined(UNDER_CE)
# endif // defined(_WIN32_WINNT) && (_WIN32_WINNT >= 0x0400)
#endif // defined(BOOST_WINDOWS) || defined(__CYGWIN__)

// Linux: epoll, eventfd and timerfd.
#if defined(__linux__)
# include <linux/version.h>
# if !defined(BOOST_ASIO_DISABLE_EPOLL)
#  if LINUX_VERSION_CODE >= KERNEL_VERSION(2,5,45)
#   define BOOST_ASIO_HAS_EPOLL 1
#  endif // LINUX_VERSION_CODE >= KERNEL_VERSION(2,5,45)
# endif // !defined(BOOST_ASIO_DISABLE_EVENTFD)
# if !defined(BOOST_ASIO_DISABLE_EVENTFD)
#  if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,22)
#   define BOOST_ASIO_HAS_EVENTFD 1
#  endif // LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,22)
# endif // !defined(BOOST_ASIO_DISABLE_EVENTFD)
# if defined(BOOST_ASIO_HAS_EPOLL)
#  if (__GLIBC__ > 2) || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 8)
#   define BOOST_ASIO_HAS_TIMERFD 1
#  endif // (__GLIBC__ > 2) || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 8)
# endif // defined(BOOST_ASIO_HAS_EPOLL)
#endif // defined(__linux__)

// Mac OS X, FreeBSD, NetBSD, OpenBSD: kqueue.
#if (defined(__MACH__) && defined(__APPLE__)) \
  || defined(__FreeBSD__) \
  || defined(__NetBSD__) \
  || defined(__OpenBSD__)
# if !defined(BOOST_ASIO_DISABLE_KQUEUE)
#  define BOOST_ASIO_HAS_KQUEUE 1
# endif // !defined(BOOST_ASIO_DISABLE_KQUEUE)
#endif // (defined(__MACH__) && defined(__APPLE__))
       //   || defined(__FreeBSD__)
       //   || defined(__NetBSD__)
       //   || defined(__OpenBSD__)

// Solaris: /dev/poll.
#if defined(__sun)
# if !defined(BOOST_ASIO_DISABLE_DEV_POLL)
#  define BOOST_ASIO_HAS_DEV_POLL 1
# endif // !defined(BOOST_ASIO_DISABLE_DEV_POLL)
#endif // defined(__sun)

// Serial ports.
#if defined(BOOST_ASIO_HAS_IOCP) \
   || !defined(BOOST_WINDOWS) && !defined(__CYGWIN__)
# if !defined(__SYMBIAN32__)
#  if !defined(BOOST_ASIO_DISABLE_SERIAL_PORT)
#   define BOOST_ASIO_HAS_SERIAL_PORT 1
#  endif // !defined(BOOST_ASIO_DISABLE_SERIAL_PORT)
# endif // !defined(__SYMBIAN32__)
#endif // defined(BOOST_ASIO_HAS_IOCP)
       //   || !defined(BOOST_WINDOWS) && !defined(__CYGWIN__)

// Windows: stream handles.
#if !defined(BOOST_ASIO_DISABLE_WINDOWS_STREAM_HANDLE)
# if defined(BOOST_ASIO_HAS_IOCP)
#  define BOOST_ASIO_HAS_WINDOWS_STREAM_HANDLE 1
# endif // defined(BOOST_ASIO_HAS_IOCP)
#endif // !defined(BOOST_ASIO_DISABLE_WINDOWS_STREAM_HANDLE)

// Windows: random access handles.
#if !defined(BOOST_ASIO_DISABLE_WINDOWS_RANDOM_ACCESS_HANDLE)
# if defined(BOOST_ASIO_HAS_IOCP)
#  define BOOST_ASIO_HAS_WINDOWS_RANDOM_ACCESS_HANDLE 1
# endif // defined(BOOST_ASIO_HAS_IOCP)
#endif // !defined(BOOST_ASIO_DISABLE_WINDOWS_RANDOM_ACCESS_HANDLE)

// Windows: OVERLAPPED wrapper.
#if !defined(BOOST_ASIO_DISABLE_WINDOWS_OVERLAPPED_PTR)
# if defined(BOOST_ASIO_HAS_IOCP)
#  define BOOST_ASIO_HAS_WINDOWS_OVERLAPPED_PTR 1
# endif // defined(BOOST_ASIO_HAS_IOCP)
#endif // !defined(BOOST_ASIO_DISABLE_WINDOWS_OVERLAPPED_PTR)

// POSIX: stream-oriented file descriptors.
#if !defined(BOOST_ASIO_DISABLE_POSIX_STREAM_DESCRIPTOR)
# if !defined(BOOST_WINDOWS) && !defined(__CYGWIN__)
#  define BOOST_ASIO_HAS_POSIX_STREAM_DESCRIPTOR 1
# endif // !defined(BOOST_WINDOWS) && !defined(__CYGWIN__)
#endif // !defined(BOOST_ASIO_DISABLE_POSIX_STREAM_DESCRIPTOR)

// UNIX domain sockets.
#if !defined(BOOST_ASIO_DISABLE_LOCAL_SOCKETS)
# if !defined(BOOST_WINDOWS) && !defined(__CYGWIN__)
#  define BOOST_ASIO_HAS_LOCAL_SOCKETS 1
# endif // !defined(BOOST_WINDOWS) && !defined(__CYGWIN__)
#endif // !defined(BOOST_ASIO_DISABLE_LOCAL_SOCKETS)

#endif // BOOST_ASIO_DETAIL_CONFIG_HPP

max_stars_repo_name: RaptDept/slimtune

max_issues_repo_name: RaptDept/slimtune

max_forks_repo_name: RaptDept/slimtune


text:
/* -*- Mode: c++; tab-width: 2; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/* vim:set softtabstop=2 shiftwidth=2 tabstop=2 expandtab: */
/*
 * Software License Agreement (BSD License)
 *
 * Copyright (c) 2014, Autonomous Intelligent Systems Group, Rheinische
 * Friedrich-Wilhelms-Universität Bonn
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the Rheinische Friedrich-Wilhelms-Universität Bonn
 *       nor the names of its contributors may be used to endorse or promote
 *       products derived from this software without specific prior written
 *       permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#define DEBUG_MASK 0

#include "image_mask.h"

#include <set>

#include <boost/make_shared.hpp>
#include <boost/iterator/iterator_concepts.hpp>

#include <opencv2/highgui/highgui.hpp> // For CV_LOAD_IMAGE_GRAYSCALE

#include <ros/console.h>

namespace ros_openni2_multicam
{

  ImageMask::ImageMask(std::string filename) : m_useMask(true)
  {
    cv::Mat mask_image(cv::imread(filename, (CV_LOAD_IMAGE_GRAYSCALE | CV_LOAD_IMAGE_ANYDEPTH)));
    if (!mask_image.data){
      ROS_WARN_STREAM("Could not find image file '" << filename << "'. Mask will be disabled");
      m_useMask = false;
      return;
    }
    m_mask.create(mask_image.rows, mask_image.cols);
    for (int y = 0; y < mask_image.rows; ++y){
      for (int x = 0; x < mask_image.cols; ++x){
        if (mask_image.at<uint8_t>(y, x) > UCHAR_MAX/2){
          m_mask(y, x) = 0xFFFF;
        }else{
          m_mask(y, x) = 0x0000;
        }
      }
    }
#if DEBUG_MASK
    cv::namedWindow( "Original", CV_WINDOW_AUTOSIZE );
    cv::namedWindow( "Mask", CV_WINDOW_AUTOSIZE );
    cv::namedWindow( "Masked", CV_WINDOW_AUTOSIZE );
#endif
  }

  ImageMask::~ImageMask()
  {
  }

  void ImageMask::maskImage(cv::Mat& image)
  {
    if (m_useMask) {
      if (image.cols == m_mask.cols && image.rows == m_mask.rows){
#if DEBUG_MASK
        cv::imshow("Original", image);
#endif
        cv::bitwise_and(image, m_mask, image);
#if DEBUG_MASK
        cv::imshow("Mask", m_mask);
        cv::imshow("Masked", image);
        cv::waitKey(10);
#endif
      } else {
        ROS_ERROR("Image and Mask do not have the same size!");
      }
    } else {
      ROS_DEBUG_ONCE("I do not mask.");
    }
  }

}


text:
#include <mpi.h>
#include <sys/time.h>
#include <iostream>
#include <functional>
#include <algorithm>
#include <vector>
#include <sstream>
#ifdef NOTR1
        #include <boost/tr1/memory.hpp>
#else
        #include <tr1/memory>
#endif
#include "../SpParVec.h"
#include "../SpTuples.h"
#include "../SpDCCols.h"
#include "../SpParMat.h"
#include "../DenseParMat.h"
#include "../DenseParVec.h"
#include "../FullyDistVec.h"
#include "../FullyDistSpVec.h"
#include "../ParFriends.h"

using namespace std;
#define NOGEMM

// Simple helper class for declarations: Just the numerical type is templated
// The index type and the sequential matrix type stays the same for the whole code
// In this case, they are "int" and "SpDCCols"
template <class NT>
class PSpMat
{
public:
	typedef SpDCCols < int64_t, NT > DCCols;
	typedef SpParMat < int64_t, NT, DCCols > MPI_DCCols;
};

int main(int argc, char* argv[])
{
	MPI::Init(argc, argv);
	int nprocs = MPI::COMM_WORLD.Get_size();
	int myrank = MPI::COMM_WORLD.Get_rank();

	if(argc < 6)
	{
		if(myrank == 0)
		{
			cout << "Usage: ./MultTest <MatrixA> <MatrixB> <MatrixC> <vecX> <vecY>" << endl;
			cout << "<MatrixA>,<MatrixB>,<MatrixC> are absolute addresses, and files should be in triples format" << endl;
		}
		MPI::Finalize();
		return -1;
	}
	{
		string Aname(argv[1]);
		string Bname(argv[2]);
		string Cname(argv[3]);
		string V1name(argv[4]);
		string V2name(argv[5]);

		ifstream inputA(Aname.c_str());
		ifstream inputB(Bname.c_str());
		ifstream inputC(Cname.c_str());
		ifstream vecinpx(V1name.c_str());
		ifstream vecinpy(V2name.c_str());

		MPI::COMM_WORLD.Barrier();

		typedef PlusTimesSRing<double, double> PTDOUBLEDOUBLE;
		typedef SelectMaxSRing<bool, int64_t> SR;

		PSpMat<double>::MPI_DCCols A, B, C, CControl;	// construct objects
		FullyDistVec<int64_t, double> ycontrol, x;
		FullyDistSpVec<int64_t, double> spycontrol, spx;

		A.ReadDistribute(inputA, 0);
#ifndef NOGEMM
		B.ReadDistribute(inputB, 0);
		CControl.ReadDistribute(inputC, 0);
#endif
		x.ReadDistribute(vecinpx, 0);
		spx.ReadDistribute(vecinpx, 0);
		ycontrol.ReadDistribute(vecinpy,0);
		spycontrol.ReadDistribute(vecinpy,0);

		FullyDistVec<int64_t, double> y = SpMV<PTDOUBLEDOUBLE>(A, x);
		if (ycontrol == y)
		{
			SpParHelper::Print("Dense SpMV (fully dist) working correctly\n");
		}
		else
		{
			SpParHelper::Print("ERROR in Dense SpMV, go fix it!\n");
		}

		FullyDistSpVec<int64_t, double> spy = SpMV<PTDOUBLEDOUBLE>(A, spx);

		if (spycontrol == spy)
		{
			SpParHelper::Print("Sparse SpMV (fully dist) working correctly\n");
		}
		else
		{
			SpParHelper::Print("ERROR in Sparse SpMV, go fix it!\n");
		}
#ifndef NOGEMM
		C = Mult_AnXBn_Synch<PTDOUBLEDOUBLE>(A,B);
		if (CControl == C)
		{
			SpParHelper::Print("Synchronous Multiplication working correctly\n");
		}
		else
		{
			SpParHelper::Print("ERROR in Synchronous Multiplication, go fix it!\n");
		}

		C = Mult_AnXBn_DoubleBuff<PTDOUBLEDOUBLE>(A,B);
		if (CControl == C)
		{
			SpParHelper::Print("Double buffered multiplication working correctly\n");
		}
		else
		{
			SpParHelper::Print("ERROR in double buffered multiplication, go fix it!\n");
		}
#endif
		OptBuf<int64_t, int64_t> optbuf;
		PSpMat<bool>::MPI_DCCols ABool(A);

		spx.Apply(bind1st (multiplies<double>(), 100));
		FullyDistSpVec<int64_t, int64_t> spxint64 (spx);
		FullyDistSpVec<int64_t, int64_t> spyint64 = SpMV<SR>(ABool, spxint64, false);

		ABool.OptimizeForGraph500(optbuf);
		FullyDistSpVec<int64_t, int64_t> spyint64buf = SpMV<SR>(ABool, spxint64, false, optbuf);

		if (spyint64 == spyint64buf)
		{
			SpParHelper::Print("Graph500 Optimizations are correct\n");
		}
		else
		{
			SpParHelper::Print("ERROR in graph500 optimizations, go fix it!\n");
		}
		ABool.ActivateThreading(4);
		FullyDistSpVec<int64_t, int64_t> spyint64_threaded = SpMV<SR>(ABool, spxint64, false);

		if (spyint64 == spyint64_threaded)
		{
			SpParHelper::Print("Multithreaded Sparse SpMV works\n");
		}
		else
		{
			SpParHelper::Print("ERROR in multithreaded sparse SpMV, go fix it!\n");
		}

		inputA.clear();
		inputA.close();
		inputB.clear();
		inputB.close();
		inputC.clear();
		inputC.close();
		vecinpx.clear();
		vecinpx.close();
		vecinpy.clear();
		vecinpy.close();
	}
	MPI::Finalize();
	return 0;
}

max_stars_repo_name: shoaibkamil/OLD-kdt-specializer

max_issues_repo_name: shoaibkamil/OLD-kdt-specializer

max_forks_repo_name: shoaibkamil/OLD-kdt-specializer


text:
/*
 * Copyright (c) 2015 University of Basel
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 *
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 *
 * Neither the name of the project's author nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
 * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */

#include <boost/program_options.hpp>

#include <itkDataManager.h>
#include <itkDirectory.h>
#include <itkImageFileReader.h>
#include <itkPCAModelBuilder.h>
#include <itkStandardImageRepresenter.h>
#include <itkStatisticalModel.h>

#include "utils/statismo-build-models-utils.h"

namespace po = boost::program_options;
using namespace std;

struct programOptions {
    bool bDisplayHelp;
    string strDataListFile;
    string strOutputFileName;
    float fNoiseVariance;
    unsigned uNumberOfDimensions;
};

po::options_description initializeProgramOptions(programOptions& poParameters);
bool isOptionsConflictPresent(programOptions& opt);
template<unsigned Dimensions>
void buildAndSaveDeformationModel(programOptions opt);

int main(int argc, char** argv) {
    programOptions poParameters;

    po::positional_options_description optPositional;
    optPositional.add("output-file", 1);
    po::options_description optAllOptions = initializeProgramOptions(poParameters);

    po::variables_map vm;
    try {
        po::parsed_options parsedOptions = po::command_line_parser(argc, argv).options(optAllOptions).positional(optPositional).run();
        po::store(parsedOptions, vm);
        po::notify(vm);
    } catch (po::error& e) {
        cerr << "An exception occurred while parsing the Command line:"<<endl;
        cerr << e.what() << endl;
        return EXIT_FAILURE;
    }

    if (poParameters.bDisplayHelp == true) {
        cout << optAllOptions << endl;
        return EXIT_SUCCESS;
    }
    if (isOptionsConflictPresent(poParameters) == true)	{
        cerr << "A conflict in the options exists or insufficient options were set." << endl;
        cout << optAllOptions << endl;
        return EXIT_FAILURE;
    }

    try {
        if (poParameters.uNumberOfDimensions == 2) {
            buildAndSaveDeformationModel<2>(poParameters);
        } else {
            buildAndSaveDeformationModel<3>(poParameters);
        }

    } catch (ifstream::failure & e) {
        cerr << "Could not read the data-list:" << endl;
        cerr << e.what() << endl;
        return EXIT_FAILURE;
    } catch (itk::ExceptionObject & e) {
        cerr << "Could not build the model:" << endl;
        cerr << e.what() << endl;
        return EXIT_FAILURE;
    }

    return EXIT_SUCCESS;
}

bool isOptionsConflictPresent(programOptions& opt) {
    if (opt.strDataListFile == "" || opt.strOutputFileName == "" ) {
        return true;
    }

    if (opt.strDataListFile == opt.strOutputFileName) {
        return true;
    }

    if (opt.fNoiseVariance < 0) {
        return true;
    }

    if (opt.uNumberOfDimensions != 2 && opt.uNumberOfDimensions != 3) {
        return true;
    }

    return false;
}

template<unsigned Dimensions>
void buildAndSaveDeformationModel(programOptions opt) {
    typedef itk::Vector<float, Dimensions> VectorPixelType;
    typedef itk::Image<VectorPixelType, Dimensions> ImageType;
    typedef itk::StandardImageRepresenter<VectorPixelType, Dimensions > RepresenterType;
    typename RepresenterType::Pointer representer = RepresenterType::New();

    typedef itk::DataManager<ImageType> DataManagerType;
    typename DataManagerType::Pointer dataManager = DataManagerType::New();

    StringList fileNames = getFileList(opt.strDataListFile);

    typedef itk::ImageFileReader<ImageType> ImageReaderType;
    typedef vector<typename ImageReaderType::Pointer> ImageReaderList;
    ImageReaderList images;
    images.reserve(fileNames.size());

    for (StringList::const_iterator it = fileNames.begin(); it != fileNames.end(); ++it) {
        typename ImageReaderType::Pointer reader = ImageReaderType::New();
        reader->SetFileName(it->c_str());
        reader->Update();
        //itk::PCAModelBuilder is not a Filter in the ITK world, so the pipeline would not get executed if its main method is called. So the pipeline before calling itk::PCAModelBuilder must be executed by the means of calls to Update() (at least for last elements needed by itk::PCAModelBuilder).
        images.push_back(reader);
    }

    if (images.size() == 0) {
        itkGenericExceptionMacro( << "No Data was loaded and thus the model can't be built.");
    }
    typename  ImageReaderType::Pointer referenceReader = *images.begin();
    representer->SetReference(referenceReader->GetOutput());
    dataManager->SetRepresenter(representer);

    for (typename ImageReaderList::const_iterator it = images.begin(); it != images.end(); ++it) {
        typename ImageReaderType::Pointer reader = *it;
        dataManager->AddDataset(reader->GetOutput(), reader->GetFileName().c_str());
    }

    typedef itk::StatisticalModel<ImageType> StatisticalModelType;
    typename StatisticalModelType::Pointer model;

    typedef itk::PCAModelBuilder<ImageType> ModelBuilderType;
    typename ModelBuilderType::Pointer pcaModelBuilder = ModelBuilderType::New();
    model = pcaModelBuilder->BuildNewModel(dataManager->GetData(), opt.fNoiseVariance);
    model->Save(opt.strOutputFileName.c_str());
}

po::options_description initializeProgramOptions(programOptions& poParameters) {
    po::options_description optMandatory("Mandatory options");
    optMandatory.add_options()
    ("data-list,l", po::value<string>(&poParameters.strDataListFile), "File containing a list of meshes to build the deformation model from")
    ("output-file,o", po::value<string>(&poParameters.strOutputFileName), "Name of the output file")
    ("dimensionality,d", po::value<unsigned>(&poParameters.uNumberOfDimensions)->default_value(3), "Dimensionality of the input images in the data list")
    ;
    po::options_description optAdditional("Optional options");
    optAdditional.add_options()
    ("noise,n", po::value<float>(&poParameters.fNoiseVariance)->default_value(0), "Noise variance of the PPCA model")
    ("help,h", po::bool_switch(&poParameters.bDisplayHelp), "Display this help message")
    ;

    po::options_description optAllOptions;
    optAllOptions.add(optMandatory).add(optAdditional);
    return optAllOptions;
}

ext: cxx

max_stars_repo_name: thewtex/statismo

max_issues_repo_name: thewtex/statismo

max_forks_repo_name: thewtex/statismo


text:
//
// detail/impl/reactive_serial_port_service.ipp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2015 Christopher M. Kohlhoff (chris at kohlhoff dot com)
// Copyright (c) 2008 Rep Invariant Systems, Inc. (info@repinvariant.com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//

#ifndef BOOST_ASIO_DETAIL_IMPL_REACTIVE_SERIAL_PORT_SERVICE_IPP
#define BOOST_ASIO_DETAIL_IMPL_REACTIVE_SERIAL_PORT_SERVICE_IPP

#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)

#include <boost/asio/detail/config.hpp>

#if defined(BOOST_ASIO_HAS_SERIAL_PORT)
#if !defined(BOOST_ASIO_WINDOWS) && !defined(__CYGWIN__)

#include <cstring>
#include <boost/asio/detail/reactive_serial_port_service.hpp>

#include <boost/asio/detail/push_options.hpp>

namespace boost {
namespace asio {
namespace detail {

reactive_serial_port_service::reactive_serial_port_service(
    boost::asio::io_service& io_service)
  : descriptor_service_(io_service)
{
}

void reactive_serial_port_service::shutdown_service()
{
  descriptor_service_.shutdown_service();
}

boost::system::error_code reactive_serial_port_service::open(
    reactive_serial_port_service::implementation_type& impl,
    const std::string& device, boost::system::error_code& ec)
{
  if (is_open(impl))
  {
    ec = boost::asio::error::already_open;
    return ec;
  }

  descriptor_ops::state_type state = 0;
  int fd = descriptor_ops::open(device.c_str(),
      O_RDWR | O_NONBLOCK | O_NOCTTY, ec);
  if (fd < 0)
    return ec;

  int s = descriptor_ops::fcntl(fd, F_GETFL, ec);
  if (s >= 0)
    s = descriptor_ops::fcntl(fd, F_SETFL, s | O_NONBLOCK, ec);
  if (s < 0)
  {
    boost::system::error_code ignored_ec;
    descriptor_ops::close(fd, state, ignored_ec);
    return ec;
  }

  // Set up default serial port options.
  termios ios;
  errno = 0;
  s = descriptor_ops::error_wrapper(::tcgetattr(fd, &ios), ec);
  if (s >= 0)
  {
#if defined(_BSD_SOURCE)
    ::cfmakeraw(&ios);
#else
    ios.c_iflag &= ~(IGNBRK | BRKINT | PARMRK
        | ISTRIP | INLCR | IGNCR | ICRNL | IXON);
    ios.c_oflag &= ~OPOST;
    ios.c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
    ios.c_cflag &= ~(CSIZE | PARENB);
    ios.c_cflag |= CS8;
#endif
    ios.c_iflag |= IGNPAR;
    ios.c_cflag |= CREAD | CLOCAL;
    errno = 0;
    s = descriptor_ops::error_wrapper(::tcsetattr(fd, TCSANOW, &ios), ec);
  }
  if (s < 0)
  {
    boost::system::error_code ignored_ec;
    descriptor_ops::close(fd, state, ignored_ec);
    return ec;
  }

  // We're done. Take ownership of the serial port descriptor.
  if (descriptor_service_.assign(impl, fd, ec))
  {
    boost::system::error_code ignored_ec;
    descriptor_ops::close(fd, state, ignored_ec);
  }

  return ec;
}

boost::system::error_code reactive_serial_port_service::do_set_option(
    reactive_serial_port_service::implementation_type& impl,
    reactive_serial_port_service::store_function_type store,
    const void* option, boost::system::error_code& ec)
{
  termios ios;
  errno = 0;
  descriptor_ops::error_wrapper(::tcgetattr(
        descriptor_service_.native_handle(impl), &ios), ec);
  if (ec)
    return ec;

  if (store(option, ios, ec))
    return ec;

  errno = 0;
  descriptor_ops::error_wrapper(::tcsetattr(
        descriptor_service_.native_handle(impl), TCSANOW, &ios), ec);
  return ec;
}

boost::system::error_code reactive_serial_port_service::do_get_option(
    const reactive_serial_port_service::implementation_type& impl,
    reactive_serial_port_service::load_function_type load,
    void* option, boost::system::error_code& ec) const
{
  termios ios;
  errno = 0;
  descriptor_ops::error_wrapper(::tcgetattr(
        descriptor_service_.native_handle(impl), &ios), ec);
  if (ec)
    return ec;

  return load(option, ios, ec);
}

} // namespace detail
} // namespace asio
} // namespace boost

#include <boost/asio/detail/pop_options.hpp>

#endif // !defined(BOOST_ASIO_WINDOWS) && !defined(__CYGWIN__)
#endif // defined(BOOST_ASIO_HAS_SERIAL_PORT)

#endif // BOOST_ASIO_DETAIL_IMPL_REACTIVE_SERIAL_PORT_SERVICE_IPP

ext: ipp

max_stars_repo_name: LazyPlanet/MX-Client

max_issues_repo_name: LazyPlanet/MX-Client

max_forks_repo_name: LazyPlanet/MX-Client


text:
#include "string.h"

#include <possumwood_sdk/app.h>

#include <boost/algorithm/string/join.hpp>
#include <boost/algorithm/string/predicate.hpp>

string_ui::string_ui() {
	m_lineEdit = new QLineEdit();

	m_lineEditConnection =
	    QObject::connect(m_lineEdit, &QLineEdit::editingFinished, [this]() -> void { callValueChangedCallbacks(); });
}

string_ui::~string_ui() {
	QObject::disconnect(m_lineEditConnection);
}

void string_ui::get(std::string& value) const {
	value = m_lineEdit->text().toStdString();
}

void string_ui::set(const std::string& value) {
	const bool bs = m_lineEdit->blockSignals(true);
	m_lineEdit->setText(value.c_str());
	m_lineEdit->blockSignals(bs);
}

QWidget* string_ui::widget() {
	return m_lineEdit;
}

void string_ui::onFlagsChanged(unsigned flags) {
	const bool bs = m_lineEdit->blockSignals(true);
	m_lineEdit->setDisabled(flags & kDisabled);
	m_lineEdit->blockSignals(bs);
}

max_stars_repo_name: martin-pr/possumwood

max_issues_repo_name: LIUJUN-liujun/possumwood

max_forks_repo_name: LIUJUN-liujun/possumwood


text:
// Copyright (c) 2012-2020 LG Electronics, Inc.
//
// 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.
//
// SPDX-License-Identifier: Apache-2.0

#include "MainDaemon.h"

#include <errno.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <memory>
#include <glib.h>
#include <boost/bind.hpp>

#include "base/AppDescriptionList.h"
#include "bus/client/AppInstallService.h"
#include "bus/client/Bootd.h"
#include "bus/client/Configd.h"
#include "bus/client/DB8.h"
#include "bus/client/LSM.h"
#include "bus/client/MemoryManager.h"
#include "bus/client/NativeContainer.h"
#include "bus/client/Notification.h"
#include "bus/client/SettingService.h"
#include "bus/client/WAM.h"
#include "bus/service/ApplicationManager.h"
#include "conf/RuntimeInfo.h"
#include "conf/SAMConf.h"
#include "util/File.h"
#include "util/JValueUtil.h"

MainDaemon::MainDaemon()
    : m_isCBDGenerated(false),
      m_isConfigsReceived(false)
{
    setClassName("MainDaemon");
    m_mainLoop = g_main_loop_new(NULL, FALSE);
}

MainDaemon::~MainDaemon()
{
    if (m_mainLoop) {
        g_main_loop_unref(m_mainLoop);
    }
}

void MainDaemon::initialize()
{
    RuntimeInfo::getInstance().initialize();
    SAMConf::getInstance().initialize();
    AppDescriptionList::getInstance().scanFull();

    if (!ApplicationManager::getInstance().attach(m_mainLoop))
        return;

    AppInstallService::getInstance().initialize();
    Bootd::getInstance().initialize();
    Configd::getInstance().initialize();
    DB8::getInstance().initialize();
    LSM::getInstance().initialize();
    MemoryManager::getInstance().initialize();
    NativeContainer::getInstance().initialize();
    Notification::getInstance().initialize();
    SettingService::getInstance().initialize();
    WAM::getInstance().initialize();

    Bootd::getInstance().EventGetBootStatus.connect(boost::bind(&MainDaemon::onGetBootStatus, this, boost::placeholders::_1));
    Configd::getInstance().EventGetConfigs.connect(boost::bind(&MainDaemon::onGetConfigs, this, boost::placeholders::_1));
}

void MainDaemon::finalize()
{
    AppInstallService::getInstance().finalize();
    Bootd::getInstance().finalize();
    Configd::getInstance().finalize();
    DB8::getInstance().finalize();
    LSM::getInstance().finalize();
    MemoryManager::getInstance().finalize();
    Notification::getInstance().finalize();
    SettingService::getInstance().finalize();
    WAM::getInstance().finalize();

    ApplicationManager::getInstance().detach();
}

void MainDaemon::start()
{
    Logger::info(getClassName(), __FUNCTION__, "Start event handler thread");
    g_main_loop_run(m_mainLoop);
}

void MainDaemon::stop()
{
    if (m_mainLoop)
        g_main_loop_quit(m_mainLoop);
}

void MainDaemon::onGetBootStatus(const JValue& subscriptionPayload)
{
    bool coreBootDone;
    if (!JValueUtil::getValue(subscriptionPayload, "signals", "core-boot-done", coreBootDone) && !coreBootDone) {
        return;
    }
    m_isCBDGenerated = true;
    checkPreconditions();
}

void MainDaemon::onGetConfigs(const JValue& responsePayload)
{
    JValue sysAssetFallbackPrecedence;
    JValue keepAliveApps;
    JValue lifeCycle;

    if (JValueUtil::getValue(responsePayload, "configs", "system.sysAssetFallbackPrecedence", sysAssetFallbackPrecedence) && sysAssetFallbackPrecedence.isArray()) {
        SAMConf::getInstance().setSysAssetFallbackPrecedence(sysAssetFallbackPrecedence);
    }
    if (JValueUtil::getValue(responsePayload, "configs", "com.webos.applicationManager.keepAliveApps", keepAliveApps) && keepAliveApps.isArray()) {
        SAMConf::getInstance().setKeepAliveApps(keepAliveApps);
    }
    m_isConfigsReceived = true;
    checkPreconditions();
}

void MainDaemon::checkPreconditions()
{
    static bool isFired = false;
    if (isFired)
        return;

    if (!m_isConfigsReceived) {
        Logger::info(getClassName(), __FUNCTION__, "Wait for receiving 'getConfigs' response");
        return;
    }
    if (!m_isCBDGenerated) {
        Logger::info(getClassName(), __FUNCTION__, "Wait for receiving 'getBootStatus' response");
        return;
    }
    Logger::info(getClassName(), __FUNCTION__, "All initial components are ready");
    isFired = true;

    ApplicationManager::getInstance().enablePosting();
}

max_stars_repo_name: webOS-ports/sam

max_issues_repo_name: webOS-ports/sam

max_forks_repo_name: webOS-ports/sam


text:
#include <boost/connector/vendor/ftx/websocket_connector.hpp>

#include <cassert>

namespace boost::connector::vendor::ftx
{
websocket_connector::websocket_connector(
    lifetime_ptr< ftx_websocket_connector_concept > lifetime)
: lifetime_(std::move(lifetime))
{
}

void
websocket_connector::drop()
{
    assert(lifetime_);
    lifetime_->drop();
}

void
websocket_connector::send(std::string payload)
{
    assert(lifetime_);
    lifetime_->send(std::move(payload));
}

auto
websocket_connector::get_executor() const -> executor_type const &
{
    assert(lifetime_);
    return lifetime_->get_executor();
}

asio::awaitable< void >
websocket_connector::wait_ready()
{
    assert(lifetime_);
    return lifetime_->wait_ready();
}

asio::awaitable< void >
websocket_connector::wait_down()
{
    assert(lifetime_);
    return lifetime_->wait_down();
}

ftx_websocket_connector_concept &
websocket_connector::get_impl()
{
    assert(lifetime_);
    return *lifetime_;
}

}   // namespace boost::connector::vendor::ftx


text:
//
//  common_types.hpp
//  fibio
//
//  Created by Chen Xu on 14-3-10.
//  Copyright (c) 2014 0d0a.com. All rights reserved.
//

#ifndef fibio_http_common_common_types_hpp
#define fibio_http_common_common_types_hpp

#include <cstdint>
#include <string>
#include <map>
#include <list>
#include <chrono>
#include <boost/algorithm/string/compare.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/lexical_cast.hpp>
#include <fibio/http/common/content_type.hpp>

namespace fibio {
namespace http {
namespace common {

enum class http_version : uint16_t
{
    INVALID_VERSION = 0x0000,
    HTTP_0_9 = 0x0009,
    HTTP_1_0 = 0x0100,
    HTTP_1_1 = 0x0101,
};

enum class http_method : uint16_t
{
    // Name conflict
    DELETE_ = 0,
    GET = 1,
    HEAD = 2,
    POST = 3,
    PUT = 4,
    /* pathological */
    CONNECT = 5,
    OPTIONS = 6,
    TRACE = 7,
    /* webdav */
    COPY = 8,
    LOCK = 9,
    MKCOL = 10,
    MOVE = 11,
    PROPFIND = 12,
    PROPPATCH = 13,
    SEARCH = 14,
    UNLOCK = 15,
    /* subversion */
    REPORT = 16,
    MKACTIVITY = 17,
    CHECKOUT = 18,
    MERGE = 19,
    /* upnp */
    MSEARCH = 20,
    NOTIFY = 21,
    SUBSCRIBE = 22,
    UNSUBSCRIBE = 23,
    /* RFC-5789 */
    PATCH = 24,
    PURGE = 25,
    INVALID_METHOD = 0xFFFF,
};

enum class http_status_code : uint16_t
{
    INVALID_STATUS = 0,
    CONTINUE = 100,
    SWITCHING_PROTOCOLS = 101,
    OK = 200,
    CREATED = 201,
    ACCEPTED = 202,
    NON_AUTHORITATIVE_INFORMATION = 203,
    NO_CONTENT = 204,
    RESET_CONTENT = 205,
    PARTIAL_CONTENT = 206,
    MULTIPLE_CHOICES = 300,
    MOVED_PERMANENTLY = 301,
    FOUND = 302,
    SEE_OTHER = 303,
    NOT_MODIFIED = 304,
    USE_PROXY = 305,
    // UNUSED                        =306,
    TEMPORARY_REDIRECT = 307,
    BAD_REQUEST = 400,
    UNAUTHORIZED = 401,
    PAYMENT_REQUIRED = 402,
    FORBIDDEN = 403,
    NOT_FOUND = 404,
    METHOD_NOT_ALLOWED = 405,
    NOT_ACCEPTABLE = 406,
    PROXY_AUTHENTICATION_REQUIRED = 407,
    REQUEST_TIMEOUT = 408,
    CONFLICT = 409,
    GONE = 410,
    LENGTH_REQUIRED = 411,
    PRECONDITION_FAILED = 412,
    REQUEST_ENTITY_TOO_LARGE = 413,
    REQUEST_URI_TOO_LONG = 414,
    UNSUPPORTED_MEDIA_TYPE = 415,
    REQUESTED_RANGE_NOT_SATISFIABLE = 416,
    EXPECTATION_FAILED = 417,
    UPGRADE_REQUIRED = 426,
    PRECONDITION_REQUIRED = 428,
    TOO_MANY_REQUESTS = 429,
    REQUEST_HEADER_FIELDS_TOO_LARGE = 431,
    INTERNAL_SERVER_ERROR = 500,
    NOT_IMPLEMENTED = 501,
    BAD_GATEWAY = 502,
    SERVICE_UNAVAILABLE = 503,
    GATEWAY_TIMEOUT = 504,
    HTTP_VERSION_NOT_SUPPORTED = 505,
};

struct parsed_url_type
{
    std::string schema;
    std::string host;
    uint16_t port = 0;
    std::string path;
    std::string query;
    std::string fragment;
    std::string userinfo;
    std::list<std::string> path_components;
    std::map<std::string, std::string> query_params;
};

bool parse_url(const std::string url,
               parsed_url_type& parsed_url,
               bool parse_path = true,
               bool parse_query = true);

typedef std::string header_key_type;
typedef std::string header_value_type;

struct iless
{
    inline bool operator()(const header_key_type& lhs, const header_key_type& rhs) const
    {
        return boost::algorithm::lexicographical_compare(lhs, rhs, op_);
    }

    boost::algorithm::is_iless op_;
};

struct iequal
{
    inline bool operator()(const header_key_type& lhs, const header_key_type& rhs) const
    {
        return boost::iequals(lhs, rhs);
    }
};

typedef std::multimap<header_key_type, header_value_type, iless> header_map;

std::string base64_encode(const char* s, size_t sz);

std::string base64_encode(const std::string& s);

std::string base64_decode(const std::string& s);

} // End of namespace common

using common::http_version;
using common::http_method;
using common::http_status_code;

} // End of namespace http
} // End of namespace fibio

#endif

max_stars_repo_name: mind-owner/fibio

max_issues_repo_name: learnerzhang/fibio

max_forks_repo_name: learnerzhang/fibio