text:
#ifndef STATIC_LINK_VW
#  define BOOST_TEST_DYN_LINK
#endif

#include <boost/test/unit_test.hpp>
#include <boost/test/test_tools.hpp>

#include "parse_primitives.h"
#include "multiclass.h"
#include "parser.h"
#include "global_data.h"
#include "shared_data.h"

void parse_label(label_parser& lp, parser* p, shared_data* sd, VW::string_view label, polylabel& l)
{
  tokenize(' ', label, p->words);
  lp.default_label(&l);
  reduction_features red_fts;
  lp.parse_label(p, sd, &l, p->words, red_fts);
}

BOOST_AUTO_TEST_CASE(multiclass_label_parser)
{
  auto lp = MULTICLASS::mc_label;
  parser p{8 /*ring_size*/, false /*strict parse*/};
  shared_data sd;

  {
    auto plabel = scoped_calloc_or_throw<polylabel>();
    BOOST_REQUIRE_THROW(parse_label(lp, &p, &sd, "1,2,3", *plabel), VW::vw_exception);
  }
  {
    auto plabel = scoped_calloc_or_throw<polylabel>();
    BOOST_REQUIRE_THROW(parse_label(lp, &p, &sd, "1a", *plabel), VW::vw_exception);
  }
  {
    auto plabel = scoped_calloc_or_throw<polylabel>();
    BOOST_REQUIRE_THROW(parse_label(lp, &p, &sd, "1 2 3", *plabel), VW::vw_exception);
  }
  {
    auto plabel = scoped_calloc_or_throw<polylabel>();
    parse_label(lp, &p, &sd, "2", *plabel);
    BOOST_ASSERT(plabel->multi.label == 2);
    BOOST_ASSERT(plabel->multi.weight == 1.0);
  }
  {
    auto plabel = scoped_calloc_or_throw<polylabel>();
    parse_label(lp, &p, &sd, "2 2", *plabel);
    BOOST_ASSERT(plabel->multi.label == 2);
    BOOST_ASSERT(plabel->multi.weight == 2.0);
  }
}

ext: cc


text:
//==================================================================================================
/*!
  @file

  @copyright 2016 NumScale SAS

  Distributed under the Boost Software License, Version 1.0.
  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
//==================================================================================================
#ifndef BOOST_SIMD_FUNCTION_BITINTEGER_HPP_INCLUDED
#define BOOST_SIMD_FUNCTION_BITINTEGER_HPP_INCLUDED

#if defined(DOXYGEN_ONLY)
namespace boost { namespace simd
{

 /*!

    @ingroup group-ieee
    Function object implementing bitinteger capabilities

    Transforms a floating point value in a pattern of bits
    stored in an integer with different formulas according to
    the floating point @ref bitofsign.

    This function is the converse of @ref bitfloating.

    @par Semantic:

    for any parameter @c x of floating type @c T

    @code
     as_integer_t<T> r = bitinteger(x);
    @endcode

    @par Note:
    This is an internally used utility function related to the computation of floating
    successors or predecessors

    @see next, prev, successor,  predecessor,  nextafter, bitfloating

  **/
  as_integer_t<T> bitinteger(Value const & v0);
} }
#endif

#include <boost/simd/function/scalar/bitinteger.hpp>
#include <boost/simd/function/simd/bitinteger.hpp>

#endif

ext: hpp

max_stars_repo_name: xmar/pythran

max_issues_repo_name: xmar/pythran

max_forks_repo_name: xmar/pythran


text:
#include <doctest/doctest.h>
#include "particle.h"
#include "rotate.h"
#include "units.h"
#include "aux/eigensupport.h"
#include <fstream>
#include <Eigen/Geometry>
#include <cereal/archives/binary.hpp>

namespace Faunus {

/**
 * @todo Inefficient to pass both Quaternion and rotation matrix. This is currently
 * done since tensors are rotated using the latter. Could these be rotated using
 * quaternions?
 */
void ParticlePropertyBase::rotate(const Eigen::Quaterniond &, const Eigen::Matrix3d &) {}
void Radius::to_json(json &j) const { j["r"] = radius; }
void Radius::from_json(const json &j) { radius = j.value("r", 0.0); }
void Charge::to_json(json &j) const { j["q"] = charge; }
void Charge::from_json(const json &j) { charge = j.value("q", 0.0); }
void Dipole::rotate(const Eigen::Quaterniond &q, const Eigen::Matrix3d &) { mu = q * mu; }

void Dipole::to_json(json &j) const {
    j["mu"] = mu;
    j["mulen"] = mulen;
}

void Dipole::from_json(const json &j) {
    mu = j.value("mu", Point(1, 0, 0));
    mulen = j.value("mulen", mulen);
}

void Polarizable::rotate(const Eigen::Quaterniond &q, const Eigen::Matrix3d &m) {
    mui = q * mui;
    alpha.rotate(m);
}

void Polarizable::to_json(json &j) const {
    j["alpha"] = alpha;
    j["mui"] = mui;
    j["muilen"] = muilen;
}

void Polarizable::from_json(const json &j) {
    alpha = j.value("alpha", alpha);
    mui = j.value("mui", Point(1, 0, 0));
    muilen = j.value("mulen", muilen);
}

void Quadrupole::rotate(const Eigen::Quaterniond &, const Eigen::Matrix3d &m) { Q.rotate(m); }

void Quadrupole::to_json(json &j) const { j["Q"] = Q; }

void Quadrupole::from_json(const json &j) { Q = j.value("Q", Q); }

void Cigar::rotate(const Eigen::Quaterniond &q, const Eigen::Matrix3d &) { scdir = q * scdir; }

void Cigar::to_json(json &j) const {
    j["scdir"] = scdir;
    j["sclen"] = sclen;
}
void Cigar::from_json(const json &j) {
    scdir = j.value("scdir", scdir);
    sclen = j.value("sclen", sclen);
}

const AtomData &Particle::traits() const { return atoms.at(id); }

/**
 * @warning Performance is sub-optimal as conversion is done through a json object
 */
Particle::Particle(const AtomData &a) { *this = json(a).front(); }
Particle::Particle(const AtomData &a, const Point &pos) : Particle(a) { this->pos = pos; }
Particle::Particle(const Particle &other) : id(other.id), charge(other.charge), pos(other.pos) {
    if (other.ext) {
        ext = std::make_shared<Particle::ParticleExtension>(*other.ext); // deep copy
    }
}

Particle &Particle::operator=(const Particle &other) {
    if (&other != this) {
        charge = other.charge;
        pos = other.pos;
        id = other.id;
        if (other.ext) {           // if particle has
            if (ext) {             // extension, then
                *ext = *other.ext; // deep copy
            } else {               // else if *this is empty, create new based on p
                ext = std::make_shared<Particle::ParticleExtension>(*other.ext); // create new
            }
        } else { // other doesn't have extended properties
            ext = nullptr;
        }
    }
    return *this;
}

/**
 * @param quaternion Quaternion used to rotate points
 * @param rotation_matrix Rotation matrix used to rotate tensors
 * @todo Only one of the above should be enough
 *
 * This has effect only on anisotropic particles and does no
 * positional rotation, only internal rotation
 */
void Particle::rotate(const Eigen::Quaterniond &quaternion, const Eigen::Matrix3d &rotation_matrix) {
    if (hasExtension()) {
        ext->rotate(quaternion, rotation_matrix);
    }
}

bool Particle::hasExtension() const { return ext != nullptr; }

Particle::ParticleExtension &Particle::createExtension() {
    assert(ext == nullptr && "extension already created");
    ext = std::make_shared<ParticleExtension>();
    return *ext;
}

void from_json(const json &j, Particle &p) {
    p.id = j.value("id", -1);
    p.pos = j.value("pos", Point(0, 0, 0));
    p.charge = j.value("q", 0.0);

    p.ext = std::make_shared<Particle::ParticleExtension>();
    from_json(j, *p.ext);
    Particle::ParticleExtension empty_extended_particle;
    // why can't we compare ParticleExtension directly?!
    // (slow and ugly)
    if (json(*p.ext) == json(empty_extended_particle))
        p.ext = nullptr; // no extended features found in json
}
void to_json(json &j, const Particle &p) {
    if (p.ext) {
        to_json(j, *p.ext);
    }
    j["id"] = p.id;
    j["pos"] = p.pos;
    j["q"] = p.charge;
}

TEST_SUITE_BEGIN("Particle");

// convert test to use `Particle::shape`
TEST_CASE("[Faunus] Particle") {
    using doctest::Approx;
    Particle p1, p2;
    p1.id = 100;
    p1.pos = {1, 2, 3};
    p1.charge = -0.8;

    CHECK(p1.hasExtension() == false);

    p1.createExtension();
    CHECK(p1.hasExtension() == true);

    p2.createExtension();
    CHECK(p2.hasExtension() == true);

    p1.getExt().mu = {0, 0, 1};
    p1.getExt().mulen = 2.8;
    p1.getExt().scdir = {-0.1, 0.3, 1.9};
    p1.getExt().sclen = 0.5;
    p1.getExt().Q = Tensor(1, 2, 3, 4, 5, 6);

    p2 = json(p1); // p1 --> json --> p2
    CHECK(p2.hasExtension() == true);

    CHECK(json(p1) == json(p2)); // p1 --> json == json <-- p2 ?

    CHECK(p2.id == 100);
    CHECK(p2.pos == Point(1, 2, 3));
    CHECK(p2.charge == -0.8);
    CHECK(p2.getExt().mu == Point(0, 0, 1));
    CHECK(p2.getExt().mulen == 2.8);
    CHECK(p2.getExt().scdir == Point(-0.1, 0.3, 1.9));
    CHECK(p2.getExt().sclen == 0.5);
    CHECK(p2.getExt().Q == Tensor(1, 2, 3, 4, 5, 6));

    // check of all properties are rotated
    QuaternionRotate qrot(pc::pi / 2, {0, 1, 0});
    p1.getExt().mu = p1.getExt().scdir = {1, 0, 0};
    p1.rotate(qrot.getQuaternion(), qrot.getRotationMatrix());

    CHECK(p1.getExt().mu.x() == Approx(0));
    CHECK(p1.getExt().mu.z() == Approx(-1));
    CHECK(p1.getExt().scdir.x() == Approx(0));
    CHECK(p1.getExt().scdir.z() == Approx(-1));

    CHECK(p1.getExt().Q(0, 0) == Approx(6));
    CHECK(p1.getExt().Q(0, 1) == Approx(5));
    CHECK(p1.getExt().Q(0, 2) == Approx(-3));
    CHECK(p1.getExt().Q(1, 1) == Approx(4));
    CHECK(p1.getExt().Q(1, 2) == Approx(-2));
    CHECK(p1.getExt().Q(2, 2) == Approx(1));

    SUBCASE("Cereal serialisation") {
        Particle p;
        p.pos = {10, 20, 30};
        p.charge = -1;
        p.id = 8;
        p.ext = std::make_shared<Particle::ParticleExtension>();
        p.getExt().mu = {0.1, 0.2, 0.3};
        p.getExt().mulen = 104;

        { // write
            std::ofstream os("out.cereal", std::ios::binary);
            cereal::BinaryOutputArchive archive(os);
            archive(p);
        }

        // set to zero
        p.pos = {0, 0, 0};
        p.charge = 0;
        p.id = 0;
        p.getExt().mu.setZero();
        p.getExt().mulen = 0;

        { // read
            std::ifstream is("out.cereal", std::ios::binary);
            cereal::BinaryInputArchive archive(is);
            archive(p);
            CHECK(p.id == 8);
            CHECK(p.charge == -1);
            CHECK(p.pos.x() == 10);
            CHECK(p.pos.y() == 20);
            CHECK(p.pos.z() == 30);
            CHECK(p.getExt().mu.x() == 0.1);
            CHECK(p.getExt().mu.y() == 0.2);
            CHECK(p.getExt().mu.z() == 0.3);
            CHECK(p.getExt().mulen == 104);
        }
    }
}

TEST_SUITE_END();

} // namespace Faunus

ext: cpp


text: #include <boost/parameter/aux_/template_keyword.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
/*!
@file
Defines `boost::hana::Iterable`.

@copyright Louis Dionne 2014
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
 */

#ifndef BOOST_HANA_ITERABLE_HPP
#define BOOST_HANA_ITERABLE_HPP

#include <boost/hana/iterable/iterable.hpp>
#include <boost/hana/iterable/mcd.hpp>

#endif // !BOOST_HANA_ITERABLE_HPP

max_stars_repo_name: rbock/hana

max_issues_repo_name: rbock/hana

max_forks_repo_name: rbock/hana


text:
#include "lm/model.hh"

#include <stdlib.h>
#include <string.h>

#define BOOST_TEST_MODULE ModelTest
#include <boost/test/unit_test.hpp>
#include <boost/test/floating_point_comparison.hpp>

// Apparently some Boost versions use templates and are pretty strict about types matching.
#define SLOPPY_CHECK_CLOSE(ref, value, tol) BOOST_CHECK_CLOSE(static_cast<double>(ref), static_cast<double>(value), static_cast<double>(tol));

namespace lm {
namespace ngram {

std::ostream &operator<<(std::ostream &o, const State &state) {
  o << "State length " << static_cast<unsigned int>(state.length) << ':';
  for (const WordIndex *i = state.words; i < state.words + state.length; ++i) {
    o << ' ' << *i;
  }
  return o;
}

namespace {

// Stupid bjam reverses the command line arguments randomly.
const char *TestLocation() {
  if (boost::unit_test::framework::master_test_suite().argc < 3) {
    return "test.arpa";
  }
  char **argv = boost::unit_test::framework::master_test_suite().argv;
  return argv[strstr(argv[1], "nounk") ? 2 : 1];
}
const char *TestNoUnkLocation() {
  if (boost::unit_test::framework::master_test_suite().argc < 3) {
    return "test_nounk.arpa";
  }
  char **argv = boost::unit_test::framework::master_test_suite().argv;
  return argv[strstr(argv[1], "nounk") ? 1 : 2];
}

template <class Model> State GetState(const Model &model, const char *word, const State &in) {
  WordIndex context[in.length + 1];
  context[0] = model.GetVocabulary().Index(word);
  std::copy(in.words, in.words + in.length, context + 1);
  State ret;
  model.GetState(context, context + in.length + 1, ret);
  return ret;
}

#define StartTest(word, ngram, score, indep_left) \
  ret = model.FullScore( \
      state, \
      model.GetVocabulary().Index(word), \
      out);\
  SLOPPY_CHECK_CLOSE(score, ret.prob, 0.001); \
  BOOST_CHECK_EQUAL(static_cast<unsigned int>(ngram), ret.ngram_length); \
  BOOST_CHECK_GE(std::min<unsigned char>(ngram, 5 - 1), out.length); \
  BOOST_CHECK_EQUAL(indep_left, ret.independent_left); \
  BOOST_CHECK_EQUAL(out, GetState(model, word, state));

#define AppendTest(word, ngram, score, indep_left) \
  StartTest(word, ngram, score, indep_left) \
  state = out;

template <class M> void Starters(const M &model) {
  FullScoreReturn ret;
  Model::State state(model.BeginSentenceState());
  Model::State out;

  StartTest("looking", 2, -0.4846522, true);

  // , probability plus <s> backoff
  StartTest(",", 1, -1.383514 + -0.4149733, true);
  // <unk> probability plus <s> backoff
  StartTest("this_is_not_found", 1, -1.995635 + -0.4149733, true);
}

template <class M> void Continuation(const M &model) {
  FullScoreReturn ret;
  Model::State state(model.BeginSentenceState());
  Model::State out;

  AppendTest("looking", 2, -0.484652, true);
  AppendTest("on", 3, -0.348837, true);
  AppendTest("a", 4, -0.0155266, true);
  AppendTest("little", 5, -0.00306122, true);
  State preserve = state;
  AppendTest("the", 1, -4.04005, true);
  AppendTest("biarritz", 1, -1.9889, true);
  AppendTest("not_found", 1, -2.29666, true);
  AppendTest("more", 1, -1.20632 - 20.0, true);
  AppendTest(".", 2, -0.51363, true);
  AppendTest("</s>", 3, -0.0191651, true);
  BOOST_CHECK_EQUAL(0, state.length);

  state = preserve;
  AppendTest("more", 5, -0.00181395, true);
  BOOST_CHECK_EQUAL(4, state.length);
  AppendTest("loin", 5, -0.0432557, true);
  BOOST_CHECK_EQUAL(1, state.length);
}

template <class M> void Blanks(const M &model) {
  FullScoreReturn ret;
  State state(model.NullContextState());
  State out;
  AppendTest("also", 1, -1.687872, false);
  AppendTest("would", 2, -2, true);
  AppendTest("consider", 3, -3, true);
  State preserve = state;
  AppendTest("higher", 4, -4, true);
  AppendTest("looking", 5, -5, true);
  BOOST_CHECK_EQUAL(1, state.length);

  state = preserve;
  // also would consider not_found
  AppendTest("not_found", 1, -1.995635 - 7.0 - 0.30103, true);

  state = model.NullContextState();
  // higher looking is a blank.
  AppendTest("higher", 1, -1.509559, false);
  AppendTest("looking", 2, -1.285941 - 0.30103, false);

  State higher_looking = state;

  BOOST_CHECK_EQUAL(1, state.length);
  AppendTest("not_found", 1, -1.995635 - 0.4771212, true);

  state = higher_looking;
  // higher looking consider
  AppendTest("consider", 1, -1.687872 - 0.4771212, true);

  state = model.NullContextState();
  AppendTest("would", 1, -1.687872, false);
  BOOST_CHECK_EQUAL(1, state.length);
  AppendTest("consider", 2, -1.687872 -0.30103, false);
  BOOST_CHECK_EQUAL(2, state.length);
  AppendTest("higher", 3, -1.509559 - 0.30103, false);
  BOOST_CHECK_EQUAL(3, state.length);
  AppendTest("looking", 4, -1.285941 - 0.30103, false);
}

template <class M> void Unknowns(const M &model) {
  FullScoreReturn ret;
  State state(model.NullContextState());
  State out;

  AppendTest("not_found", 1, -1.995635, false);
  State preserve = state;
  AppendTest("not_found2", 2, -15.0, true);
  AppendTest("not_found3", 2, -15.0 - 2.0, true);

  state = preserve;
  AppendTest("however", 2, -4, true);
  AppendTest("not_found3", 3, -6, true);
}

template <class M> void MinimalState(const M &model) {
  FullScoreReturn ret;
  State state(model.NullContextState());
  State out;

  AppendTest("baz", 1, -6.535897, true);
  BOOST_CHECK_EQUAL(0, state.length);
  state = model.NullContextState();
  AppendTest("foo", 1, -3.141592, true);
  BOOST_CHECK_EQUAL(1, state.length);
  AppendTest("bar", 2, -6.0, true);
  // Has to include the backoff weight.
  BOOST_CHECK_EQUAL(1, state.length);
  AppendTest("bar", 1, -2.718281 + 3.0, true);
  BOOST_CHECK_EQUAL(1, state.length);

  state = model.NullContextState();
  AppendTest("to", 1, -1.687872, false);
  AppendTest("look", 2, -0.2922095, true);
  BOOST_CHECK_EQUAL(2, state.length);
  AppendTest("a", 3, -7, true);
}

template <class M> void ExtendLeftTest(const M &model) {
  State right;
  FullScoreReturn little(model.FullScore(model.NullContextState(), model.GetVocabulary().Index("little"), right));
  const float kLittleProb = -1.285941;
  SLOPPY_CHECK_CLOSE(kLittleProb, little.prob, 0.001);
  unsigned char next_use;
  float backoff_out[4];

  FullScoreReturn extend_none(model.ExtendLeft(NULL, NULL, NULL, little.extend_left, 1, NULL, next_use));
  BOOST_CHECK_EQUAL(0, next_use);
  BOOST_CHECK_EQUAL(little.extend_left, extend_none.extend_left);
  SLOPPY_CHECK_CLOSE(little.prob - little.rest, extend_none.prob, 0.001);
  BOOST_CHECK_EQUAL(1, extend_none.ngram_length);

  const WordIndex a = model.GetVocabulary().Index("a");
  float backoff_in = 3.14;
  // a little
  FullScoreReturn extend_a(model.ExtendLeft(&a, &a + 1, &backoff_in, little.extend_left, 1, backoff_out, next_use));
  BOOST_CHECK_EQUAL(1, next_use);
  SLOPPY_CHECK_CLOSE(-0.69897, backoff_out[0], 0.001);
  SLOPPY_CHECK_CLOSE(-0.09132547 - little.rest, extend_a.prob, 0.001);
  BOOST_CHECK_EQUAL(2, extend_a.ngram_length);
  BOOST_CHECK(!extend_a.independent_left);

  const WordIndex on = model.GetVocabulary().Index("on");
  FullScoreReturn extend_on(model.ExtendLeft(&on, &on + 1, &backoff_in, extend_a.extend_left, 2, backoff_out, next_use));
  BOOST_CHECK_EQUAL(1, next_use);
  SLOPPY_CHECK_CLOSE(-0.4771212, backoff_out[0], 0.001);
  SLOPPY_CHECK_CLOSE(-0.0283603 - (extend_a.rest + little.rest), extend_on.prob, 0.001);
  BOOST_CHECK_EQUAL(3, extend_on.ngram_length);
  BOOST_CHECK(!extend_on.independent_left);

  const WordIndex both[2] = {a, on};
  float backoff_in_arr[4];
  FullScoreReturn extend_both(model.ExtendLeft(both, both + 2, backoff_in_arr, little.extend_left, 1, backoff_out, next_use));
  BOOST_CHECK_EQUAL(2, next_use);
  SLOPPY_CHECK_CLOSE(-0.69897, backoff_out[0], 0.001);
  SLOPPY_CHECK_CLOSE(-0.4771212, backoff_out[1], 0.001);
  SLOPPY_CHECK_CLOSE(-0.0283603 - little.rest, extend_both.prob, 0.001);
  BOOST_CHECK_EQUAL(3, extend_both.ngram_length);
  BOOST_CHECK(!extend_both.independent_left);
  BOOST_CHECK_EQUAL(extend_on.extend_left, extend_both.extend_left);
}

#define StatelessTest(word, provide, ngram, score) \
  ret = model.FullScoreForgotState(indices + num_words - word, indices + num_words - word + provide, indices[num_words - word - 1], state); \
  SLOPPY_CHECK_CLOSE(score, ret.prob, 0.001); \
  BOOST_CHECK_EQUAL(static_cast<unsigned int>(ngram), ret.ngram_length); \
  model.GetState(indices + num_words - word, indices + num_words - word + provide, before); \
  ret = model.FullScore(before, indices[num_words - word - 1], out); \
  BOOST_CHECK(state == out); \
  SLOPPY_CHECK_CLOSE(score, ret.prob, 0.001); \
  BOOST_CHECK_EQUAL(static_cast<unsigned int>(ngram), ret.ngram_length);

template <class M> void Stateless(const M &model) {
  const char *words[] = {"<s>", "looking", "on", "a", "little", "the", "biarritz", "not_found", "more", ".", "</s>"};
  const size_t num_words = sizeof(words) / sizeof(const char*);
  // Silience "array subscript is above array bounds" when extracting end pointer.
  WordIndex indices[num_words + 1];
  for (unsigned int i = 0; i < num_words; ++i) {
    indices[num_words - 1 - i] = model.GetVocabulary().Index(words[i]);
  }
  FullScoreReturn ret;
  State state, out, before;

  ret = model.FullScoreForgotState(indices + num_words - 1, indices + num_words, indices[num_words - 2], state);
  SLOPPY_CHECK_CLOSE(-0.484652, ret.prob, 0.001);
  StatelessTest(1, 1, 2, -0.484652);

  // looking
  StatelessTest(1, 2, 2, -0.484652);
  // on
  AppendTest("on", 3, -0.348837, true);
  StatelessTest(2, 3, 3, -0.348837);
  StatelessTest(2, 2, 3, -0.348837);
  StatelessTest(2, 1, 2, -0.4638903);
  // a
  StatelessTest(3, 4, 4, -0.0155266);
  // little
  AppendTest("little", 5, -0.00306122, true);
  StatelessTest(4, 5, 5, -0.00306122);
  // the
  AppendTest("the", 1, -4.04005, true);
  StatelessTest(5, 5, 1, -4.04005);
  // No context of the.
  StatelessTest(5, 0, 1, -1.687872);
  // biarritz
  StatelessTest(6, 1, 1, -1.9889);
  // not found
  StatelessTest(7, 1, 1, -2.29666);
  StatelessTest(7, 0, 1, -1.995635);

  WordIndex unk[1];
  unk[0] = 0;
  model.GetState(unk, unk + 1, state);
  BOOST_CHECK_EQUAL(1, state.length);
  BOOST_CHECK_EQUAL(static_cast<WordIndex>(0), state.words[0]);
}

template <class M> void NoUnkCheck(const M &model) {
  WordIndex unk_index = 0;
  State state;

  FullScoreReturn ret = model.FullScoreForgotState(&unk_index, &unk_index + 1, unk_index, state);
  SLOPPY_CHECK_CLOSE(-100.0, ret.prob, 0.001);
}

template <class M> void Everything(const M &m) {
  Starters(m);
  Continuation(m);
  Blanks(m);
  Unknowns(m);
  MinimalState(m);
  ExtendLeftTest(m);
  Stateless(m);
}

class ExpectEnumerateVocab : public EnumerateVocab {
  public:
    ExpectEnumerateVocab() {}

    void Add(WordIndex index, const StringPiece &str) {
      BOOST_CHECK_EQUAL(seen.size(), index);
      seen.push_back(std::string(str.data(), str.length()));
    }

    void Check(const base::Vocabulary &vocab) {
      BOOST_CHECK_EQUAL(37ULL, seen.size());
      BOOST_REQUIRE(!seen.empty());
      BOOST_CHECK_EQUAL("<unk>", seen[0]);
      for (WordIndex i = 0; i < seen.size(); ++i) {
        BOOST_CHECK_EQUAL(i, vocab.Index(seen[i]));
      }
    }

    void Clear() {
      seen.clear();
    }

    std::vector<std::string> seen;
};

template <class ModelT> void LoadingTest() {
  Config config;
  config.arpa_complain = Config::NONE;
  config.messages = NULL;
  config.probing_multiplier = 2.0;
  {
    ExpectEnumerateVocab enumerate;
    config.enumerate_vocab = &enumerate;
    ModelT m(TestLocation(), config);
    enumerate.Check(m.GetVocabulary());
    BOOST_CHECK_EQUAL((WordIndex)37, m.GetVocabulary().Bound());
    Everything(m);
  }
  {
    ExpectEnumerateVocab enumerate;
    config.enumerate_vocab = &enumerate;
    ModelT m(TestNoUnkLocation(), config);
    enumerate.Check(m.GetVocabulary());
    BOOST_CHECK_EQUAL((WordIndex)37, m.GetVocabulary().Bound());
    NoUnkCheck(m);
  }
}

BOOST_AUTO_TEST_CASE(probing) {
  LoadingTest<Model>();
}
BOOST_AUTO_TEST_CASE(trie) {
  LoadingTest<TrieModel>();
}
BOOST_AUTO_TEST_CASE(quant_trie) {
  LoadingTest<QuantTrieModel>();
}
BOOST_AUTO_TEST_CASE(bhiksha_trie) {
  LoadingTest<ArrayTrieModel>();
}
BOOST_AUTO_TEST_CASE(quant_bhiksha_trie) {
  LoadingTest<QuantArrayTrieModel>();
}

template <class ModelT> void BinaryTest(Config::WriteMethod write_method) {
  Config config;
  config.write_mmap = "test.binary";
  config.messages = NULL;
  config.write_method = write_method;
  ExpectEnumerateVocab enumerate;
  config.enumerate_vocab = &enumerate;

  {
    ModelT copy_model(TestLocation(), config);
    enumerate.Check(copy_model.GetVocabulary());
    enumerate.Clear();
    Everything(copy_model);
  }

  config.write_mmap = NULL;

  ModelType type;
  BOOST_REQUIRE(RecognizeBinary("test.binary", type));
  BOOST_CHECK_EQUAL(ModelT::kModelType, type);

  {
    ModelT binary("test.binary", config);
    enumerate.Check(binary.GetVocabulary());
    Everything(binary);
  }
  unlink("test.binary");

  // Now test without <unk>.
  config.write_mmap = "test_nounk.binary";
  config.messages = NULL;
  enumerate.Clear();
  {
    ModelT copy_model(TestNoUnkLocation(), config);
    enumerate.Check(copy_model.GetVocabulary());
    enumerate.Clear();
    NoUnkCheck(copy_model);
  }
  config.write_mmap = NULL;
  {
    ModelT binary(TestNoUnkLocation(), config);
    enumerate.Check(binary.GetVocabulary());
    NoUnkCheck(binary);
  }
  unlink("test_nounk.binary");
}

template <class ModelT> void BinaryTest() {
  BinaryTest<ModelT>(Config::WRITE_MMAP);
  BinaryTest<ModelT>(Config::WRITE_AFTER);
}

BOOST_AUTO_TEST_CASE(write_and_read_probing) {
  BinaryTest<ProbingModel>();
}
BOOST_AUTO_TEST_CASE(write_and_read_rest_probing) {
  BinaryTest<RestProbingModel>();
}
BOOST_AUTO_TEST_CASE(write_and_read_trie) {
  BinaryTest<TrieModel>();
}
BOOST_AUTO_TEST_CASE(write_and_read_quant_trie) {
  BinaryTest<QuantTrieModel>();
}
BOOST_AUTO_TEST_CASE(write_and_read_array_trie) {
  BinaryTest<ArrayTrieModel>();
}
BOOST_AUTO_TEST_CASE(write_and_read_quant_array_trie) {
  BinaryTest<QuantArrayTrieModel>();
}

BOOST_AUTO_TEST_CASE(rest_max) {
  Config config;
  config.arpa_complain = Config::NONE;
  config.messages = NULL;

  RestProbingModel model(TestLocation(), config);
  State state, out;
  FullScoreReturn ret(model.FullScore(model.NullContextState(), model.GetVocabulary().Index("."), state));
  SLOPPY_CHECK_CLOSE(-0.2705918, ret.rest, 0.001);
  SLOPPY_CHECK_CLOSE(-0.01916512, model.FullScore(state, model.GetVocabulary().EndSentence(), out).rest, 0.001);
}

} // namespace
} // namespace ngram
} // namespace lm

max_stars_repo_name: janlelis/wisdom-query

max_issues_repo_name: janlelis/wisdom-query

max_forks_repo_name: janlelis/wisdom-query


text:
//
// Copyright (c) 2015-2020 CNRS INRIA
//

#ifndef __pinocchio_python_algorithms_hpp__
#define __pinocchio_python_algorithms_hpp__

#include "pinocchio/bindings/python/fwd.hpp"
#include <boost/python.hpp>

namespace pinocchio
{
  namespace python
  {
    namespace bp = boost::python;

    void exposeJointsAlgo();
    void exposeABA();
    void exposeCRBA();
    void exposeCentroidal();
    void exposeRNEA();
    void exposeCOM();
    void exposeFramesAlgo();
    void exposeEnergy();
    void exposeKinematics();
    void exposeDynamics();
    void exposeCAT();
    void exposeJacobian();
    void exposeGeometryAlgo();
    void exposeKinematicRegressor();
    void exposeRegressor();
    void exposeCholesky();
    void exposeModelAlgo();

    void exposeRNEADerivatives();
    void exposeABADerivatives();
    void exposeKinematicsDerivatives();
    void exposeFramesDerivatives();
    void exposeCentroidalDerivatives();

    void exposeAlgorithms();

  } // namespace python
} // namespace pinocchio

#endif // ifndef __pinocchio_python_algorithms_hpp__


text:
/// @file
/// @copyright The code is licensed under the BSD License
///            <http://opensource.org/licenses/BSD-2-Clause>,
///            Copyright (c) 2013-2015 Alexandre Hamez.
/// @author Alexandre Hamez

#pragma once

#include <functional> // hash
#include <iosfwd>

#include <boost/dynamic_bitset.hpp>

namespace pnmc { namespace mc { namespace shared {

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

struct live
{
  const std::size_t index;
  boost::dynamic_bitset<>& bitset;

  template <typename T>
  T
  operator()(const T& val)
  const noexcept
  {
    bitset[index] = true;
    return val;
  }

  friend
  bool
  operator==(const live& lhs, const live& rhs)
  noexcept
  {
    return lhs.index == rhs.index;
  }

  friend
  std::ostream&
  operator<<(std::ostream& os, const live& l)
  {
    return os << "live(" << l.index << ")";
  }
};

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

}}} // namespace pnmc::mc::shared

namespace std
{

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

template <>
struct hash<pnmc::mc::shared::live>
{
  std::size_t
  operator()(const pnmc::mc::shared::live& l)
  const noexcept
  {
    using namespace sdd::hash;
    return seed(49979687) (val(l.index));
  }
};

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

} // namespace std

ext: hh

max_stars_repo_name: ahamez/pnmc

max_issues_repo_name: ahamez/pnmc

max_forks_repo_name: ahamez/pnmc


text:
//
// detail/mockup_serial_port_service.hpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//

#ifndef BOOST_ASIO_DETAIL_MOCKUP_SERIAL_PORT_SERVICE_HPP
#define BOOST_ASIO_DETAIL_MOCKUP_SERIAL_PORT_SERVICE_HPP

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

#include <string>
#include <deque>
#include <memory>
#include <boost/chrono.hpp>
#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <boost/asio/error.hpp>
#include <boost/asio/io_service.hpp>
#include <boost/asio/serial_port_base.hpp>
#include <boost/asio/streambuf.hpp>

#include <boost/asio/buffer.hpp>
#include <boost/asio/buffers_iterator.hpp>

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

#include <boost/thread/condition_variable.hpp>
#include <boost/thread/recursive_mutex.hpp>

#if defined(GENERATING_DOCUMENTATION)
# define BOOST_ASIO_OPTION_STORAGE implementation_defined
#elif defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
# define BOOST_ASIO_OPTION_STORAGE DCB
#else
# define BOOST_ASIO_OPTION_STORAGE termios
#endif

namespace boost {
namespace asio {
namespace detail {

// Extend mockup_descriptor_service to provide serial port support.
class mockup_serial_port_service
{
public:
  // The dummy native type of a serial port.
  typedef int native_handle_type;

  // The dummy implementation type of the serial port.
  struct implementation_type {

    // Each read handler that get registered, get's a work object associated,
    // to avoid io_service.run() from returning until the handler can effectively
    // be called
    typedef std::pair<boost::function<void ()>, io_service::work> read_handler_entry;

    // Thread specific values
    native_handle_type handle_ = -1;
    bool open_ = false;
    bool cancelled_ = false;

    // The buffer, it's mutex and condition_variable is shared by
    // multiple thread opening the same device name.
    std::shared_ptr<std::string> serial_line_simulation_buffer_in_
      = std::make_shared<std::string>();

    // io_service associated stack of handler to call in case a write occurs.
    std::shared_ptr<std::map<
      io_service*,
      std::shared_ptr<std::deque< read_handler_entry >>
    >> pending_read_handlers_
      = std::make_shared<std::map<
          io_service*,
          std::shared_ptr<std::deque< read_handler_entry >>
        >>();

    // Mutex to protect access the shared(_ptr) values
    std::shared_ptr<boost::recursive_mutex> mutex_
      = std::make_shared<boost::recursive_mutex>();

    // Condition variable to come back from a blocking read or a cancel faster.
    std::shared_ptr<boost::condition_variable> ready_read_
      = std::make_shared<boost::condition_variable>();
  };

  BOOST_ASIO_DECL mockup_serial_port_service(
      boost::asio::io_service& io_service);

  // Destroy all user-defined handler objects owned by the service.
  BOOST_ASIO_DECL void shutdown_service();

  // Construct a new serial port implementation.
  void construct(implementation_type& impl)
  {
  }

  // Move-construct a new serial port implementation.
  void move_construct(implementation_type& impl,
      implementation_type& other_impl)
  {
    impl.serial_line_simulation_buffer_in_ = other_impl.serial_line_simulation_buffer_in_;
  }

//  // Move-assign from another serial port implementation.
//  void move_assign(implementation_type& impl,
//      mockup_serial_port_service& other_service,
//      implementation_type& other_impl)
//  {
//    impl = other_service.fake_serial_;
//  }

  // Destroy a serial port implementation.
  void destroy(implementation_type& impl)
  {
  }

  // Open the serial port using the specified device name.
  BOOST_ASIO_DECL boost::system::error_code open(implementation_type& impl,
      const std::string& device, boost::system::error_code& ec);

  // Assign a native descriptor to a serial port implementation.
  boost::system::error_code assign(implementation_type& impl,
      const native_handle_type& native_descriptor,
      boost::system::error_code& ec)
  {
    throw std::runtime_error("Assigning from native handle is unsupported in mockup.");
  }

  // Determine whether the serial port is open.
  bool is_open(const implementation_type& impl) const
  {
    return impl.open_;
  }

  // Destroy a serial port implementation.
  boost::system::error_code close(implementation_type& impl,
      boost::system::error_code& ec)
  {
    cancel(impl, ec);
    impl.open_ = false;
    ec = boost::system::error_code();
    return ec;
  }

  // Get the native serial port representation.
  native_handle_type native_handle(implementation_type& impl)
  {
    return impl.handle_;
  }

  // Cancel all operations associated with the serial port.
  boost::system::error_code cancel(implementation_type& impl,
      boost::system::error_code& ec)
  {
    if (!is_open(impl))
    {
      ec = boost::asio::error::bad_descriptor;
      return ec;
    }

    impl.cancelled_ = true;

    { boost::recursive_mutex::scoped_lock lock{*impl.mutex_};

      auto pending_handlers = impl.pending_read_handlers_
        ->at(std::addressof(io_service_));

      while (!pending_handlers->empty()) {
        // operation_aborted will be passed as they
        // will notice all was cancelled
        io_service_.post(pending_handlers->back().first);
        pending_handlers->pop_back();
      }
    }

    impl.ready_read_->notify_all();

    ec = boost::system::error_code();
    return ec;
  }

  // Set an option on the serial port.
  template <typename SettableSerialPortOption>
  boost::system::error_code set_option(implementation_type& impl,
      const SettableSerialPortOption& option, boost::system::error_code& ec)
  {
    return do_set_option(impl,
        &mockup_serial_port_service::store_option<SettableSerialPortOption>,
        &option, ec);
  }

  // Get an option from the serial port.
  template <typename GettableSerialPortOption>
  boost::system::error_code get_option(const implementation_type& impl,
      GettableSerialPortOption& option, boost::system::error_code& ec) const
  {
    return do_get_option(impl,
        &mockup_serial_port_service::load_option<GettableSerialPortOption>,
        &option, ec);
  }

  // Send a break sequence to the serial port.
  boost::system::error_code send_break(implementation_type& impl,
      boost::system::error_code& ec)
  {
    ec = boost::asio::error::operation_not_supported;
    return ec;
  }

  // Write the given data. Returns the number of bytes sent.
  template <typename ConstBufferSequence>
  size_t write_some(implementation_type& impl,
      const ConstBufferSequence& buffers, boost::system::error_code& ec)
  {
    boost::recursive_mutex::scoped_lock lock{*impl.mutex_};

    if (impl.cancelled_) {
      ec = boost::asio::error::operation_aborted;
      return 0;
    }

    auto begin_bytes = boost::asio::buffers_iterator<ConstBufferSequence>::begin(buffers);
    auto end_bytes = boost::asio::buffers_iterator<ConstBufferSequence>::end(buffers);

    std::copy(begin_bytes, end_bytes, std::back_inserter(*impl.serial_line_simulation_buffer_in_));
    size_t bytes_transferred = std::distance(begin_bytes, end_bytes);

    for (auto& pending_handler : *impl.pending_read_handlers_) {
      while (!pending_handler.second->empty()) {
        pending_handler.first->post(pending_handler.second->back().first);
        pending_handler.second->pop_back();
      }
    }

    impl.ready_read_->notify_all();
    ec = boost::system::error_code();
    return bytes_transferred;
  }

  // Start an asynchronous write. The data being written must be valid for the
  // lifetime of the asynchronous operation.
  template <typename ConstBufferSequence, typename Handler>
  void async_write_some(implementation_type& impl,
      const ConstBufferSequence& buffers, Handler& handler)
  {

    auto perform_write = [&impl, buffers, handler, this]() mutable {
      boost::system::error_code ec{};
      auto bytes_written = write_some(impl, buffers, ec);
      handler(ec, bytes_written);
    };

    io_service_.post(perform_write);
  }

  // Read some data. Returns the number of bytes received.
  template <typename MutableBufferSequence>
  size_t read_some(implementation_type& impl,
      const MutableBufferSequence& buffers, boost::system::error_code& ec)
  {
    // empy out buffer is a no-op.
    buffer_sequence_adapter<boost::asio::mutable_buffer,
        MutableBufferSequence> bufs_adapted(buffers);
    if (bufs_adapted.all_empty()) {
      ec = boost::system::error_code();
      return 0;
    }

    bool bytes_available = false;
    { boost::recursive_mutex::scoped_lock lock{*impl.mutex_};
      bytes_available = !impl.serial_line_simulation_buffer_in_->empty();
    }

    while ( (!bytes_available) && (!impl.cancelled_) ) {
      // Wait for bytes to be available
      boost::mutex mutex_wait{};
      boost::mutex::scoped_lock wait_lock{mutex_wait};
      impl.ready_read_->wait_for(wait_lock, boost::chrono::milliseconds(5));

      { boost::recursive_mutex::scoped_lock lock{*impl.mutex_};
        bytes_available = !impl.serial_line_simulation_buffer_in_->empty();
      }

    }

    if (impl.cancelled_) {
      ec = boost::asio::error::operation_aborted;
      return 0;
    }

    { boost::recursive_mutex::scoped_lock lock{*impl.mutex_};

      size_t read_count = 0;

      for (auto buf : buffers) {
        char* bytes = boost::asio::buffer_cast<char*>(buf);
        auto bytes_to_read =  std::min(boost::asio::buffer_size(buf), impl.serial_line_simulation_buffer_in_->size());
        memcpy(bytes, impl.serial_line_simulation_buffer_in_->data(), bytes_to_read);
        impl.serial_line_simulation_buffer_in_->erase(0, bytes_to_read);

        read_count += bytes_to_read;
      }

      ec = boost::system::error_code();
      return read_count;
    }
  }

  // Start an asynchronous read. The buffer for the data being received must be
  // valid for the lifetime of the asynchronous operation.
  template <typename MutableBufferSequence, typename Handler>
  void async_read_some(implementation_type& impl,
      const MutableBufferSequence& buffers, Handler& handler)
  {

    boost::function<void ()> perform_read = [&impl, buffers, handler, this]() mutable {
      boost::system::error_code ec{};
      auto bytes_read = read_some(impl, buffers, ec);
      handler(ec, bytes_read);
    };

    { boost::recursive_mutex::scoped_lock lock{*impl.mutex_};
      impl.pending_read_handlers_
        ->at(std::addressof(io_service_))
        ->push_front(std::make_pair(perform_read, io_service::work(io_service_)));
    }
  }

private:

  // Function pointer type for storing a serial port option.
  typedef boost::system::error_code (*store_function_type)(
      const void*, BOOST_ASIO_OPTION_STORAGE&, boost::system::error_code&);

  // Helper function template to store a serial port option.
  template <typename SettableSerialPortOption>
  static boost::system::error_code store_option(const void* option,
      BOOST_ASIO_OPTION_STORAGE& storage, boost::system::error_code& ec)
  {
    return static_cast<const SettableSerialPortOption*>(option)->store(
        storage, ec);
  }

  // Helper function to set a serial port option.
  BOOST_ASIO_DECL boost::system::error_code do_set_option(
      implementation_type& impl, store_function_type store,
      const void* option, boost::system::error_code& ec);

  // Function pointer type for loading a serial port option.
  typedef boost::system::error_code (*load_function_type)(
      void*, const BOOST_ASIO_OPTION_STORAGE&, boost::system::error_code&);

  // Helper function template to load a serial port option.
  template <typename GettableSerialPortOption>
  static boost::system::error_code load_option(void* option,
      const BOOST_ASIO_OPTION_STORAGE& storage, boost::system::error_code& ec)
  {
    return static_cast<GettableSerialPortOption*>(option)->load(storage, ec);
  }

  // Helper function to get a serial port option.
  BOOST_ASIO_DECL boost::system::error_code do_get_option(
      const implementation_type& impl, load_function_type load,
      void* option, boost::system::error_code& ec) const;

  io_service& io_service_;
  BOOST_ASIO_OPTION_STORAGE termios_storage;
};

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

#include <pre/boost/asio/detail/impl/mockup_serial_port_service.ipp>

#endif // BOOST_ASIO_DETAIL_MOCKUP_SERIAL_PORT_SERVICE_HPP

max_stars_repo_name: xplorfin/lib-cpp-pre

max_issues_repo_name: xplorfin/lib-cpp-pre

max_forks_repo_name: xplorfin/lib-cpp-pre


text:
#define CONTRACT_DISABLE_POSTCONDITIONS
#include <contract/contract.hpp>

#include "contract_error.hpp"

#include <boost/test/unit_test.hpp>

namespace
{

void test_disable_postconditions()
{
    contract (fun) { postcondition(false); };
}

void test_disable_postconditions_precondition()
{
    contract (fun) { precondition(false); };
}

void test_disable_postconditions_invariant()
{
    contract (fun) { invariant(false); };
}

}

BOOST_AUTO_TEST_CASE(macro_disable_postconditions)
{
    test::contract_handler_frame cframe;

    // expect disabled postcondition
    BOOST_CHECK_NO_THROW(test_disable_postconditions());

    // expect precondition to fail
    BOOST_CHECK_THROW(test_disable_postconditions_precondition(),
                      test::contract_error);

    // expect invariant to fail
    BOOST_CHECK_THROW(test_disable_postconditions_invariant(),
                      test::contract_error);
}

// Copyright Alexei Zakharov, 2013.
//
// 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)

max_stars_repo_name: alexeiz/contract

max_issues_repo_name: idfumg/contract

max_forks_repo_name: idfumg/contract


text:
//
// Created by Nicholas Newdigate on 18/07/2020.
//

#ifndef TEENSY_RESAMPLING_SDREADER_READER_MONO_LOOP_TESTS_CPP
#define TEENSY_RESAMPLING_SDREADER_READER_MONO_LOOP_TESTS_CPP
#include <boost/test/unit_test.hpp>
#include "ResamplingReaderFixture.h"

BOOST_AUTO_TEST_SUITE(test_raw_mono_loop_forward_playback)

    BOOST_FIXTURE_TEST_CASE(ReadForwardLoopAtRegularPlaybackRate, ResamplingReaderFixture) {

        const uint32_t expectedDataSize = 32; // 32 16bit samples = 64 bytes of space
        printf("ReadForwardAtRegularPlaybackRate(%d)\n", expectedDataSize);
        int16_t expected[expectedDataSize];
        for (int16_t i = 0; i < expectedDataSize; i++) {
            expected[i] = i;
        }
        SD.setSDCardFileData((char*) expected, expectedDataSize * 2);

        resamplingSdReader->begin();
        resamplingSdReader->setPlaybackRate(1.0);
        resamplingSdReader->playRaw("test2.bin", 1);
        resamplingSdReader->setLoopType(looptype_repeat);
        int16_t actual[256];
        int16_t *buffers[1] = { actual };
        int j = 0, samplesRead = 0, total_bytes_read = 0, currentExpected = 0;
        bool assertionsPass = true;
        do {
            samplesRead = resamplingSdReader->read((void**)buffers, 256 ); // 256 samples
            total_bytes_read += samplesRead * 2;
            printf("j:%d samplesRead: %d \n", j, samplesRead);

            for (int i=0; i < samplesRead; i++) {
                printf("\t\t[%x]:%x", currentExpected, actual[i]);

                if (currentExpected != actual[i]) {
                    assertionsPass = false;
                    BOOST_FAIL("Value not as expected!!!");
                }

                currentExpected++;
                currentExpected %= expectedDataSize;
            }

            printf("\n");
            j++;
        } while (j < 100);
        printf("total_bytes_read: %d \n", total_bytes_read);
        resamplingSdReader->close();

    }

    BOOST_FIXTURE_TEST_CASE(ReadForwardLoopAtHalfPlaybackRate, ResamplingReaderFixture) {

        const uint32_t size_of_datasource = 800;
        printf("ReadForwardAtRegularPlaybackRate(%d)\n", size_of_datasource);
        int16_t dataSource[size_of_datasource];
        for (int16_t i = 0; i < size_of_datasource; i++) {
            dataSource[i] = i;
        }
        SD.setSDCardFileData((char*) dataSource, size_of_datasource * 2);

        const int16_t expectedSize = size_of_datasource * 2;
        int16_t expected[expectedSize];
        for (int16_t i = 0; i < expectedSize; i++) {
            expected[i] = i / 2;
        }

        resamplingSdReader->begin();
        resamplingSdReader->setPlaybackRate(0.5);
        resamplingSdReader->playRaw("test2.bin", 1);
        resamplingSdReader->setLoopType(looptype_none);
        int16_t actual[expectedSize];
        int16_t *buffers[1] = { actual };
        int j = 0, samplesRead = 0, total_bytes_read = 0;
        do {
            samplesRead = resamplingSdReader->read((void**)buffers, 256 );
            total_bytes_read += samplesRead * 2;
            printf("j:%d samplesRead: %d: ", j, samplesRead);
            for (int i=0; i < samplesRead; i++) {
                printf("\t\t[%x]:%x", expected[j * 256 + i], actual[i]);
            }
            printf("\n");

            if (samplesRead != 0)
                BOOST_CHECK_EQUAL_COLLECTIONS(&expected[j * 256], &expected[j * 256 + samplesRead - 1], &actual[0], &actual[samplesRead - 1]);
            j++;
        } while (samplesRead > 0);
        printf("total_bytes_read: %d \n", total_bytes_read);
        resamplingSdReader->close();
    }

BOOST_AUTO_TEST_SUITE_END()

#endif //TEENSY_RESAMPLING_SDREADER_READER_MONO_LOOP_TESTS_CPP

max_stars_repo_name: newdigate/teensy-resampling-sdreader

max_issues_repo_name: newdigate/teensy-resampling-sdreader

max_forks_repo_name: newdigate/teensy-resampling-sdreader


text:
// remopts_common.cc
#include "remopts_common.h"
#include "remopts_log.h"
#include "remopts_messages.h"
#include <boost/algorithm/hex.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/trim_all.hpp>
#include <curl/curl.h>
#include <stdbool.h>

using namespace isc::log;

namespace isc {
namespace remopts {

std::string gethexOptionPtr(const isc::dhcp::OptionPtr opt) {
  std::string hex_str = opt->toHexString();
  boost::algorithm::erase_head(hex_str, 2); // get rid of '0x' header

  return hex_str;
}

std::string unhexOptionPtr(const isc::dhcp::OptionPtr opt) {
  std::string hex_str = gethexOptionPtr(opt);
  std::string str = boost::algorithm::unhex(hex_str);

  return str;
}

std::string sstrim(const std::stringstream &ss) {
  std::string s = ss.str();
  boost::algorithm::erase_all(s, "\n");
  boost::algorithm::trim_all(s);
  return s;
}

bool make_curl_request(const std::string &request, std::stringstream &ss) {
  // Variables related to curl (there are "C" variables)
  CURL *curl;
  CURLcode res;
  struct curl_slist *list = NULL;
  int curl_opt_res = 0;

  // "C" varaibles.
  char *bp;
  size_t size;
  FILE *response_memfile;

  curl_global_init(CURL_GLOBAL_DEFAULT);
  curl = curl_easy_init();
  if (!curl) {
    curl_global_cleanup();
    LOG_ERROR(remopts_logger, REMOPTS_CURL)
        .arg("Could not initialize curl");
    return false;
  }

  list = curl_slist_append(list, "Accept: application/json");
  if (list == NULL) {
    curl_easy_cleanup(curl);
    curl_global_cleanup();
    LOG_ERROR(remopts_logger, REMOPTS_CURL)
        .arg("Could not create curl slist.");
    return false;
  }

  response_memfile = open_memstream(&bp, &size);
  if (response_memfile == NULL) {
    curl_easy_cleanup(curl);
    curl_global_cleanup();
    LOG_ERROR(remopts_logger, REMOPTS_CURL)
        .arg("Could not create memfile.");
    return false;
  }

  // If we don't set a timeout, curl will try for 300 seconds by default.
  curl_opt_res += curl_easy_setopt(curl, CURLOPT_TIMEOUT, 1L);
  curl_opt_res += curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 1L);
  // libcurl's docs say to cast as void, don't blame me.
  curl_opt_res +=
      curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)response_memfile);
  // CURLOPT_URL takes a char*
  curl_opt_res += curl_easy_setopt(curl, CURLOPT_URL, (request).c_str());
  curl_opt_res += curl_easy_setopt(curl, CURLOPT_HTTPHEADER, list);

#ifdef SKIP_PEER_VERIFICATION
  curl_opt_res += curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
#endif

#ifdef SKIP_HOSTNAME_VERIFICATION
  curl_opt_res += curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);
#endif

  if (curl_opt_res > 0) {
    fclose(response_memfile);
    free(bp);
    curl_easy_cleanup(curl);
    curl_global_cleanup();
    LOG_ERROR(remopts_logger, REMOPTS_CURL)
        .arg("Error setting curl options.");
    return false;
  }

  res = curl_easy_perform(curl);
  // Check for errors
  if (res != CURLE_OK) {
    fclose(response_memfile);
    free(bp);
    curl_easy_cleanup(curl);
    curl_global_cleanup();
    return false;
  }

  // make bp available for reading.
  fclose(response_memfile);
  curl_easy_cleanup(curl);
  curl_global_cleanup();
  ss << bp;
  free(bp);
  return true;
}

} // namespace remopts
} // namespace isc


text:
/**
 * KalmanFilter.hpp
 * @author : koide
 * 13/08/04
 **/
#ifndef KKL_KALMAN_FILTER_HPP
#define KKL_KALMAN_FILTER_HPP

#include <Eigen/Dense>

namespace kkl{
  namespace alg{

/*****************************************************
 * Kalman filter
 * T : type of scalar
 * stateDim : dimension of the state
 * inputDim : dimension of the input
 * measurementDim : dimension of the observation
*****************************************************/
template<typename T, int stateDim, int inputDim, int measurementDim>
class KalmanFilter{
  const static int N = stateDim;
  const static int M = inputDim;
  const static int K = measurementDim;

  typedef Eigen::Matrix<T, N, 1> VectorN;
  typedef Eigen::Matrix<T, M, 1> VectorM;
  typedef Eigen::Matrix<T, K, 1> VectorK;
  typedef Eigen::Matrix<T, N, N> MatrixNN;
  typedef Eigen::Matrix<T, N, M> MatrixNM;
  typedef Eigen::Matrix<T, K, K> MatrixKK;
  typedef Eigen::Matrix<T, K, N> MatrixKN;
  typedef Eigen::Matrix<T, N, K> MatrixNK;
public:

  /*****************************************************************
   * constructor
   * transition		 : state transition matrix
   * control			 : input response matrix
   * measurement		 : observation matrix
   * processNoise		 : process noise covariance matrix
   * measurementNoise  : measurement noise covariance matrix
   * mean				 : initial mean
   * cov				 : initial covariance matrix
  *****************************************************************/
  KalmanFilter( const MatrixNN& transition, const MatrixNM& control, const MatrixKN& measurement, const MatrixNN& processNoise, const MatrixKK& measurementNoise, const VectorN& mean, const MatrixNN& cov )
    : mean( mean ),
    cov( cov ),
    transitionMatrix( transition ),
    controlMatrix( control ),
    measurementMatrix( measurement ),
    processNoiseCov( processNoise ),
    measurementNoiseCov( measurementNoise ){}

  EIGEN_MAKE_ALIGNED_OPERATOR_NEW

  /*****************************************************************
   * predict
   * control : input
  *****************************************************************/
  void predict( const VectorM& control ){
    const auto& A = transitionMatrix;
    const auto& B = controlMatrix;
    const auto& R = processNoiseCov;

    const auto& u = control;

    mean = A * mean + B * u;
    cov = A * cov * A.transpose() + R;
  }

  /*****************************************************************
   * correct
   * measurement : measurement vector
  *****************************************************************/
  void correct( const VectorK& measurement ){
    const auto& C = measurementMatrix;
    const auto& Q = measurementNoiseCov;

    kalmanGain = cov * C.transpose() * ( C * cov * C.transpose() + Q ).inverse();
    const auto& K = kalmanGain;

    mean = mean + K * ( measurement - C * mean );
    cov = ( MatrixNN::Identity() - K * C ) * cov;
  }

  /*			getter			*/
  const VectorN& getMean() const { return mean; }
  const MatrixNN& getCov() const { return cov; }

  const MatrixNN& getTransitionMatrix() const { return transitionMatrix; }
  const MatrixNM& getControlMatrix() const { return controlMatrix; }
  const MatrixKN& getMeasurementMatrix() const { return measurementMatrix; }

  const MatrixNN& getProcessNoiseCov() const { return processNoiseCov; }
  const MatrixKK& getMeasurementNoiseCov() const { return measurementNoiseCov; }

  const MatrixNK& getKalmanGain() const { return kalmanGain; }

  /*			setter			*/
  KalmanFilter& setMean( const VectorN& m ){ mean = m;			return *this; }
  KalmanFilter& setCov( const MatrixNN& s ){ cov = s;			return *this; }

  KalmanFilter& setTransitionMatrix( const MatrixNN& t ){ transitionMatrix = t;	return *this; }
  KalmanFilter& setControlMatrix( const MatrixNM& c ){ controlMatrix = c;			return *this; }
  KalmanFilter& setMeasurementMatrix( const MatrixKN& m ){ measurementMatrix = m;	return *this; }

  KalmanFilter& setProcessNoiseCov( const MatrixNN& p ){ processNoiseCov = p;			return *this; }
  KalmanFilter& setMeasurementNoiseCov( const MatrixKK& m ){ measurementNoiseCov = m;	return *this; }
public:
  VectorN mean;			// mean of the state
  MatrixNN cov;			// covariance of the state

  MatrixNN transitionMatrix;		//
  MatrixNM controlMatrix;			//
  MatrixKN measurementMatrix;		//
  MatrixNN processNoiseCov;		//
  MatrixKK measurementNoiseCov;	//

private:
  MatrixNK kalmanGain;
};
  }
}

#endif


text:
// Copyright (c) 2020 fortiss GmbH
//
// Authors: Julian Bernhard, Klemens Esterle, Patrick Hart and
// Tobias Kessler
//
// This work is licensed under the terms of the MIT license.
// For a copy, see <https://opensource.org/licenses/MIT>.

#ifndef BARK_MODELS_EXECUTION_MPC_COST_FUNCTOR_HPP_
#define BARK_MODELS_EXECUTION_MPC_COST_FUNCTOR_HPP_

#include <Eigen/Dense>
#include <iostream>
#include "bark/models/execution/mpc/common.hpp"

namespace bark {
namespace models {
namespace execution {
using namespace bark::models::dynamic;

template <typename T>
inline Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> KinematicModel(
    T const* const* parameters,
    bark::models::dynamic::Trajectory desired_trajectory,
    const OptimizationSettings& optimization_settings) {
  Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> traj =
      desired_trajectory.cast<T>();

  // TODO: Lf als Parameter
  T Lf = T(2.6);

  for (int i = 1; i < optimization_settings.num_optimization_steps; i++) {
    Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> f_dot(1, 5);

    // fill matrix
    f_dot << T(1),  // (0) t' = 1
        traj(i - 1, StateDefinition::VEL_POSITION) *
            cos(traj(
                i - 1,
                StateDefinition::THETA_POSITION)),  // (1) x_dot = v*cos(psi)
        traj(i - 1, StateDefinition::VEL_POSITION) *
            sin(traj(
                i - 1,
                StateDefinition::THETA_POSITION)),  // (2) y_dot = v*sin(psi)
        tan(parameters[1][i - 1]) / Lf,  // (3) theta_dot = tan(delta)/Lf
        parameters[0][i - 1];            // (4) v_dot = a

    traj.block(i, 0, 1, 5) =
        traj.block(i - 1, 0, 1, 5) + T(optimization_settings.dt) * f_dot;
  }
  return traj;
}

struct CostFunctor {
  template <typename T>
  bool operator()(T const* const* parameters, T* residual) {
    // initialize
    T cost = T(0.0);
    Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> traj = KinematicModel(
        parameters, desired_discrete_states_, optimization_settings_);
    Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> desired_discrete_states =
        desired_discrete_states_.cast<T>();
    Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> weights =
        weights_.cast<T>();

    // offsets
    for (int i = 0; i < optimization_settings_.num_optimization_steps - 1;
         i++) {
      T xDiff, yDiff, thetaDiff, velDiff;
      xDiff = traj(i, StateDefinition::X_POSITION) -
              desired_discrete_states(i, StateDefinition::X_POSITION);
      yDiff = traj(i, StateDefinition::Y_POSITION) -
              desired_discrete_states(i, StateDefinition::Y_POSITION);
      thetaDiff = traj(i, StateDefinition::THETA_POSITION) -
                  desired_discrete_states(i, StateDefinition::THETA_POSITION);
      velDiff = traj(i, StateDefinition::VEL_POSITION) -
                desired_discrete_states(i, StateDefinition::VEL_POSITION);

      cost += weights(i, StateDefinition::X_POSITION) * xDiff * xDiff;
      cost += weights(i, StateDefinition::Y_POSITION) * yDiff * yDiff;
      cost +=
          weights(i, StateDefinition::THETA_POSITION) * thetaDiff * thetaDiff;
      cost += weights(i, StateDefinition::VEL_POSITION) * velDiff * velDiff;
    }

    // differential values
    // TODO(@all): seperate weights
    T weights_acc = T(1e1);
    T weights_delta = T(1);
    for (int i = 0; i < optimization_settings_.num_optimization_steps - 1;
         i++) {
      cost +=
          weights_acc * parameters[0][i] * parameters[0][i];  // acceleration
      cost += weights_delta * parameters[1][i] * parameters[1][i];  // steering
    }

    residual[0] = cost / (weights.sum() +
                          (weights_acc + weights_delta) *
                              T(optimization_settings_.num_optimization_steps));
    return true;
  }

  bool set_desired_states(
      const bark::models::dynamic::Trajectory& desired_states) {
    desired_discrete_states_ = desired_states;
    return true;
  }

  bool set_optimization_settings(
      const OptimizationSettings& optimization_settings) {
    optimization_settings_ = optimization_settings;
    return true;
  }

  bool set_weights(
      const Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> weights) {
    weights_ = weights;
    return true;
  }

  bark::models::dynamic::Trajectory desired_discrete_states_;
  Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> weights_;
  OptimizationSettings optimization_settings_;
};

}  // namespace execution
}  // namespace models
}  // namespace bark

#endif  // BARK_MODELS_EXECUTION_MPC_COST_FUNCTOR_HPP_

max_stars_repo_name: RdecKa/bark

max_issues_repo_name: RdecKa/bark

max_forks_repo_name: RdecKa/bark


text:
#include "stocks.h"

#include <boost/random.hpp>
#include <ctime>

int random_int(int start, int end, bool generateNewSeed)
{
	static boost::random::mt19937 generator;
	static bool seedWasGenerated = false;

	if(generateNewSeed) seedWasGenerated = false;
	if(!seedWasGenerated)
	{
		generator.seed(std::time(nullptr));
		seedWasGenerated = true;
	}
	boost::uniform_int<> uni_dist(start,end);
	boost::variate_generator<boost::random::mt19937&, boost::uniform_int<> > uni(generator, uni_dist);
	return uni();
}

bool is_string_empty(const std::string &str)
{
	for(char character : str)
	{
		if(!isspace(character))
			return false;
	}
	return true;
}

std::__cxx11::string trim(const std::string &srcStr,const short type)
{
	std::string str(srcStr);
	if(type <= 0)
	{
		for(auto it = str.begin(); it!=str.end();) // TODO: Optimize regular cycle
		{
			if(!isspace(*it))
				break;
			it = str.erase(it);
		}
	}

	typedef std::string::reverse_iterator riter;
	if(type >= 0)
	{
		for(auto it = str.rbegin(); it!=str.rend();) // TODO: Optimize reverse cycle
		{
			if(!isspace(*it))
				break;
			it = riter( str.erase(std::next(it).base()) );
		}
	}
	return str;
}

std::pair<std::string, std::string> string_tok(const std::string &str, const std::string &delimiter, bool toTrim)
{
	std::pair<std::string, std::string> returnValue;
	int delimiterPos = str.find_first_of(delimiter);
	if(delimiterPos > 0)
	{
		returnValue.first = str.substr(0, delimiterPos);
		returnValue.second = str.substr(delimiterPos+delimiter.size());
		if (toTrim)
		{
			returnValue.first = trim(returnValue.first, 0);
			returnValue.second = trim(returnValue.second, 0);
		}
	}
	return returnValue;
}

void msleep(uint delay)
{
	usleep(1000 * delay);
}

max_stars_repo_name: In-line/TelegramTestBot

max_issues_repo_name: In-line/TelegramTestBot

max_forks_repo_name: In-line/TelegramTestBot


text:
/*
 * Copyright (c) 2008, Willow Garage, Inc.
 * 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 Willow Garage, Inc. 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 OWNER 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.
 */

/*
 * This file contains helper functions for loading images as maps.
 *
 * Author: Brian Gerkey
 * 2nd author: Giorgio Grisetti
 */

#include "map_server/image_loader.h"
#include <Eigen/Geometry>
#include <cstring>
#include <opencv2/opencv.hpp>
#include <stdexcept>
#include <stdio.h>
#include <stdlib.h>

// compute linear index for given map coords
#define MAP_IDX(sx, i, j) ((sx) * (j) + (i))

// IASTIMIA: gg: non ho mai visto tanta merda cosi' concentrata in un unico file

namespace map_server {

  template <typename PixelType>
  void getAvgAlpha(uint8_t& avg, uint8_t& alpha, const PixelType& p) {
    float accumulator = 0;
    static constexpr int avg_channels =
      PixelType::channels < 3 ? PixelType::channels : PixelType::channels - 1;
    static constexpr int alpha_channel = PixelType::channels > 3 ? 3 : -1;
    alpha                              = alpha_channel > -1 ? p(alpha_channel) : 0;

    for (int i = 0; i < avg_channels; ++i) {
      accumulator += (float) p(i);
    }
    avg = (uint8_t)(accumulator / avg_channels);
  }

  template <int num_channels>
  bool fillMapFromImage(nav_msgs::GetMap::Response& dest,
                        const cv::Mat src,
                        float occ_th,
                        float free_th,
                        bool negate  = false,
                        MapMode mode = TRINARY) {
    if (src.type() != CV_8UC1 && src.type() != CV_8UC3 && src.type() != CV_8UC4) {
      std::cerr << "cannot handle image of type [:" << src.type() << "]" << std::endl;
      std::cerr << "known types are :" << CV_8UC1 << " " << CV_8UC3 << " " << CV_8UC4 << std::endl;
      return false;
    }
    if (num_channels != src.channels()) {
      std::cerr << "cannot handle image with [:" << src.channels() << "] channels" << std::endl;
    }
    dest.map.info.width  = src.cols;
    dest.map.info.height = src.rows;

    using PixelType = cv::Vec<uint8_t, num_channels>;
    dest.map.data.resize(src.rows * src.cols);
    for (int r = 0; r < src.rows; ++r) {
      int8_t* dptr = &dest.map.data[src.cols * (src.rows - r - 1)]; // this is sick
      for (int c = 0; c < src.cols; ++c, ++dptr) {
        uint8_t avg, alpha;
        getAvgAlpha(avg, alpha, src.at<PixelType>(r, c));
        int8_t out = -1; // default output occupancy (unknown)
        // if alpha channel >0 process the occupancy
        if (alpha > 0) {
          if (!negate) {
            avg = 255 - avg;
          }
          float avg_f = (float) avg / (float) 255.f;
          float occ_f = std::max(0.f, (float) (avg_f - free_th) / (float) (occ_th - free_th));
          occ_f       = std::min(1.f, occ_f);
          switch (mode) {
            case RAW:
              out = avg;
              break;
            case SCALE:
              out = occ_f * 100;
              break;
            case TRINARY:
              if (occ_f > occ_th)
                out = 100;
              else if (occ_f <= free_th)
                out = 0;
              break;
          }
        }
        *dptr = out;
      }
    }
    return true;
  }

#if CV_VERSION_MAJOR < 4
#define IMAGE_READ_MODE CV_LOAD_IMAGE_UNCHANGED
#else
#define IMAGE_READ_MODE cv::IMREAD_UNCHANGED
#endif

  void loadMapFromFile(nav_msgs::GetMap::Response* resp,
                       const char* fname,
                       double res,
                       bool negate,
                       double occ_th,
                       double free_th,
                       double* origin,
                       MapMode mode) {
    cv::Mat img = cv::imread(fname, IMAGE_READ_MODE);

    bool result = false;
    switch (img.channels()) {
      case 1:
        result = fillMapFromImage<1>(*resp, img, occ_th, free_th, negate, mode);
        break;
      case 3:
        result = fillMapFromImage<3>(*resp, img, occ_th, free_th, negate, mode);
        break;
      case 4:
        result = fillMapFromImage<4>(*resp, img, occ_th, free_th, negate, mode);
        break;
      default:
        std::cerr << "cannot handle image of type [:" << img.type() << "]" << std::endl;
    }
    if (!result) {
      std::cerr << "issue in converting map" << std::endl;
      return;
    }
    // Copy the image data into the map structure
    resp->map.info.resolution        = res;
    resp->map.info.origin.position.x = origin[0];
    resp->map.info.origin.position.y = origin[1];
    resp->map.info.origin.position.z = 0.0;
    Eigen::AngleAxisf rot(origin[2], Eigen::Vector3f::UnitZ());
    Eigen::Quaternionf q(rot.toRotationMatrix());
    resp->map.info.origin.orientation.w = q.w();
    resp->map.info.origin.orientation.x = q.x();
    resp->map.info.origin.orientation.y = q.y();
    resp->map.info.origin.orientation.z = q.z();
  }
} // namespace map_server


text:
//
// Copyright © 2017 Arm Ltd. All rights reserved.
// See LICENSE file in the project root for full license information.
//
#include "Network.hpp"
#include "Graph.hpp"
#include "Layer.hpp"
#include "backends/CpuTensorHandle.hpp"
#include "backends/WorkloadFactory.hpp"
#include "Optimizer.hpp"

#include <armnn/Utils.hpp>

#include <fcntl.h>
#include <algorithm>
#include <fstream>
#include <memory>

#include <boost/assert.hpp>
#include <boost/format.hpp>
#include <boost/log/trivial.hpp>
#include <boost/numeric/conversion/converter_policies.hpp>
#include <boost/cast.hpp>

namespace armnn
{

armnn::INetwork* INetwork::CreateRaw()
{
    return new Network();
}

armnn::INetworkPtr INetwork::Create()
{
    return INetworkPtr(CreateRaw(), &INetwork::Destroy);
}

void INetwork::Destroy(INetwork* network)
{
    delete boost::polymorphic_downcast<Network*>(network);
}

Status Network::PrintGraph()
{
    m_Graph->Print();
    return Status::Success;
}

void IOptimizedNetwork::Destroy(IOptimizedNetwork* network)
{
    delete boost::polymorphic_downcast<OptimizedNetwork*>(network);
}

Status OptimizedNetwork::PrintGraph()
{
    m_Graph->Print();
    return Status::Success;
}

Status OptimizedNetwork::SerializeToDot(std::ostream& stream) const
{
    return m_Graph->SerializeToDot(stream);
}

IOptimizedNetworkPtr Optimize(const INetwork& inNetwork, const DeviceSpec& deviceSpec)
{
    const Network& network = *boost::polymorphic_downcast<const Network*>(&inNetwork);
    std::unique_ptr<Graph> graph = std::make_unique<Graph>(network.GetGraph());

    OptimizedNetwork* optNet = new OptimizedNetwork(std::move(graph));

    Optimizer::Optimize(optNet->GetGraph());

    // Infer the tensor infos for all output slots. Throws an exception on failure.
    optNet->GetGraph().InferTensorInfos();

    // Assign a compute device for all nodes
    for (auto&& layer : optNet->GetGraph())
    {
        DataType dataType = layer->GetDataType();

        // Default to the user-requested compute device from the Runtime
        layer->SetComputeDevice(deviceSpec.DefaultComputeDevice);

        // If the layer is unsupported by this device, fall back to reference
        std::string reasonIfUnsupported;
        if (!IWorkloadFactory::IsLayerSupported(*layer, dataType, reasonIfUnsupported))
        {
            BOOST_LOG_TRIVIAL(warning) << "Layer of type " << GetLayerTypeAsCString(layer->GetType()) <<
                " is not supported on requested backend " << layer->GetComputeDevice() << " (reason: " <<
                reasonIfUnsupported << "), falling back to CpuRef backend.";
            layer->SetComputeDevice(Compute::CpuRef);
        }

        BOOST_ASSERT_MSG(IWorkloadFactory::IsLayerSupported(*layer, dataType, reasonIfUnsupported),
            "Layer has no valid compute device");
    }

    optNet->GetGraph().AddCopyLayers();

    return {optNet, &IOptimizedNetwork::Destroy};
}

Network::Network()
: m_Graph(std::make_unique<Graph>())
{
}

Network::~Network()
{
}

IConnectableLayer* Network::AddInputLayer(LayerBindingId id, const char* name)
{
    return m_Graph->AddLayer<InputLayer>(id, name);
}

IConnectableLayer* Network::AddFullyConnectedLayerImpl(const FullyConnectedDescriptor& fullyConnectedDescriptor,
    const ConstTensor& weights,
    const ConstTensor* biases,
    const char* name)
{
    if (fullyConnectedDescriptor.m_BiasEnabled && (biases == nullptr))
    {
        throw InvalidArgumentException("AddFullyConnectedLayer: biases cannot be NULL");
    }

    const auto layer = m_Graph->AddLayer<FullyConnectedLayer>(fullyConnectedDescriptor, name);

    layer->m_Weight = std::make_unique<ScopedCpuTensorHandle>(weights);

    if (fullyConnectedDescriptor.m_BiasEnabled)
    {
        layer->m_Bias = std::make_unique<ScopedCpuTensorHandle>(*biases);
    }

    return layer;
}

IConnectableLayer* Network::AddFullyConnectedLayer(const FullyConnectedDescriptor& fullyConnectedDescriptor,
    const ConstTensor& weights,
    const char* name)
{
    return AddFullyConnectedLayerImpl(fullyConnectedDescriptor, weights, nullptr, name);
}

IConnectableLayer* Network::AddFullyConnectedLayer(const FullyConnectedDescriptor& fullyConnectedDescriptor,
    const ConstTensor& weights,
    const ConstTensor& biases,
    const char* name)
{
    return AddFullyConnectedLayerImpl(fullyConnectedDescriptor, weights, &biases, name);
}

IConnectableLayer* Network::AddConvolution2dLayerImpl(const Convolution2dDescriptor& convolution2dDescriptor,
    const ConstTensor& weights,
    const ConstTensor* biases,
    const char* name)
{
    if (convolution2dDescriptor.m_BiasEnabled && (biases == nullptr))
    {
        throw InvalidArgumentException("AddConvolution2dLayer: biases cannot be NULL");
    }

    const auto layer = m_Graph->AddLayer<Convolution2dLayer>(convolution2dDescriptor, name);

    layer->m_Weight = std::make_unique<ScopedCpuTensorHandle>(weights);

    if (convolution2dDescriptor.m_BiasEnabled)
    {
        layer->m_Bias = std::make_unique<ScopedCpuTensorHandle>(*biases);
    }

    return layer;
}

IConnectableLayer* Network::AddConvolution2dLayer(const Convolution2dDescriptor& convolution2dDescriptor,
    const ConstTensor& weights,
    const char* name)
{
    return AddConvolution2dLayerImpl(convolution2dDescriptor, weights, nullptr, name);
}
IConnectableLayer* Network::AddConvolution2dLayer(const Convolution2dDescriptor& convolution2dDescriptor,
    const ConstTensor& weights,
    const ConstTensor& biases,
    const char* name)
{
    return AddConvolution2dLayerImpl(convolution2dDescriptor, weights, &biases, name);
}

IConnectableLayer* Network::AddDepthwiseConvolution2dLayerImpl(
    const DepthwiseConvolution2dDescriptor& convolution2dDescriptor,
    const ConstTensor& weights,
    const ConstTensor* biases,
    const char* name)
{
    if (convolution2dDescriptor.m_BiasEnabled && (biases == nullptr))
    {
        throw InvalidArgumentException("AddDepthwiseConvolution2dLayer: biases cannot be NULL");
    }

    const auto layer = m_Graph->AddLayer<DepthwiseConvolution2dLayer>(convolution2dDescriptor, name);

    layer->m_Weight = std::make_unique<ScopedCpuTensorHandle>(weights);

    if (convolution2dDescriptor.m_BiasEnabled)
    {
        layer->m_Bias = std::make_unique<ScopedCpuTensorHandle>(*biases);
    }

    return layer;
}

IConnectableLayer* Network::AddDepthwiseConvolution2dLayer(
    const DepthwiseConvolution2dDescriptor& convolution2dDescriptor,
    const ConstTensor& weights,
    const char* name)
{
    return AddDepthwiseConvolution2dLayerImpl(convolution2dDescriptor, weights, nullptr, name);
}
IConnectableLayer* Network::AddDepthwiseConvolution2dLayer(
    const DepthwiseConvolution2dDescriptor& convolution2dDescriptor,
    const ConstTensor& weights,
    const ConstTensor& biases,
    const char* name)
{
    return AddDepthwiseConvolution2dLayerImpl(convolution2dDescriptor, weights, &biases, name);
}

IConnectableLayer* Network::AddPermuteLayer(const PermuteDescriptor& permuteDescriptor,
                                            const char* name)
{
    return m_Graph->AddLayer<PermuteLayer>(permuteDescriptor, name);
}

IConnectableLayer* Network::AddPooling2dLayer(const Pooling2dDescriptor& pooling2dDescriptor,
    const char* name)
{
    return m_Graph->AddLayer<Pooling2dLayer>(pooling2dDescriptor, name);
}

IConnectableLayer* Network::AddActivationLayer(const ActivationDescriptor& activationDescriptor,
    const char* name)
{
    return m_Graph->AddLayer<ActivationLayer>(activationDescriptor, name);
}

IConnectableLayer* Network::AddNormalizationLayer(const NormalizationDescriptor& normalizationDescriptor,
    const char* name)
{
    return m_Graph->AddLayer<NormalizationLayer>(normalizationDescriptor, name);
}

IConnectableLayer* Network::AddSoftmaxLayer(const SoftmaxDescriptor& softmaxDescriptor,
    const char* name)
{
    return m_Graph->AddLayer<SoftmaxLayer>(softmaxDescriptor, name);
}

IConnectableLayer* Network::AddSplitterLayer(const ViewsDescriptor& splitterDescriptor,
    const char* name)
{
    return m_Graph->AddLayer<SplitterLayer>(splitterDescriptor, name);
}

IConnectableLayer* Network::AddMergerLayer(const OriginsDescriptor& mergerDescriptor,
    const char* name)
{
    return m_Graph->AddLayer<MergerLayer>(mergerDescriptor, name);
}

IConnectableLayer* Network::AddAdditionLayer(const char* name)
{
    return m_Graph->AddLayer<AdditionLayer>(name);
}

IConnectableLayer* Network::AddMultiplicationLayer(const char* name)
{
    return m_Graph->AddLayer<MultiplicationLayer>(name);
}

IConnectableLayer* Network::AddOutputLayer(LayerBindingId id, const char* name)
{
    return m_Graph->AddLayer<OutputLayer>(id, name);
}

IConnectableLayer* Network::AddBatchNormalizationLayer(const BatchNormalizationDescriptor& desc,
                                                       const ConstTensor&                  mean,
                                                       const ConstTensor&                  variance,
                                                       const ConstTensor&                  beta,
                                                       const ConstTensor&                  gamma,
                                                       const char*                         name)
{
    const auto layer = m_Graph->AddLayer<BatchNormalizationLayer>(desc, name);

    layer->m_Mean = std::make_unique<ScopedCpuTensorHandle>(mean);
    layer->m_Variance = std::make_unique<ScopedCpuTensorHandle>(variance);
    layer->m_Beta = std::make_unique<ScopedCpuTensorHandle>(beta);
    layer->m_Gamma = std::make_unique<ScopedCpuTensorHandle>(gamma);

    return layer;
}

IConnectableLayer* Network::AddResizeBilinearLayer(const ResizeBilinearDescriptor& resizeDescriptor, const char* name)
{
    return m_Graph->AddLayer<ResizeBilinearLayer>(resizeDescriptor,name);
}

IConnectableLayer* Network::AddL2NormalizationLayer(const char* name)
{
    return m_Graph->AddLayer<L2NormalizationLayer>(name);
}

IConnectableLayer* Network::AddConstantLayer(const ConstTensor& input, const char* name)
{
    return m_Graph->AddLayer<ConstantLayer>(std::make_shared<ScopedCpuTensorHandle>(input), name);
}

IConnectableLayer* Network::AddReshapeLayer(const ReshapeDescriptor& reshapeDescriptor, const char* name)
{
    return m_Graph->AddLayer<ReshapeLayer>(reshapeDescriptor, name);
}

IConnectableLayer* Network::AddFloorLayer(const char* name)
{
    return m_Graph->AddLayer<FloorLayer>(name);
}

OptimizedNetwork::OptimizedNetwork(std::unique_ptr<Graph> graph)
    : m_Graph(std::move(graph))
{
}

OptimizedNetwork::~OptimizedNetwork()
{
}

} // namespace armnn


text:
//
// Copyright yutopp 2013 - .
//
// 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 RILL_TYPE_TYPE_REGISTRY_HPP
#define RILL_TYPE_TYPE_REGISTRY_HPP

#include <unordered_map>

#include <boost/optional.hpp>

#include "type_registry_fwd.hpp"
#include "type.hpp"
#include "../environment/environment_fwd.hpp"

#include "../debug/debug.hpp"

namespace rill
{
    //
    class type_registry
    {
    public:
        typedef type_id_t                   type_id_type;
        typedef type                        type_type;

        typedef std::allocator<type_type>   dereference_allocator_type;

    public:
        template<typename ClassEnvPtr>
        auto add(
            ClassEnvPtr const& class_env,
            attribute::type_attributes const& type_attr
            )
            -> type_id_t
        {
            auto const& class_env_id
                = ( class_env != nullptr )
                ? class_env->get_id()
                : environment_id_undetermined;

            return add( class_env_id, type_attr );
        }

        auto add(
            environment_id_t const& class_env_id,
            attribute::type_attributes const& type_attr
            )
            -> type_id_t
        try {
            if ( auto const& o = is_exist( class_env_id, type_attr ) ) {
                return *o;
            }

            // make a type
            type t = { class_env_id, type_attr };
            data_holder_.emplace( current_index_, std::move( t ) );

            rill_dout << ">>> type registered." << std::endl
                      << ">>>  id  : " << class_env_id << std::endl;

            dereference_data_holder_[class_env_id][attribute::detail::make_type_attributes_bit( type_attr )] = current_index_;

            return type_id_t( current_index_++ );

        } catch( std::exception const& e ) {
            std::cerr << e.what() << std::endl;
            assert( false && "[ice]" );
        }

        auto at( type_id_t const& type_id )
            -> type_type&
        {
            if ( type_id >= type_id_limit ) {
                rill::debug::dump_backtrace();
                assert( false && "[[ICE]]" );
            }

            return data_holder_.at( type_id );
        }

        auto at( type_id_t const& type_id ) const
            -> type_type const&
        {
            if ( type_id >= type_id_limit ) {
                rill::debug::dump_backtrace();
                assert( false && "[[ICE]]" );
            }

            return data_holder_.at( type_id );
        }

        auto is_class_exist( environment_id_t const& class_env_id ) const
            -> bool
        {
            return dereference_data_holder_.find( class_env_id ) != dereference_data_holder_.cend();
        }

        auto is_exist( environment_id_t const& class_env_id, attribute::type_attributes const& type_attr ) const
            -> boost::optional<type_id_t>
        {
            auto const it = dereference_data_holder_.find( class_env_id );
            if ( it == dereference_data_holder_.cend() )
                return boost::none;

            auto const& reit = it->second.find( attribute::detail::make_type_attributes_bit( type_attr ) );
            return ( reit != it->second.cend() ) ? boost::make_optional( reit->second ) : boost::none;
        }
/*
        // it makes be able to find id from env and attributes
        template<typename ClassEnvPtr>
        auto link_name_and_id(
            ClassEnvPtr const& class_env,
            attribute::type_attributes const& type_attr
            )
            -> type_id_t
        {
            type t = { class_env_id->get_id(), type_attr };
            data_holder_.emplace( current_index_, std::move( t ) );

            return type_id_t( current_index_++ );
        }
*/

        //inline auto is_exist()

    private:
        type_id_t current_index_ = type_id_t( 0 );
        std::unordered_map<type_id_t, type, detail::type_id_t_hasher> data_holder_;

        // TODO: use Scoped Allocator
        std::unordered_map<
            environment_id_t,
            std::unordered_map<attribute::attributes_bit_t, type_id_t>
            > dereference_data_holder_;

        //std::allocator<attributes_bit_t> dereference_data_allocator_;
    };

} // namespace rill

#endif /*RILL_TYPE_TYPE_REGISTRY_HPP*/

max_stars_repo_name: rhysd/rill

max_issues_repo_name: rhysd/rill

max_forks_repo_name: rhysd/rill


text:
///////////////////////////////////////////////////////////////////////////////
// logical_newline_matcher.hpp
//
//  Copyright 2007 Eric Niebler. 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_XPRESSIVE_DETAIL_CORE_MATCHER_LOGICAL_NEWLINE_MATCHER_HPP_EAN_10_04_2005
#define BOOST_XPRESSIVE_DETAIL_CORE_MATCHER_LOGICAL_NEWLINE_MATCHER_HPP_EAN_10_04_2005

// MS compatible compilers support #pragma once
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
# pragma once
#endif

#include <boost/xpressive/detail/detail_fwd.hpp>
#include <boost/xpressive/detail/core/quant_style.hpp>
#include <boost/xpressive/detail/core/state.hpp>

namespace boost { namespace xpressive { namespace detail
{

    //////////////////////////////////////////////////////////////////////////
    // logical_newline_matcher
    //
    template<typename Traits>
    struct logical_newline_matcher
      : quant_style_variable_width
    {
        typedef typename Traits::char_type char_type;
        typedef typename Traits::char_class_type char_class_type;

        logical_newline_matcher(Traits const &traits)
          : newline_(lookup_classname(traits, "newline"))
          , nl_(traits.widen('\n'))
          , cr_(traits.widen('\r'))
        {
        }

        template<typename BidiIter, typename Next>
        bool match(match_state<BidiIter> &state, Next const &next) const
        {
            if(state.eos())
            {
                return false;
            }

            char_type ch = *state.cur_;
            if(traits_cast<Traits>(state).isctype(ch, this->newline_))
            {
                ++state.cur_;
                if(this->cr_ == ch && !state.eos() && this->nl_ == *state.cur_)
                {
                    ++state.cur_;
                    if(next.match(state))
                    {
                        return true;
                    }
                    --state.cur_;
                }
                else if(next.match(state))
                {
                    return true;
                }

                --state.cur_;
            }
            return false;
        }

        char_class_type newline() const
        {
            return this->newline_;
        }

    private:
        char_class_type newline_;
        char_type nl_, cr_;
    };

}}}

#endif


text:
//  (C) Copyright Gennadiy Rozental 2005-2012.
//  Use, modification, and distribution are subject to 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)

//  See http://www.boost.org/libs/test for the library home page.
//
//  File        : $RCSfile$
//
//  Version     : $Revision$
//
//  Description : input validation helpers definition
// ***************************************************************************

#ifndef BOOST_RT_CLA_VALIDATION_HPP_062604GER
#define BOOST_RT_CLA_VALIDATION_HPP_062604GER

// Boost.Runtime.Parameter
#include <boost/test/utils/runtime/config.hpp>

#include <boost/test/utils/runtime/cla/fwd.hpp>

namespace boost {

namespace BOOST_RT_PARAM_NAMESPACE {

namespace cla {

// ************************************************************************** //
// **************       runtime::cla::report_input_error       ************** //
// ************************************************************************** //

void report_input_error( argv_traverser const& tr, format_stream& msg );

//____________________________________________________________________________//

#define BOOST_RT_CLA_VALIDATE_INPUT( b, tr, msg ) \
    if( b ) ; else ::boost::BOOST_RT_PARAM_NAMESPACE::cla::report_input_error( tr, format_stream().ref() << msg )

//____________________________________________________________________________//

} // namespace cla

} // namespace BOOST_RT_PARAM_NAMESPACE

} // namespace boost

#ifndef BOOST_RT_PARAM_OFFLINE

#  define BOOST_RT_PARAM_INLINE inline
#  include <boost/test/utils/runtime/cla/validation.ipp>

#endif

#endif // BOOST_RT_CLA_VALIDATION_HPP_062604GER

max_stars_repo_name: ballisticwhisper/boost

max_issues_repo_name: ballisticwhisper/boost

max_forks_repo_name: ballisticwhisper/boost


text:
/*
 * Pointcloudtogrid.hpp
 *
 *  Created on: Aug 1, 2019
 *      Author: Peter XXC
 *	 Institute: ZJU, Robotics 104
 */

#pragma once

// Elevation Mapping
#include "elevation_mapping/ElevationMap.hpp"
#include "elevation_mapping/RobotMotionMapUpdater.hpp"
#include "elevation_mapping/sensor_processors/SensorProcessorBase.hpp"
#include "elevation_mapping/WeightedEmpiricalCumulativeDistributionFunction.hpp"

// Grid Map
#include <grid_map_msgs/GetGridMap.h>
#include <grid_map_msgs/ProcessFile.h>
#include "grid_map_core/TypeDefs.hpp"
#include "grid_map_core/SubmapGeometry.hpp"
#include "grid_map_core/BufferRegion.hpp"

// Eigen
#include <Eigen/Core>
#include <Eigen/Geometry>

// PCL
#include <pcl/conversions.h>
#include <pcl/point_cloud.h>
#include <pcl/point_types.h>
#include <pcl/PCLPointCloud2.h>
#include <pcl_conversions/pcl_conversions.h>
#include <pcl/filters/voxel_grid.h>

// ROS
#include <ros/ros.h>
#include <sensor_msgs/PointCloud2.h>
#include <message_filters/cache.h>
#include <message_filters/subscriber.h>
#include <tf/transform_listener.h>
#include <geometry_msgs/PoseWithCovarianceStamped.h>
#include <std_srvs/Empty.h>

// Boost
#include <boost/thread.hpp>

// Eigen
#include <Eigen/Core>
#include <Eigen/Geometry>

#define NOT_OCCUPIED 0
#define OCCUPIED 1
#define OUT_OF_SCOPE 2

using namespace grid_map;
using namespace pcl;

struct Cell_feature
{
    //short cell_position[2] = {-1, -1};
    float highest = 0.0;
    float lowest = 0.0;
    float h_var = 0.0;
    float l_var = 0.0;
    int flag = NOT_OCCUPIED;
};

namespace elevation_mapping {

class PointcloudToGrid
{

public:

    /*!
   * Constructor.
   */
    PointcloudToGrid();

    /*!
    * Destructor.
    */
    virtual ~PointcloudToGrid();

    /*!
    * Callback function for processing pointcloud to grid map.
    * @param pointCloud the point cloud to be processed.
    */

    void pointCloudProcess(const pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr &InputCloud, Eigen::VectorXf& variances, struct Cell_feature cell_with_pos[]);

    /*!
    * Set the geometry of the grid map.
    * @param length the side lengths in x, and y-direction of the grid map [m].
    * @param resolution the cell size in [m/cell].
    */
    void setScale(const Length& length, const double resolution);

private:

    //! Side length of the map in x- and y-direction [m].
    Length length_;

    //! Map resolution in xy plane [m/cell].
    double resolution_;

    //! Map grid cell number.
    Index grid_num;

    //! Size of the buffer (rows and cols of the data structure).
    Size size_;

    //! cell struct.
    //Cell_feature *cell_with_pos;

};

}

max_stars_repo_name: mcx/GEM

max_issues_repo_name: whale-tea/GEM

max_forks_repo_name: whale-tea/GEM


text:
// This file is part of SWGANH which is released under the MIT license.
// See file LICENSE or go to http://swganh.com/LICENSE

#ifndef WIN32
#include <Python.h>
#endif

#include "combat_init.h"

#include <boost/program_options/options_description.hpp>
#include <boost/program_options/variables_map.hpp>

#include "swganh/logger.h"

#include "swganh/plugin/bindings.h"
#include "swganh/plugin/plugin_manager.h"

#include "swganh/app/swganh_kernel.h"

#include "combat_service.h"

#include "version.h"

namespace swganh {
namespace combat {

void Initialize(swganh::app::SwganhKernel* kernel)
{
    swganh::plugin::ObjectRegistration registration;
    registration.version.major = VERSION_MAJOR;
    registration.version.minor = VERSION_MINOR;

    // Register
    registration.CreateObject = [kernel] (swganh::plugin::ObjectParams* params) -> void * {
        return new CombatService(kernel);
    };

    registration.DestroyObject = [] (void * object) {
        if (object) {
            delete static_cast<CombatService*>(object);
        }
    };

    kernel->GetPluginManager()->RegisterObject("Combat::CombatService", &registration);
}

}}  // namespace swganh::galaxy

max_stars_repo_name: apathyboy/swganh

max_issues_repo_name: apathyboy/swganh

max_forks_repo_name: apathyboy/swganh


text:
#include <iostream>
#include <fstream>
#include <vector>
#include <ctime>
#include <stdlib.h>
#include <time.h>
#include <algorithm>
#include <deque>
#include <unordered_set>
#include <math.h>
//PCL
#include <pcl/common/transforms.h>
#include <pcl/ModelCoefficients.h>
#include <pcl/sample_consensus/method_types.h>
#include <pcl/sample_consensus/model_types.h>
#include <pcl/segmentation/sac_segmentation.h>
#include <pcl/io/pcd_io.h>
#include <pcl/point_types.h>
#include <pcl/point_cloud.h>
#include <pcl/visualization/cloud_viewer.h>
#include <pcl/filters/passthrough.h>
#include <pcl/filters/impl/passthrough.hpp>
#include <pcl/filters/extract_indices.h>
#include <pcl/features/normal_3d.h>
#include "patchwork.hpp"
#include <pcl/visualization/impl/point_cloud_geometry_handlers.hpp>//自定义点云类型时要加
#include <pcl/filters/conditional_removal.h>
//Eigen
#include <Eigen/Dense>
#include <queue>

#include <unordered_map>

#include <opencv2/opencv.hpp>
#include <opencv2/imgproc.hpp>

#include "CVC_cluster.h"

using namespace std;

struct PointXYZILID
{
  PCL_ADD_POINT4D;                    // quad-word XYZ
  float    intensity;                 ///< laser intensity reading
  uint16_t label;                     ///< point label
  uint16_t id;
  EIGEN_MAKE_ALIGNED_OPERATOR_NEW     // ensure proper alignment
} EIGEN_ALIGN16;

// Register custom point struct according to PCL
POINT_CLOUD_REGISTER_POINT_STRUCT(PointXYZILID,
                                  (float, x, x)
                                  (float, y, y)
                                  (float, z, z)
                                  (float, intensity, intensity)
                                  (uint16_t, label, label)
                                  (uint16_t, id, id))

struct PointXYZIR{
	PCL_ADD_POINT4D;
	float intensity;
	uint16_t ring;
	EIGEN_MAKE_ALIGNED_OPERATOR_NEW
}EIGEN_ALIGN16;

POINT_CLOUD_REGISTER_POINT_STRUCT(PointXYZIR,
		(float,x,x)
		(float,y,y)
		(float,z,z)
		(float,intensity,intensity)
		(uint16_t,ring,ring)
)

void PointXYZILID2XYZI(pcl::PointCloud<PointXYZILID>& src,
                       pcl::PointCloud<pcl::PointXYZI>::Ptr dst){
  dst->points.clear();
  for (const auto &pt: src.points){
    pcl::PointXYZI pt_xyzi;
    pt_xyzi.x = pt.x;
    pt_xyzi.y = pt.y;
    pt_xyzi.z = pt.z;
    pt_xyzi.intensity = pt.intensity;
    dst->points.push_back(pt_xyzi);
  }
}

using PointType = PointXYZILID;
boost::shared_ptr<PatchWork<PointType> > PatchworkGroundSeg;

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

       pcl::PointCloud<PointXYZIR>::Ptr cloud(new pcl::PointCloud<PointXYZIR>);//初始化点云
       pcl::io::loadPCDFile<PointXYZIR>(argv[1], *cloud);//加载pcd点云并放入cloud中

       PatchworkGroundSeg.reset(new PatchWork<PointXYZILID>());
       pcl::PointCloud<PointType>::Ptr pc_curr(new pcl::PointCloud<PointType>);
       pcl::PointCloud<PointType>::Ptr pc_ground(new pcl::PointCloud<PointType>);
       pcl::PointCloud<PointType>::Ptr pc_non_ground(new pcl::PointCloud<PointType>);
       double time_taken;

	for(int i=0; i<cloud->points.size(); ++i){
		PointType p;
		p.x = cloud->points[i].x;
		p.y = cloud->points[i].y;
		p.z = cloud->points[i].z;
		p.intensity = cloud->points[i].intensity;
		pc_curr->points.push_back(p);
	}

        PatchworkGroundSeg->estimate_ground(*pc_curr, *pc_ground, *pc_non_ground, time_taken);

	cout<<time_taken<<endl;

	vector<float> param(3,0);
	param[0] = 2;
	param[1] = 0.4;
	param[2] = 1.5;

	pcl::PointCloud<pcl::PointXYZ>::Ptr cluster_point(new pcl::PointCloud<pcl::PointXYZ>);

	for(int i=0; i<pc_non_ground->points.size(); ++i){
		pcl::PointXYZ p;
		p.x = pc_non_ground->points[i].x;
		p.y = pc_non_ground->points[i].y;
		p.z = pc_non_ground->points[i].z;
		cluster_point->points.push_back(p);
	}

	cout<<"cluster_point "<<cluster_point->points.size()<<endl;
	CVC Cluster(param);
	std::vector<PointAPR> capr;
	Cluster.calculateAPR(*cluster_point, capr);

	cout<<"capr "<<capr.size()<<endl;
	std::unordered_map<int, Voxel> hash_table;
	Cluster.build_hash_table(capr, hash_table);
	vector<int> cluster_indices;
	cluster_indices = Cluster.cluster(hash_table, capr);
	vector<int> cluster_id;
	Cluster.most_frequent_value(cluster_indices, cluster_id);

	boost::shared_ptr<pcl::visualization::PCLVisualizer> viewer(
			new pcl::visualization::PCLVisualizer("pcd")); //PCLVisualizer 可视化类
	viewer->setBackgroundColor(0, 0, 0);
	viewer->addCoordinateSystem(1);

	cv::RNG rng(12345);

        int r = rng.uniform(0, 200);
        int g = rng.uniform(0, 200);
        int b = rng.uniform(0, 200);
	pcl::visualization::PointCloudColorHandlerCustom <PointType> colorob(pc_ground, (r), (g),(b));
	string csob = "cloudfinalob";
	viewer->addPointCloud(pc_ground,colorob, csob);

	//pcl::visualization::PointCloudColorHandlerCustom <PointType> colorob2(pc_non_ground, (0), (255),(0));
	//string csob2 = "cloudfinalob1";
	//viewer->addPointCloud(pc_non_ground,colorob2, csob2);

	for(int j = 0; j < cluster_id.size(); ++j){
                int r = rng.uniform(20, 255);
                int g = rng.uniform(20, 255);
                int b = rng.uniform(20, 255);
		pcl::PointCloud<pcl::PointXYZ>::Ptr cloudcluster(new pcl::PointCloud<pcl::PointXYZ>);//初始化
		for(int i =0; i<cluster_indices.size(); ++i){
			if(cluster_indices[i] == cluster_id[j]){
				 cloudcluster->points.push_back(cluster_point->points[i]);
			}
		}

		pcl::visualization::PointCloudColorHandlerCustom <pcl::PointXYZ> color(cloudcluster, (r), (g),(b));
		string text = "cloud" + toString(j);
		viewer->addPointCloud(cloudcluster,color, text);
	}

	while (!viewer->wasStopped()) {
		viewer->spin();
	}

    return 0;
}


text:
#include "VideoCaptureSession.h"
#include <boost/bind/bind.hpp>
#include <boost/thread/thread_only.hpp>

void deleteCaptureThread(RunningCaptureThread* running_capture)
{
	if (running_capture == nullptr)
		return;

	running_capture->functor->stop();
	running_capture->thread->join();
	delete running_capture->thread;
	delete running_capture->functor;
	delete running_capture;
}

VideoCaptureSession::VideoCaptureSession(VideoPollingBackend* functor) :
	polling_functor(functor),
	polling_thread(nullptr, &deleteCaptureThread) { }

VideoCaptureSession::~VideoCaptureSession()
{
	polling_thread.reset(nullptr);
}

bool VideoCaptureSession::startCapture()
{
	auto* thread = new RunningCaptureThread();
	thread->functor = polling_functor;
	thread->thread = new boost::thread(boost::bind(&VideoPollingBackend::operator(), polling_functor));
	polling_thread.reset(thread);
	return true;
}

void VideoCaptureSession::stopCapture()
{
	// blocks until the next opportunity to stop the capture.
	polling_thread.reset(nullptr);
}

const VideoPollingBackend* VideoCaptureSession::getBackend() const
{
	return polling_functor;
}

max_stars_repo_name: dmikushin/RemoteEye

max_issues_repo_name: dmikushin/RemoteEye

max_forks_repo_name: dmikushin/RemoteEye


text:
/*
    Copyright 2013 <copyright holder> <email>

    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.
*/

#include "assetsessions.hpp"

#include "../../lib/hashes.h"
#include <boost/make_shared.hpp>

bithorded::UpstreamRequestBinding::Ptr bithorded::AssetSessions::findAsset(const bithorde::BindRead& req)
{
	std::string tigerId = findBithordeId(req.ids(), bithorde::HashType::TREE_TIGER);
	if (tigerId.empty())
		return UpstreamRequestBinding::Ptr();
	if (auto active = _tigerCache[tigerId])
		return active;

	UpstreamRequestBinding::Ptr res;
	if (auto asset = openAsset(req)) {
		res = boost::make_shared<UpstreamRequestBinding>(asset);
		add(tigerId, res);
	}
	return res;
}

void bithorded::AssetSessions::add(const std::string& tigerId, const UpstreamRequestBinding::Ptr& asset)
{
	if (asset)
		_tigerCache.set(tigerId, asset);
}

max_stars_repo_name: zidz/bithorde

max_issues_repo_name: zidz/bithorde

max_forks_repo_name: zidz/bithorde