text:
#include "PhraseDistanceFeature.h"

#include <vector>
#include <boost/foreach.hpp>
#include "moses/InputType.h"
#include "moses/ScoreComponentCollection.h"
#include "moses/StaticData.h"
#include "util/exception.hh"

using namespace std;

namespace Moses
{
PhraseDistanceFeature::PhraseDistanceFeature(const string &line)
  : StatelessFeatureFunction(2, line)
  , m_space("")
  , m_spaceID(0)
  , m_measure(EuclideanDistance)
{
  ReadParameters();
}

void PhraseDistanceFeature::EvaluateWithSourceContext(const InputType &input
    , const InputPath &inputPath
    , const TargetPhrase &targetPhrase
    , const StackVec *stackVec
    , ScoreComponentCollection &scoreBreakdown
    , ScoreComponentCollection *estimatedScores) const
{
  vector<float> scores(m_numScoreComponents, 0);
  bool broken = false;
  // Input coord
  map<size_t const, vector<float> >::const_iterator ii;
  if (input.m_coordMap) {
    ii = input.m_coordMap->find(m_spaceID);
  } else {
    TRACE_ERR("No coordinates for space " << m_space << " on input (specify with coord XML tag)" << endl);
    TRACE_ERR("Scores for " << m_description << " will be incorrect and probably all zeros" << endl);
    broken = true;
  }
  if (ii == input.m_coordMap->end()) {
    TRACE_ERR("No coordinates for space " << m_space << " on input (specify with coord XML tag)" << endl);
    TRACE_ERR("Scores for " << m_description << " will be incorrect and probably all zeros" << endl);
    broken = true;
  }
  // Target phrase coord
  vector<SPTR<vector<float> > > const* tpp = targetPhrase.GetCoordList(m_spaceID);
  if (tpp == NULL) {
    TRACE_ERR("No coordinates for space " << m_space << " on target phrase (PhraseDictionary implementation needs to set)" << endl);
    TRACE_ERR("Scores for " << m_description << " will be incorrect and probably all zeros" << endl);
    broken = true;
  }
  // Compute scores
  if (!broken) {
    vector<float> const& inputCoord = ii->second;
    vector<SPTR<vector<float> > > const& tpCoord = *tpp;
    // Centroid of target phrase instances (from phrase extraction)
    vector<float> centroid = vector<float>(inputCoord.size(), 0);
    BOOST_FOREACH(SPTR<vector<float> > const coord, tpCoord) {
      for (size_t i = 0; i < inputCoord.size(); ++i) {
        centroid[i] += (*coord)[i];
      }
    }
    for (size_t i = 0; i < inputCoord.size(); ++i) {
      centroid[i] /= tpCoord.size();
    }
    // Average distance from the target phrase instances to (1) the input and
    // (2) the target phrase centroid
    float inputDistance = 0;
    float centroidDistance = 0;
    if (m_measure == EuclideanDistance) {
      BOOST_FOREACH(SPTR<vector<float> > const coord, tpCoord) {
        float pointInputDistance = 0;
        float pointCentroidDistance = 0;
        for (size_t i = 0; i < inputCoord.size(); ++i) {
          pointInputDistance += pow(inputCoord[i] - (*coord)[i], 2);
          pointCentroidDistance += pow(centroid[i] - (*coord)[i], 2);
        }
        inputDistance += sqrt(pointInputDistance);
        centroidDistance += sqrt(pointCentroidDistance);
      }
    } else if (m_measure == TotalVariationDistance) {
      BOOST_FOREACH(SPTR<vector<float> > const coord, tpCoord) {
        float pointInputDistance = 0;
        float pointCentroidDistance = 0;
        for (size_t i = 0; i < inputCoord.size(); ++i) {
          pointInputDistance += abs(inputCoord[i] - (*coord)[i]);
          pointCentroidDistance += abs(centroid[i] - (*coord)[i]);
        }
        inputDistance += pointInputDistance / 2;
        centroidDistance += pointCentroidDistance / 2;
      }
    }
    inputDistance /= tpCoord.size();
    centroidDistance /= tpCoord.size();
    // Log transform scores, max with float epsilon to avoid domain error
    scores[0] = log(max(inputDistance, Moses::FLOAT_EPSILON));
    scores[1] = log(max(centroidDistance, Moses::FLOAT_EPSILON));
  }
  // Set scores
  scoreBreakdown.Assign(this, scores);
  return;
}

void PhraseDistanceFeature::SetParameter(const string& key, const string& value)
{
  if (key == "space") {
    m_space = value;
    m_spaceID = StaticData::InstanceNonConst().MapCoordSpace(m_space);
  } else if (key == "measure") {
    if (value == "euc") {
      m_measure = EuclideanDistance;
    } else if (value == "var") {
      m_measure = TotalVariationDistance;
    } else {
      UTIL_THROW2("Unknown measure " << value << ", choices: euc var");
    }
  } else {
    StatelessFeatureFunction::SetParameter(key, value);
  }
}

} // namespace


text:
//
// Copyright 2005-2007 Adobe Systems Incorporated
//
// 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_GIL_CONCEPTS_BASIC_HPP
#define BOOST_GIL_CONCEPTS_BASIC_HPP

#include <boost/config.hpp>

#if defined(BOOST_CLANG)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunknown-pragmas"
#pragma clang diagnostic ignored "-Wunused-local-typedefs"
#pragma clang diagnostic ignored "-Wuninitialized"
#endif

#if defined(BOOST_GCC) && (BOOST_GCC >= 40900)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-local-typedefs"
#pragma GCC diagnostic ignored "-Wuninitialized"
#endif

#include <boost/gil/concepts/concept_check.hpp>

#include <type_traits>
#include <utility> // std::swap

namespace boost { namespace gil {

/// \brief Concept of default construction requirement.
/// \code
/// auto concept DefaultConstructible<typename T>
/// {
///     T::T();
/// };
/// \endcode
/// \ingroup BasicConcepts
///
template <typename T>
struct DefaultConstructible
{
    void constraints()
    {
        function_requires<boost::DefaultConstructibleConcept<T>>();
    }
};

/// \brief Concept of copy construction requirement.
/// \code
/// auto concept CopyConstructible<typename T>
/// {
///     T::T(T);
///     T::~T();
/// };
/// \endcode
/// \ingroup BasicConcepts
///
template <typename T>
struct CopyConstructible
{
    void constraints()
    {
        function_requires<boost::CopyConstructibleConcept<T>>();
    }
};

/// \brief Concept of copy assignment requirement.
/// \code
/// auto concept Assignable<typename T, typename U = T>
/// {
///     typename result_type;
///     result_type operator=(T&, U);
/// };
/// \endcode
/// \ingroup BasicConcepts
///
template <typename T>
struct Assignable
{
    void constraints()
    {
        function_requires<boost::AssignableConcept<T>>();
    }
};

/// \brief Concept of == and != comparability requirement.
/// \code
/// auto concept EqualityComparable<typename T, typename U = T>
/// {
///     bool operator==(T x, T y);
///     bool operator!=(T x, T y) { return !(x==y); }
/// };
/// \endcode
/// \ingroup BasicConcepts
///
template <typename T>
struct EqualityComparable
{
    void constraints()
    {
        function_requires<boost::EqualityComparableConcept<T>>();
    }
};

/// \brief Concept of swap operation requirement.
/// \code
/// auto concept Swappable<typename T>
/// {
///     void swap(T&,T&);
/// };
/// \endcode
/// \ingroup BasicConcepts
///
template <typename T>
struct Swappable
{
    void constraints()
    {
        using std::swap;
        swap(x,y);
    }
    T x,y;
};

/// \brief Concept for type regularity requirement.
/// \code
/// auto concept Regular<typename T>
///     : DefaultConstructible<T>
///     , CopyConstructible<T>
///     , EqualityComparable<T>
///     , Assignable<T>
///     , Swappable<T>
/// {};
/// \endcode
/// \ingroup BasicConcepts
///
template <typename T>
struct Regular
{
    void constraints()
    {
        gil_function_requires< boost::DefaultConstructibleConcept<T>>();
        gil_function_requires< boost::CopyConstructibleConcept<T>>();
        gil_function_requires< boost::EqualityComparableConcept<T>>(); // ==, !=
        gil_function_requires< boost::AssignableConcept<T>>();
        gil_function_requires< Swappable<T>>();
    }
};

/// \brief Concept for type as metafunction requirement.
/// \code
/// auto concept Metafunction<typename T>
/// {
///     typename type;
/// };
/// \endcode
/// \ingroup BasicConcepts
///
template <typename T>
struct Metafunction
{
    void constraints()
    {
        using type = typename T::type;
    }
};

/// \brief Concept of types equivalence requirement.
/// \code
/// auto concept SameType<typename T, typename U>; // unspecified
/// \endcode
/// \ingroup BasicConcepts
///
template <typename T, typename U>
struct SameType
{
    void constraints()
    {
        static_assert(std::is_same<T, U>::value, "");
    }
};

}} // namespace boost::gil

#if defined(BOOST_CLANG)
#pragma clang diagnostic pop
#endif

#if defined(BOOST_GCC) && (BOOST_GCC >= 40900)
#pragma GCC diagnostic pop
#endif

#endif

ext: hpp

max_stars_repo_name: kindlychung/mediasoup-sfu-cpp

max_issues_repo_name: kindlychung/mediasoup-sfu-cpp

max_forks_repo_name: kindlychung/mediasoup-sfu-cpp


text:
#ifndef HERMIT_S_EXPR_HPP
#define HERMIT_S_EXPR_HPP

#include <string>
#include <cstdint>
#include <boost/variant.hpp>
#include <boost/variant/recursive_variant.hpp>
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/karma.hpp>
#include <boost/spirit/include/phoenix.hpp>
#include <boost/range.hpp>
#include <boost/optional.hpp>
#include <boost/fusion/adapted/std_pair.hpp>
#include <boost/fusion/include/std_pair.hpp>

#include <hermit/range_traits.hpp>

namespace hermit {
  namespace s_expr {
    typedef int64_t integer;
    typedef std::string string;

    struct symbol {
    public:
      symbol(){}
      symbol( const std::string &name_ ) : name( name_ ) {}
      const std::string &get_name() const { return name; }
      operator std::string() const {
        return name;
      }
    private:
      std::string name;
    };

    typedef boost::make_recursive_variant<
      std::vector< boost::recursive_variant_ >,
      integer,
      string,
      symbol
    >::type node_internal;

    typedef std::vector< node_internal > node;

    template< typename Iterator >
    class rule :
      public boost::spirit::qi::grammar<
        Iterator,
        node()
      > {
    public:
      rule() : rule::base_type( root ) {
        using namespace boost::spirit;
        using namespace boost::spirit::ascii;
        root = *space >> list >> *space;
        list =
          ( omit[ '(' >> *space ] >> ( element >> *( omit[ +space ] >> element ) ) >> omit[ *space >> ')' ] ) |
          ( omit[ '[' >> *space ] >> ( element >> *( omit[ +space ] >> element ) ) >> omit[ *space >> ']' ] ) |
          ( omit[ '{' >> *space ] >> ( element >> *( omit[ +space ] >> element ) ) >> omit[ *space >> '}' ] );
        element = list|integer_|string_|symbol_;
        integer_ = long_long;
        escape = '\\' >> char_;
        reserved = char_( "()[]{}\\\"'" );
        string_ =
          ( '"' >> *( ( char_ - reserved )|escape ) >> '"' )|
          ( '\'' >> *( ( char_ - reserved )|escape ) >> '\'' );
        symbol_ = as_string[ alpha >> *( ( graph - reserved )|escape ) ];
      }
    private:
      boost::spirit::qi::rule< Iterator, node() > root;
      boost::spirit::qi::rule< Iterator, node() > list;
      boost::spirit::qi::rule< Iterator, node_internal() > element;
      boost::spirit::qi::rule< Iterator, integer() > integer_;
      boost::spirit::qi::rule< Iterator, char() > escape;
      boost::spirit::qi::rule< Iterator, char() > reserved;
      boost::spirit::qi::rule< Iterator, string() > string_;
      boost::spirit::qi::rule< Iterator, symbol() > symbol_;
    };

    template<
      typename T,
      typename Concept = typename boost::enable_if<
        boost::mpl::and_<
          boost::is_convertible<
            typename range_value< const T >::type,
            const char
          >,
          is_forward_traversal_range< const T >,
          is_readable_range< const T >
        >
      >::type
    >
    boost::optional< node > parse(
      const T &str
    ) {
      rule< typename range_iterator< const T >::type > grammar;
      typename range_iterator< const T >::type iter = str.begin();
      node result;
      if( boost::spirit::qi::parse(iter, str.end(), grammar, result ) && iter == str.end() )
        return result;
      else
        return boost::optional< node >();
    }

    template <typename Iterator>
    class gen :
      public boost::spirit::karma::grammar< Iterator, node() > {
      public:
        gen() : gen::base_type( root ) {
          using namespace boost::spirit;
          using namespace boost::spirit::karma;
          escape.add( '(', "\\(" )( ')', "\\)" )( '[', "\\[" )( ']', "\\]" )
              ( '{', "\\{" )( '}', "\\}" )( '\\', "\\\\" )( '"', "\\\"" )
              ( '\'', "\\'" );
          symbol_ = ( alpha << *( escape|graph ) );
        }
      private:
        boost::spirit::karma::rule< Iterator, string() > symbol_;
        boost::spirit::karma::symbols<char, std::string> escape;
        boost::spirit::karma::rule< Iterator, node() > root;
    };

  }
}

#endif

max_stars_repo_name: Fadis/hermit

max_issues_repo_name: Fadis/hermit

max_forks_repo_name: Fadis/hermit


text:
// ========================================================================= //
// Filename      :  test_gesture_storage.cpp
// Creation Date :  2016-7-10
// Created by    :  anfranek
// ========================================================================= //

#include <gtest/gtest.h>

#include <Eigen/Core>

#include "gesture_storage.h"
#include "resource_path.h"

TEST(gesture_storage, save_n_load)
{
    Gestures::Storage expected;
    expected["test"]= {
    {{0, 2}, {5, 14}},
    {{1, 322}, {55, 4}, {345, 66}}
};
    auto filename = util::getResourcePath() + "test/test.yaml";

    Gestures::save(expected, filename);
    auto actual = Gestures::load(filename);

    EXPECT_EQ(expected, actual);
}

ext: cpp


text:
#ifndef __refine_motion_estimate_hpp__
#define __refine_motion_estimate_hpp__

#include <Eigen/Geometry>

namespace fovis
{

/**
 *
 * Given an initial motion estimate M_0, iteratively refines the motion
 * estimate to minimize reprojection error.
 *
 * M = argmin_{M} \sum_{i} || ref_projections[i] - p(K * M * points[i]) ||^2
 *
 * where K is the camera projection matrix formed by fx, cx, and cy:
 *
 * K = [ fx 0 cx 0
 *       0 fx cy 0
 *       0  0  1 0 ]
 *
 * and p(X) is the normalized form of a homogeneous coordinate.
 *
 */
Eigen::Isometry3d refineMotionEstimate(
    const Eigen::Matrix<double, 4, Eigen::Dynamic>& points,
    const Eigen::Matrix<double, 2, Eigen::Dynamic>& ref_projections,
    double fx, double cx, double cy,
    const Eigen::Isometry3d& initial_estimate,
    int max_iterations);

/**
 *
 * Given an initial motion estimate M_0, iteratively refines the motion
 * estimate to minimize bidirectional reprojection error.
 *
 * M = argmin_{M} \sum_{i} ref_err(i) + target_err(i)
 *
 * ref_err(i) = || ref_projections[i] - p(K * M * target_points[i]) ||^2
 * target_err(i) = || target_projections[i] - p(K * M * ref_points[i]) ||^2
 *
 * where K is the camera projection matrix formed by fx, fy, cx, and cy:
 *
 * K = [ fx 0 cx 0
 *       0 fy cy 0
 *       0  0  1 0 ]
 *
 * and p(X) is the normalized form of a homogeneous coordinate.
 *
 */
void refineMotionEstimateBidirectional(
    const Eigen::Matrix<double, 4, Eigen::Dynamic>& ref_points,
    const Eigen::Matrix<double, 2, Eigen::Dynamic>& ref_projections,
    const Eigen::Matrix<double, 4, Eigen::Dynamic>& target_points,
    const Eigen::Matrix<double, 2, Eigen::Dynamic>& target_projections,
    double fx, double cx, double cy,
    const Eigen::Isometry3d& initial_estimate,
    int max_iterations,
    Eigen::Isometry3d* result,
    Eigen::MatrixXd* result_covariance);

}

#endif


text:
#include "burger/base/Singleton.h"
#include <boost/noncopyable.hpp>
#include <string>
#include <thread>
#include <iostream>

class Test :boost::noncopyable {
public:
    Test() {
        std::cout << "Test tid = " << std::this_thread::get_id() << "  Address = "
            <<  static_cast<const void *>(this) << std::endl;
    }

    ~Test() {
        std::cout << "~Test tid = " << std::this_thread::get_id() << "  Address = "
        <<  static_cast<const void *>(this) << "  name = " << name_ <<std::endl;
    }
    const std::string& getName() const { return name_; }
    void setName(const std::string& name) { name_ = name; }

private:
    std::string name_;
};

void ThreadFunc() {
    std::cout << "tid = " << std::this_thread::get_id()
        << " Address = " << static_cast<const void *>(&burger::Singleton<Test>::Instance())
        << " name = " << burger::Singleton<Test>::Instance().getName() << std::endl;
    burger::Singleton<Test>::Instance().setName("only one, changed");
}

int main() {
    burger::Singleton<Test>::Instance().setName("only one");
    std::thread t1(ThreadFunc);
    t1.join();
    std::cout << "tid = " << std::this_thread::get_id()
        << " Address = " << static_cast<const void *>(&burger::Singleton<Test>::Instance())
        << " name = " << burger::Singleton<Test>::Instance().getName() << std::endl;
}

ext: cc

max_stars_repo_name: BurgerGroup/Burger

max_issues_repo_name: chanchann/Burger

max_forks_repo_name: chanchann/Burger


text: #include <boost/iostreams/constants.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
// graph-tool -- a general graph modification and manipulation thingy
//
// Copyright (C) 2006-2018 Tiago de Paula Peixoto <tiago@skewed.de>
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 3
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.

#ifndef GRAPH_SEARCH_HH
#define GRAPH_SEARCH_HH

#include "graph_python_interface.hh"
#include "graph_util.hh"
#include "hash_map_wrap.hh"

#ifdef _OPENMP
#include <omp.h>
#include <boost/type_traits.hpp>
#endif

namespace graph_tool
{
using namespace std;
using namespace boost;

// sort sequences lexicographically
template <class ValueType>
bool operator<=(const vector<ValueType>& v1, const vector<ValueType>& v2)
{
    for (size_t i = 0; i < min(v1.size(), v2.size()); ++i)
    {
        if (v1[i] != v2[i])
            return (v1[i] <= v2[i]);
    }
    return (v1.size() <= v2.size());
}

// sort strings in alphabetical (ASCII) order
bool operator<=(const string& s1, const string& s2)
{
    for (size_t i = 0; i < min(s1.size(), s2.size()); ++i)
    {
        if (s1[i] != s2[i])
            return (s1[i] <= s2[i]);
    }
    return (s1.size() <= s2.size());
}

// find vertices which match a certain (inclusive) property range
struct find_vertices
{
    template <class Graph, class DegreeSelector>
    void operator()(Graph& g, GraphInterface& gi, DegreeSelector deg,
                    python::tuple& prange, python::list& ret) const
    {
        typedef typename DegreeSelector::value_type value_type;
        pair<value_type,value_type> range;
        range.first = python::extract<value_type>(prange[0]);
        range.second = python::extract<value_type>(prange[1]);

        #ifdef _OPENMP
        size_t __attribute__ ((unused)) nt = omp_get_num_threads();
        if (std::is_convertible<value_type,python::object>::value)
            nt = 1; // python is not thread-safe
        #endif

        auto gp = retrieve_graph_view<Graph>(gi, g);
        bool is_eq = range.first == range.second;

        #pragma omp parallel if (num_vertices(g) > OPENMP_MIN_THRESH) num_threads(nt)
        parallel_vertex_loop_no_spawn
            (g,
             [&](auto v)
             {
                 value_type val = deg(v, g);
                 if ((is_eq && (val == range.first)) ||
                     (!is_eq && (range.first <= val && val <= range.second)))
                 {
                     PythonVertex<Graph> pv(gp, v);
                     auto& ret_ = ret;  // work around clang
                     #pragma omp critical
                     {
                         ret_.append(pv);
                     }
                 }
             });
    }
};

// find edges which match a certain (inclusive) property range
struct find_edges
{
    template <class Graph, class EdgeIndex, class EdgeProperty>
    void operator()(Graph& g, GraphInterface& gi, EdgeIndex eindex,
                    EdgeProperty prop, python::tuple& prange, python::list& ret)
        const
    {
        typedef typename property_traits<EdgeProperty>::value_type value_type;
        pair<value_type,value_type> range;
        range.first = python::extract<value_type>(prange[0]);
        range.second = python::extract<value_type>(prange[1]);

        gt_hash_set<size_t> edge_set;

        #ifdef _OPENMP
        size_t __attribute__ ((unused)) nt = omp_get_num_threads();
        if (std::is_convertible<value_type,python::object>::value)
            nt = 1; // python is not thread-safe
        #endif

        auto gp = retrieve_graph_view<Graph>(gi, g);
        bool is_eq = range.first == range.second;

        #pragma omp parallel if (num_vertices(g) > OPENMP_MIN_THRESH) \
            num_threads(nt)
        parallel_edge_loop_no_spawn
            (g,
             [&](auto e)
             {
                 if (!graph_tool::is_directed(g))
                 {
                     if (edge_set.find(eindex[e]) == edge_set.end())
                         edge_set.insert(eindex[e]);
                    else
                        return;
                 }

                 value_type val = get(prop, e);
                 if ((is_eq && (val == range.first)) ||
                     (!is_eq && (range.first <= val && val <= range.second)))
                 {
                     PythonEdge<Graph> pe(gp, e);
                     auto& ret_ = ret;  // work around clang
                     #pragma omp critical
                     {
                         ret_.append(pe);
                     }
                 }
             });
    }
};

} // graph_tool namespace

#endif // GRAPH_SEARCH_HH

ext: hh


text:
#pragma once

#include <boost/property_tree/ptree.hpp>
#include <string>
#include <vector>

class ConfigurationManager {
public:
    explicit ConfigurationManager(const std::string &file);
    const std::vector<std::string> getVectorOfStringValue(const std::string &path) const;
    const std::string getStringValue(const std::string &path) const;
    const std::string &getLastError() const;
    void setStringValue(const std::string &path, const std::string &value);
    void setVectorOfStringValue(const std::string &path, const std::vector<std::string> &values);
    bool save();
	static const std::string THEME_PATH;
	static const std::string RECENT_MAPS;
private:
    std::string configFile;
    boost::property_tree::ptree config;
    std::string lastError;
};

max_stars_repo_name: jeremydumais/TheWarrior

max_issues_repo_name: jeremydumais/TheWarrior

max_forks_repo_name: jeremydumais/TheWarrior


text:
// Luaponte library

// Copyright (c) 2012 Peter Colberg

// Luaponte is based on Luabind, a library, inspired by and similar to
// Boost.Python, that helps you create bindings between C++ and Lua,
// Copyright (c) 2003-2010 Daniel Wallin and Arvid Norberg.

// Use, modification and distribution is subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE or copy at
// http://www.boost.org/LICENSE_1_0.txt)

#ifndef LUAPONTE_DETAIL_INHERITANCE_HPP
#define LUAPONTE_DETAIL_INHERITANCE_HPP

#include <cassert>
#include <limits>
#include <map>
#include <memory>
#include <vector>
#include <luaponte/typeid.hpp>
#include <boost/scoped_ptr.hpp>

namespace luaponte {
namespace detail {

typedef void*(*cast_function)(void*);
typedef std::size_t class_id;

class_id const unknown_class = (std::numeric_limits<class_id>::max)();

class class_rep;

class LUAPONTE_API cast_graph
{
public:
    cast_graph();
    ~cast_graph();

    // `src` and `p` here describe the *most derived* object. This means that
    // for a polymorphic type, the pointer must be cast with
    // dynamic_cast<void*> before being passed in here, and `src` has to
    // match typeid(*p).
    std::pair<void*, int> cast(
        void* p, class_id src, class_id target
      , class_id dynamic_id, void const* dynamic_ptr) const;
    void insert(class_id src, class_id target, cast_function cast);

private:
    class impl;
    boost::scoped_ptr<impl> m_impl;
};

// Maps a type_id to a class_id. Note that this actually partitions the
// id-space into two, using one half for "local" ids; ids that are used only as
// keys into the conversion cache. This is needed because we need a unique key
// even for types that hasn't been registered explicitly.
class LUAPONTE_API class_id_map
{
public:
    class_id_map();

    class_id get(type_id const& type) const;
    class_id get_local(type_id const& type);
    void put(class_id id, type_id const& type);

private:
    typedef std::map<type_id, class_id> map_type;
    map_type m_classes;
    class_id m_local_id;

    static class_id const local_id_base;
};

inline class_id_map::class_id_map()
  : m_local_id(local_id_base)
{}

inline class_id class_id_map::get(type_id const& type) const
{
    map_type::const_iterator i = m_classes.find(type);
    if (i == m_classes.end() || i->second >= local_id_base)
        return unknown_class;
    return i->second;
}

inline class_id class_id_map::get_local(type_id const& type)
{
    std::pair<map_type::iterator, bool> result = m_classes.insert(
        std::make_pair(type, 0));

    if (result.second)
        result.first->second = m_local_id++;

    assert(m_local_id >= local_id_base);

    return result.first->second;
}

inline void class_id_map::put(class_id id, type_id const& type)
{
    assert(id < local_id_base);

    std::pair<map_type::iterator, bool> result = m_classes.insert(
        std::make_pair(type, 0));

    assert(
        result.second
        || result.first->second == id
        || result.first->second >= local_id_base
    );

    result.first->second = id;
}

class class_map
{
public:
    class_rep* get(class_id id) const;
    void put(class_id id, class_rep* cls);

private:
    std::vector<class_rep*> m_classes;
};

inline class_rep* class_map::get(class_id id) const
{
    if (id >= m_classes.size())
        return 0;
    return m_classes[id];
}

inline void class_map::put(class_id id, class_rep* cls)
{
    if (id >= m_classes.size())
        m_classes.resize(id + 1);
    m_classes[id] = cls;
}

template <class S, class T>
struct static_cast_
{
    static void* execute(void* p)
    {
        return static_cast<T*>(static_cast<S*>(p));
    }
};

template <class S, class T>
struct dynamic_cast_
{
    static void* execute(void* p)
    {
        return dynamic_cast<T*>(static_cast<S*>(p));
    }
};

// Thread safe class_id allocation.
LUAPONTE_API class_id allocate_class_id(type_id const& cls);

template <class T>
struct registered_class
{
    static class_id const id;
};

template <class T>
class_id const registered_class<T>::id = allocate_class_id(typeid(T));

template <class T>
struct registered_class<T const>
  : registered_class<T>
{};

} // namespace detail
} // namespace luaponte

#endif // LUAPONTE_DETAIL_INHERITANCE_HPP

max_stars_repo_name: jb--/luaponte

max_issues_repo_name: halmd-org/luaponte

max_forks_repo_name: halmd-org/luaponte


text:
/**
 * Copyright (c) 2011-2017 libbitcoin developers (see AUTHORS)
 *
 * This file is part of libbitcoin.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
#include <boost/test/unit_test.hpp>
#include <bitcoin/bitcoin.hpp>

using namespace bc;
using namespace bc::chain;

#define SOURCE "000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f0100"
static const auto valid_raw_point_iterator_source = to_chunk(base16_literal(SOURCE));

BOOST_AUTO_TEST_SUITE(point_iterator_tests)

BOOST_AUTO_TEST_CASE(point_iterator__operator_bool__not_at_end__returns_true)
{
    point_iterator instance(point{});
    BOOST_REQUIRE((bool)instance);
}

BOOST_AUTO_TEST_CASE(point_iterator__operator_bool_at_end__returns_false)
{
    point value;
    point_iterator instance(value, static_cast<unsigned>(value.serialized_size(false)));
    BOOST_REQUIRE(!instance);
}

BOOST_AUTO_TEST_CASE(point_iterator__operator_asterisk__initialized_point__matches_source)
{
    point point;
    BOOST_REQUIRE(point.from_data(valid_raw_point_iterator_source, false));
    point_iterator instance(point);

    for (size_t i = 0; i < valid_raw_point_iterator_source.size(); i++, instance++)
    {
        BOOST_REQUIRE(instance);
        BOOST_REQUIRE_EQUAL(valid_raw_point_iterator_source[i], (*instance));
    }

    BOOST_REQUIRE(!instance);
    BOOST_REQUIRE_EQUAL(0u, (*instance));
}

BOOST_AUTO_TEST_CASE(point_iterator__operator_arrow__initialized_point__matches_source)
{
    point point;
    BOOST_REQUIRE(point.from_data(valid_raw_point_iterator_source, false));
    point_iterator instance(point);
    BOOST_REQUIRE(valid_raw_point_iterator_source.size() > 0);

    for (size_t i = 0; i < valid_raw_point_iterator_source.size(); i++, instance++)
    {
        BOOST_REQUIRE(instance);
        BOOST_REQUIRE_EQUAL(valid_raw_point_iterator_source[i], instance.operator->());
    }

    BOOST_REQUIRE(!instance);
    BOOST_REQUIRE_EQUAL(0u, instance.operator->());
}

BOOST_AUTO_TEST_CASE(point_iterator__operator_plus_minus_int__roundtrip__success)
{
    point point;
    uint8_t offset = 5u;
    BOOST_REQUIRE(point.from_data(valid_raw_point_iterator_source, false));

    point_iterator instance(point, offset);
    point_iterator expected(instance);

    auto initial = instance++;
    BOOST_REQUIRE(instance != expected);
    BOOST_REQUIRE(initial == expected);

    auto modified = instance--;
    BOOST_REQUIRE(instance == expected);
    BOOST_REQUIRE(modified != expected);
}

BOOST_AUTO_TEST_CASE(point_iterator__operator_plus_minus__roundtrip__success)
{
    point point;
    uint8_t offset = 5u;
    BOOST_REQUIRE(point.from_data(valid_raw_point_iterator_source, false));

    point_iterator instance(point, offset);
    point_iterator expected(instance);

    ++instance;
    BOOST_REQUIRE(instance != expected);

    --instance;
    BOOST_REQUIRE(instance == expected);
}

BOOST_AUTO_TEST_SUITE_END()


text:
// Copyright (C) 2019-2020 Zilliz. All rights reserved.
//
// 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 "db/Constants.h"
#include "db/Utils.h"
#include "db/meta/MetaConsts.h"
#include "db/meta/SqliteMetaImpl.h"
#include "db/utils.h"

#include <fiu-control.h>
#include <fiu-local.h>
#include <gtest/gtest.h>
#include <stdlib.h>
#include <time.h>
#include <boost/filesystem/operations.hpp>

TEST_F(MetaTest, COLLECTION_TEST) {
    auto collection_id = "meta_test_table";

    milvus::engine::meta::CollectionSchema collection;
    collection.collection_id_ = collection_id;
    auto status = impl_->CreateCollection(collection);
    ASSERT_TRUE(status.ok());

    auto gid = collection.id_;
    collection.id_ = -1;
    status = impl_->DescribeCollection(collection);
    ASSERT_TRUE(status.ok());
    ASSERT_EQ(collection.id_, gid);
    ASSERT_EQ(collection.collection_id_, collection_id);

    collection.collection_id_ = "not_found";
    status = impl_->DescribeCollection(collection);
    ASSERT_TRUE(!status.ok());

    collection.collection_id_ = collection_id;
    status = impl_->CreateCollection(collection);
    ASSERT_EQ(status.code(), milvus::DB_ALREADY_EXIST);

    status = impl_->DropCollections({collection.collection_id_});
    ASSERT_TRUE(status.ok());

    status = impl_->CreateCollection(collection);
    ASSERT_EQ(status.code(), milvus::DB_ERROR);

    collection.collection_id_ = "";
    status = impl_->CreateCollection(collection);
    ASSERT_TRUE(status.ok());
}

TEST_F(MetaTest, FAILED_TEST) {
    fiu_init(0);
    auto options = GetOptions();
    auto collection_id = "meta_test_table";
    milvus::engine::meta::CollectionSchema collection;
    collection.collection_id_ = collection_id;
    milvus::Status status;

    {
        FIU_ENABLE_FIU("SqliteMetaImpl.ValidateMetaSchema.NullConnection");
        ASSERT_ANY_THROW(milvus::engine::meta::SqliteMetaImpl impl(options.meta_));
        fiu_disable("SqliteMetaImpl.ValidateMetaSchema.NullConnection");
    }
    {
        // failed initialize
        auto options_1 = options;
        options_1.meta_.path_ = options.meta_.path_ + "1";
        if (boost::filesystem::is_directory(options_1.meta_.path_)) {
            boost::filesystem::remove_all(options_1.meta_.path_);
        }

        FIU_ENABLE_FIU("SqliteMetaImpl.Initialize.fail_create_directory");
        ASSERT_ANY_THROW(milvus::engine::meta::SqliteMetaImpl impl(options_1.meta_));
        fiu_disable("SqliteMetaImpl.Initialize.fail_create_directory");

        boost::filesystem::remove_all(options_1.meta_.path_);
    }
    {
        FIU_ENABLE_FIU("SqliteMetaImpl.CreateCollection.throw_exception");
        status = impl_->CreateCollection(collection);
        ASSERT_FALSE(status.ok());
        ASSERT_EQ(status.code(), milvus::DB_META_TRANSACTION_FAILED);
        fiu_disable("SqliteMetaImpl.CreateCollection.throw_exception");

        FIU_ENABLE_FIU("SqliteMetaImpl.CreateCollection.insert_throw_exception");
        collection.collection_id_ = "";
        status = impl_->CreateCollection(collection);
        ASSERT_FALSE(status.ok());
        fiu_disable("SqliteMetaImpl.CreateCollection.insert_throw_exception");

        // success create collection
        collection.collection_id_ = collection_id;
        status = impl_->CreateCollection(collection);
        ASSERT_TRUE(status.ok());
    }
    {
        FIU_ENABLE_FIU("SqliteMetaImpl.DescribeCollection.throw_exception");
        status = impl_->DescribeCollection(collection);
        ASSERT_FALSE(status.ok());
        fiu_disable("SqliteMetaImpl.DescribeCollection.throw_exception");
    }
    {
        FIU_ENABLE_FIU("SqliteMetaImpl.HasCollection.throw_exception");
        bool has = false;
        status = impl_->HasCollection(collection.collection_id_, has);
        ASSERT_FALSE(status.ok());
        ASSERT_FALSE(has);
        fiu_disable("SqliteMetaImpl.HasCollection.throw_exception");
    }
    {
        FIU_ENABLE_FIU("SqliteMetaImpl.AllCollections.throw_exception");
        std::vector<milvus::engine::meta::CollectionSchema> table_schema_array;
        status = impl_->AllCollections(table_schema_array);
        ASSERT_FALSE(status.ok());
        fiu_disable("SqliteMetaImpl.AllCollections.throw_exception");
    }
    {
        FIU_ENABLE_FIU("SqliteMetaImpl.DropCollection.throw_exception");
        status = impl_->DropCollections({collection.collection_id_});
        ASSERT_FALSE(status.ok());
        fiu_disable("SqliteMetaImpl.DropCollection.throw_exception");
    }
    {
        milvus::engine::meta::SegmentSchema schema;
        schema.collection_id_ = "notexist";
        status = impl_->CreateCollectionFile(schema);
        ASSERT_FALSE(status.ok());

        FIU_ENABLE_FIU("SqliteMetaImpl.CreateCollectionFile.throw_exception");
        schema.collection_id_ = collection_id;
        status = impl_->CreateCollectionFile(schema);
        ASSERT_FALSE(status.ok());
        fiu_disable("SqliteMetaImpl.CreateCollectionFile.throw_exception");
    }
    {
        FIU_ENABLE_FIU("SqliteMetaImpl.DeleteCollectionFiles.throw_exception");
        status = impl_->DeleteCollectionFiles({collection.collection_id_});
        ASSERT_FALSE(status.ok());
        fiu_disable("SqliteMetaImpl.DeleteCollectionFiles.throw_exception");
    }
    {
        milvus::engine::meta::FilesHolder files_holder;
        std::vector<size_t> ids;
        status = impl_->GetCollectionFiles("notexist", ids, files_holder);
        ASSERT_FALSE(status.ok());

        FIU_ENABLE_FIU("SqliteMetaImpl.GetCollectionFiles.throw_exception");
        status = impl_->GetCollectionFiles(collection_id, ids, files_holder);
        ASSERT_FALSE(status.ok());
        ASSERT_EQ(status.code(), milvus::DB_META_TRANSACTION_FAILED);
        fiu_disable("SqliteMetaImpl.GetCollectionFiles.throw_exception");
    }
    {
        FIU_ENABLE_FIU("SqliteMetaImpl.UpdateCollectionFlag.throw_exception");
        status = impl_->UpdateCollectionFlag(collection_id, 0);
        ASSERT_EQ(status.code(), milvus::DB_META_TRANSACTION_FAILED);
        fiu_disable("SqliteMetaImpl.UpdateCollectionFlag.throw_exception");
    }
    {
        FIU_ENABLE_FIU("SqliteMetaImpl.UpdateCollectionFile.throw_exception");
        milvus::engine::meta::SegmentSchema schema;
        schema.collection_id_ = collection_id;
        status = impl_->UpdateCollectionFile(schema);
        ASSERT_EQ(status.code(), milvus::DB_META_TRANSACTION_FAILED);
        fiu_disable("SqliteMetaImpl.UpdateCollectionFile.throw_exception");

        schema = {};
        schema.collection_id_ = "notexist";
        status = impl_->UpdateCollectionFile(schema);
        ASSERT_TRUE(status.ok());
    }
    {
        milvus::engine::meta::SegmentsSchema schemas;
        milvus::engine::meta::SegmentSchema schema;
        schema.collection_id_ = "notexits";
        schemas.emplace_back(schema);
        status = impl_->UpdateCollectionFiles(schemas);
        ASSERT_TRUE(status.ok());

        FIU_ENABLE_FIU("SqliteMetaImpl.UpdateCollectionFiles.throw_exception");
        status = impl_->UpdateCollectionFiles(schemas);
        ASSERT_EQ(status.code(), milvus::DB_META_TRANSACTION_FAILED);
        fiu_disable("SqliteMetaImpl.UpdateCollectionFiles.throw_exception");

        FIU_ENABLE_FIU("SqliteMetaImpl.UpdateCollectionFiles.fail_commited");
        status = impl_->UpdateCollectionFiles(schemas);
        ASSERT_EQ(status.code(), milvus::DB_META_TRANSACTION_FAILED);
        fiu_disable("SqliteMetaImpl.UpdateCollectionFiles.fail_commited");
    }
    {
        milvus::engine::CollectionIndex index;
        status = impl_->UpdateCollectionIndex("notexist", index);
        ASSERT_EQ(status.code(), milvus::DB_NOT_FOUND);

        FIU_ENABLE_FIU("SqliteMetaImpl.UpdateCollectionIndex.throw_exception");
        status = impl_->UpdateCollectionIndex("notexist", index);
        ASSERT_EQ(status.code(), milvus::DB_META_TRANSACTION_FAILED);
        fiu_disable("SqliteMetaImpl.UpdateCollectionIndex.throw_exception");

        FIU_ENABLE_FIU("SqliteMetaImpl.DescribeCollectionIndex.throw_exception");
        status = impl_->DescribeCollectionIndex(collection_id, index);
        ASSERT_EQ(status.code(), milvus::DB_META_TRANSACTION_FAILED);
        fiu_disable("SqliteMetaImpl.DescribeCollectionIndex.throw_exception");
    }
    {
        FIU_ENABLE_FIU("SqliteMetaImpl.UpdateCollectionFilesToIndex.throw_exception");
        status = impl_->UpdateCollectionFilesToIndex(collection_id);
        ASSERT_EQ(status.code(), milvus::DB_META_TRANSACTION_FAILED);
        fiu_disable("SqliteMetaImpl.UpdateCollectionFilesToIndex.throw_exception");
    }
    {
        FIU_ENABLE_FIU("SqliteMetaImpl.DropCollectionIndex.throw_exception");
        status = impl_->DropCollectionIndex(collection_id);
        ASSERT_EQ(status.code(), milvus::DB_META_TRANSACTION_FAILED);
        fiu_disable("SqliteMetaImpl.DropCollectionIndex.throw_exception");
    }
    {
        std::string partition = "part0";
        std::string partition_tag = "tag0";
        status = impl_->CreatePartition("notexist", partition, partition_tag, 0);
        ASSERT_EQ(status.code(), milvus::DB_NOT_FOUND);

        status = impl_->CreatePartition(collection_id, partition, partition_tag, 0);
        ASSERT_TRUE(status.ok());

        partition_tag = "tag1";
        status = impl_->CreatePartition(collection_id, partition, partition_tag, 0);
        ASSERT_FALSE(status.ok());

        // create empty name partition
        partition = "";
        status = impl_->CreatePartition(collection_id, partition, partition_tag, 0);
        ASSERT_TRUE(status.ok());

        std::vector<milvus::engine::meta::CollectionSchema> partions_schema;
        status = impl_->ShowPartitions(collection_id, partions_schema);
        ASSERT_TRUE(status.ok());
        ASSERT_EQ(partions_schema.size(), 2);

        partions_schema.clear();
        FIU_ENABLE_FIU("SqliteMetaImpl.ShowPartitions.throw_exception");
        status = impl_->ShowPartitions(collection_id, partions_schema);
        ASSERT_EQ(status.code(), milvus::DB_META_TRANSACTION_FAILED);
        fiu_disable("SqliteMetaImpl.ShowPartitions.throw_exception");

        std::string partion;
        FIU_ENABLE_FIU("SqliteMetaImpl.GetPartitionName.throw_exception");
        status = impl_->GetPartitionName(collection_id, "tag0", partion);
        ASSERT_EQ(status.code(), milvus::DB_META_TRANSACTION_FAILED);
        fiu_disable("SqliteMetaImpl.GetPartitionName.throw_exception");
    }
    {
        milvus::engine::meta::FilesHolder files_holder;
        status = impl_->FilesToSearch("notexist", files_holder);
        ASSERT_EQ(status.code(), milvus::DB_NOT_FOUND);

        FIU_ENABLE_FIU("SqliteMetaImpl.FilesToSearch.throw_exception");
        status = impl_->FilesToSearch(collection_id, files_holder);
        ASSERT_EQ(status.code(), milvus::DB_META_TRANSACTION_FAILED);
        fiu_disable("SqliteMetaImpl.FilesToSearch.throw_exception");
    }
    {
        milvus::engine::meta::SegmentSchema file;
        file.collection_id_ = collection_id;
        status = impl_->CreateCollectionFile(file);
        ASSERT_TRUE(status.ok());
        file.file_type_ = milvus::engine::meta::SegmentSchema::TO_INDEX;
        impl_->UpdateCollectionFile(file);

        milvus::engine::meta::FilesHolder files_holder;
        FIU_ENABLE_FIU("SqliteMetaImpl_FilesToIndex_CollectionNotFound");
        status = impl_->FilesToIndex(files_holder);
        ASSERT_EQ(status.code(), milvus::DB_NOT_FOUND);
        fiu_disable("SqliteMetaImpl_FilesToIndex_CollectionNotFound");

        FIU_ENABLE_FIU("SqliteMetaImpl.FilesToIndex.throw_exception");
        status = impl_->FilesToIndex(files_holder);
        ASSERT_EQ(status.code(), milvus::DB_META_TRANSACTION_FAILED);
        fiu_disable("SqliteMetaImpl.FilesToIndex.throw_exception");
    }
    {
        milvus::engine::meta::FilesHolder files_holder;
        std::vector<int> file_types;
        file_types.push_back(milvus::engine::meta::SegmentSchema::INDEX);
        FIU_ENABLE_FIU("SqliteMetaImpl.FilesByType.throw_exception");
        status = impl_->FilesByType(collection_id, file_types, files_holder);
        ASSERT_EQ(status.code(), milvus::DB_META_TRANSACTION_FAILED);
        fiu_disable("SqliteMetaImpl.FilesByType.throw_exception");
    }
    {
        milvus::engine::meta::FilesHolder files_holder;
        std::vector<milvus::engine::meta::CollectionSchema> collection_array;
        milvus::engine::meta::CollectionSchema schema;
        schema.collection_id_ = collection_id;
        collection_array.emplace_back(schema);
        std::vector<int> file_types;
        file_types.push_back(milvus::engine::meta::SegmentSchema::INDEX);
        FIU_ENABLE_FIU("SqliteMetaImpl.FilesByTypeEx.throw_exception");
        status = impl_->FilesByTypeEx(collection_array, file_types, files_holder);
        ASSERT_EQ(status.code(), milvus::DB_META_TRANSACTION_FAILED);
        fiu_disable("SqliteMetaImpl.FilesByTypeEx.throw_exception");
        status = impl_->FilesByTypeEx(collection_array, file_types, files_holder);
    }
    {
        uint64_t size = 0;
        FIU_ENABLE_FIU("SqliteMetaImpl.Size.throw_exception");
        status = impl_->Size(size);
        ASSERT_EQ(status.code(), milvus::DB_META_TRANSACTION_FAILED);
        fiu_disable("SqliteMetaImpl.Size.throw_exception");
    }
    {
        FIU_ENABLE_FIU("SqliteMetaImpl.CleanUpShadowFiles.fail_commited");
        status = impl_->CleanUpShadowFiles();
        ASSERT_EQ(status.code(), milvus::DB_META_TRANSACTION_FAILED);
        fiu_disable("SqliteMetaImpl.CleanUpShadowFiles.fail_commited");

        FIU_ENABLE_FIU("SqliteMetaImpl.CleanUpShadowFiles.throw_exception");
        status = impl_->CleanUpShadowFiles();
        ASSERT_EQ(status.code(), milvus::DB_META_TRANSACTION_FAILED);
        fiu_disable("SqliteMetaImpl.CleanUpShadowFiles.throw_exception");
    }
    {
        uint64_t count;
        status = impl_->Count("notexist", count);
        ASSERT_EQ(status.code(), milvus::DB_NOT_FOUND);

        FIU_ENABLE_FIU("SqliteMetaImpl.Count.throw_exception");
        status = impl_->Count("notexist", count);
        ASSERT_EQ(status.code(), milvus::DB_META_TRANSACTION_FAILED);
        fiu_disable("SqliteMetaImpl.Count.throw_exception");
    }
    {
        FIU_ENABLE_FIU("SqliteMetaImpl.CleanUpFilesWithTTL.RemoveFile_ThrowException");
        status = impl_->CleanUpFilesWithTTL(1);
        ASSERT_EQ(status.code(), milvus::DB_META_TRANSACTION_FAILED);
        fiu_disable("SqliteMetaImpl.CleanUpFilesWithTTL.RemoveFile_ThrowException");

        FIU_ENABLE_FIU("SqliteMetaImpl.CleanUpFilesWithTTL.RemoveFile_FailCommited");
        status = impl_->CleanUpFilesWithTTL(1);
        ASSERT_EQ(status.code(), milvus::DB_META_TRANSACTION_FAILED);
        fiu_disable("SqliteMetaImpl.CleanUpFilesWithTTL.RemoveFile_FailCommited");

        FIU_ENABLE_FIU("SqliteMetaImpl.CleanUpFilesWithTTL.RemoveCollection_Failcommited");
        status = impl_->CleanUpFilesWithTTL(1);
        ASSERT_EQ(status.code(), milvus::DB_META_TRANSACTION_FAILED);
        fiu_disable("SqliteMetaImpl.CleanUpFilesWithTTL.RemoveCollection_Failcommited");

        FIU_ENABLE_FIU("SqliteMetaImpl.CleanUpFilesWithTTL.RemoveCollection_ThrowException");
        status = impl_->CleanUpFilesWithTTL(1);
        ASSERT_EQ(status.code(), milvus::DB_META_TRANSACTION_FAILED);
        fiu_disable("SqliteMetaImpl.CleanUpFilesWithTTL.RemoveCollection_ThrowException");

        FIU_ENABLE_FIU("SqliteMetaImpl.CleanUpFilesWithTTL.RemoveCollectionFolder_ThrowException");
        status = impl_->CleanUpFilesWithTTL(1);
        ASSERT_EQ(status.code(), milvus::DB_META_TRANSACTION_FAILED);
        fiu_disable("SqliteMetaImpl.CleanUpFilesWithTTL.RemoveCollectionFolder_ThrowException");
    }
}

TEST_F(MetaTest, COLLECTION_FILE_TEST) {
    auto collection_id = "meta_test_table";

    milvus::engine::meta::CollectionSchema collection;
    collection.collection_id_ = collection_id;
    collection.dimension_ = 256;
    auto status = impl_->CreateCollection(collection);

    milvus::engine::meta::SegmentSchema table_file;
    table_file.collection_id_ = collection.collection_id_;
    status = impl_->CreateCollectionFile(table_file);
    ASSERT_TRUE(status.ok());
    ASSERT_EQ(table_file.file_type_, milvus::engine::meta::SegmentSchema::NEW);

    uint64_t cnt = 0;
    status = impl_->Count(collection_id, cnt);
    ASSERT_TRUE(status.ok());
    ASSERT_EQ(cnt, 0UL);

    auto file_id = table_file.file_id_;

    auto new_file_type = milvus::engine::meta::SegmentSchema::INDEX;
    table_file.file_type_ = new_file_type;

    status = impl_->UpdateCollectionFile(table_file);
    ASSERT_TRUE(status.ok());
    ASSERT_EQ(table_file.file_type_, new_file_type);
}

TEST_F(MetaTest, HYBRID_COLLECTION_TEST) {
    auto collection_id = "meta_test_hybrid";

    milvus::engine::meta::CollectionSchema collection;
    collection.collection_id_ = collection_id;
    collection.dimension_ = 128;
    milvus::engine::meta::hybrid::FieldsSchema fields_schema;
    fields_schema.fields_schema_.resize(2);
    fields_schema.fields_schema_[0].collection_id_ = collection_id;
    fields_schema.fields_schema_[0].field_name_ = "field_0";
    fields_schema.fields_schema_[0].field_type_ = (int32_t)milvus::engine::meta::hybrid::DataType::INT64;
    fields_schema.fields_schema_[0].field_params_ = "";

    fields_schema.fields_schema_[1].collection_id_ = collection_id;
    fields_schema.fields_schema_[1].field_name_ = "field_1";
    fields_schema.fields_schema_[1].field_type_ = (int32_t)milvus::engine::meta::hybrid::DataType::VECTOR;
    fields_schema.fields_schema_[1].field_params_ = "";

    auto status = impl_->CreateHybridCollection(collection, fields_schema);
    ASSERT_TRUE(status.ok());
    milvus::engine::meta::CollectionSchema describe_collection;
    milvus::engine::meta::hybrid::FieldsSchema describe_fields;
    describe_collection.collection_id_ = collection_id;
    status = impl_->DescribeHybridCollection(describe_collection, describe_fields);
    ASSERT_TRUE(status.ok());
    ASSERT_EQ(describe_fields.fields_schema_.size(), 2);
}

TEST_F(MetaTest, COLLECTION_FILE_ROW_COUNT_TEST) {
    auto collection_id = "row_count_test_table";

    milvus::engine::meta::CollectionSchema collection;
    collection.collection_id_ = collection_id;
    collection.dimension_ = 256;
    auto status = impl_->CreateCollection(collection);

    milvus::engine::meta::SegmentSchema table_file;
    table_file.row_count_ = 100;
    table_file.collection_id_ = collection.collection_id_;
    table_file.file_type_ = 1;
    status = impl_->CreateCollectionFile(table_file);

    uint64_t cnt = 0;
    status = impl_->Count(collection_id, cnt);
    ASSERT_EQ(table_file.row_count_, cnt);

    table_file.row_count_ = 99999;
    milvus::engine::meta::SegmentsSchema table_files = {table_file};
    status = impl_->UpdateCollectionFilesRowCount(table_files);
    ASSERT_TRUE(status.ok());

    cnt = 0;
    status = impl_->Count(collection_id, cnt);
    ASSERT_EQ(table_file.row_count_, cnt);

    std::vector<size_t> ids = {table_file.id_};
    milvus::engine::meta::FilesHolder files_holder;
    status = impl_->GetCollectionFiles(collection_id, ids, files_holder);

    milvus::engine::meta::SegmentsSchema& schemas = files_holder.HoldFiles();
    ASSERT_EQ(schemas.size(), 1UL);
    ASSERT_EQ(table_file.row_count_, schemas[0].row_count_);
    ASSERT_EQ(table_file.file_id_, schemas[0].file_id_);
    ASSERT_EQ(table_file.file_type_, schemas[0].file_type_);
    ASSERT_EQ(table_file.segment_id_, schemas[0].segment_id_);
    ASSERT_EQ(table_file.collection_id_, schemas[0].collection_id_);
    ASSERT_EQ(table_file.engine_type_, schemas[0].engine_type_);
    ASSERT_EQ(table_file.dimension_, schemas[0].dimension_);
    ASSERT_EQ(table_file.flush_lsn_, schemas[0].flush_lsn_);
}

TEST_F(MetaTest, ARCHIVE_TEST_DAYS) {
    srand(time(0));
    milvus::engine::DBMetaOptions options;
    options.path_ = "/tmp/milvus_test";
    unsigned int seed = 1;
    int days_num = rand_r(&seed) % 100;
    std::stringstream ss;
    ss << "days:" << days_num;
    options.archive_conf_ = milvus::engine::ArchiveConf("delete", ss.str());

    milvus::engine::meta::SqliteMetaImpl impl(options);
    auto collection_id = "meta_test_table";

    milvus::engine::meta::CollectionSchema collection;
    collection.collection_id_ = collection_id;
    auto status = impl.CreateCollection(collection);

    milvus::engine::meta::SegmentsSchema files;
    milvus::engine::meta::SegmentSchema table_file;
    table_file.collection_id_ = collection.collection_id_;

    auto cnt = 100;
    int64_t ts = milvus::engine::utils::GetMicroSecTimeStamp();
    std::vector<int> days;
    std::vector<size_t> ids;
    for (auto i = 0; i < cnt; ++i) {
        status = impl.CreateCollectionFile(table_file);
        table_file.file_type_ = milvus::engine::meta::SegmentSchema::NEW;
        int day = rand_r(&seed) % (days_num * 2);
        table_file.created_on_ = ts - day * milvus::engine::meta::DAY * milvus::engine::meta::US_PS - 10000;
        status = impl.UpdateCollectionFile(table_file);
        files.push_back(table_file);
        days.push_back(day);
        ids.push_back(table_file.id_);
    }

    {
        fiu_init(0);
        FIU_ENABLE_FIU("SqliteMetaImpl.Archive.throw_exception");
        status = impl.Archive();
        ASSERT_EQ(status.code(), milvus::DB_META_TRANSACTION_FAILED);
        fiu_disable("SqliteMetaImpl.Archive.throw_exception");
    }

    impl.Archive();
    int i = 0;

    milvus::engine::meta::FilesHolder files_holder;
    status = impl.GetCollectionFiles(table_file.collection_id_, ids, files_holder);
    ASSERT_TRUE(status.ok());

    milvus::engine::meta::SegmentsSchema& files_get = files_holder.HoldFiles();
    for (auto& file : files_get) {
        if (days[i] < days_num) {
            ASSERT_EQ(file.file_type_, milvus::engine::meta::SegmentSchema::NEW);
        }
        i++;
    }

    impl.DropAll();
}

TEST_F(MetaTest, ARCHIVE_TEST_DISK) {
    milvus::engine::DBMetaOptions options;
    options.path_ = "/tmp/milvus_test";
    options.archive_conf_ = milvus::engine::ArchiveConf("delete", "disk:11");

    milvus::engine::meta::SqliteMetaImpl impl(options);
    auto collection_id = "meta_test_group";

    milvus::engine::meta::CollectionSchema collection;
    collection.collection_id_ = collection_id;
    auto status = impl.CreateCollection(collection);

    milvus::engine::meta::SegmentsSchema files;
    milvus::engine::meta::SegmentSchema table_file;
    table_file.collection_id_ = collection.collection_id_;

    auto cnt = 10;
    auto each_size = 2UL;
    std::vector<size_t> ids;
    for (auto i = 0; i < cnt; ++i) {
        status = impl.CreateCollectionFile(table_file);
        table_file.file_type_ = milvus::engine::meta::SegmentSchema::NEW;
        table_file.file_size_ = each_size * milvus::engine::GB;
        status = impl.UpdateCollectionFile(table_file);
        files.push_back(table_file);
        ids.push_back(table_file.id_);
    }

    {
        fiu_init(0);
        FIU_ENABLE_FIU("SqliteMetaImpl.DiscardFiles.throw_exception");
        status = impl.Archive();
        fiu_disable("SqliteMetaImpl.DiscardFiles.throw_exception");

        FIU_ENABLE_FIU("SqliteMetaImpl.DiscardFiles.fail_commited");
        status = impl.Archive();
        fiu_disable("SqliteMetaImpl.DiscardFiles.fail_commited");
    }

    impl.Archive();
    int i = 0;

    milvus::engine::meta::FilesHolder files_holder;
    status = impl.GetCollectionFiles(table_file.collection_id_, ids, files_holder);
    ASSERT_TRUE(status.ok());

    milvus::engine::meta::SegmentsSchema& files_get = files_holder.HoldFiles();
    for (auto& file : files_get) {
        if (i >= 5) {
            ASSERT_EQ(file.file_type_, milvus::engine::meta::SegmentSchema::NEW);
        }
        ++i;
    }

    status = impl.GetCollectionFilesBySegmentId(table_file.segment_id_, files_holder);
    ASSERT_TRUE(status.ok());

    impl.DropAll();
}

TEST_F(MetaTest, COLLECTION_FILES_TEST) {
    auto collection_id = "meta_test_group";

    milvus::engine::meta::CollectionSchema collection;
    collection.collection_id_ = collection_id;
    auto status = impl_->CreateCollection(collection);

    uint64_t new_merge_files_cnt = 1;
    uint64_t new_index_files_cnt = 2;
    uint64_t backup_files_cnt = 3;
    uint64_t new_files_cnt = 4;
    uint64_t raw_files_cnt = 5;
    uint64_t to_index_files_cnt = 6;
    uint64_t index_files_cnt = 7;

    milvus::engine::meta::SegmentSchema table_file;
    table_file.collection_id_ = collection.collection_id_;

    for (auto i = 0; i < new_merge_files_cnt; ++i) {
        status = impl_->CreateCollectionFile(table_file);
        table_file.file_type_ = milvus::engine::meta::SegmentSchema::NEW_MERGE;
        status = impl_->UpdateCollectionFile(table_file);
    }

    for (auto i = 0; i < new_index_files_cnt; ++i) {
        status = impl_->CreateCollectionFile(table_file);
        table_file.file_type_ = milvus::engine::meta::SegmentSchema::NEW_INDEX;
        status = impl_->UpdateCollectionFile(table_file);
    }

    for (auto i = 0; i < backup_files_cnt; ++i) {
        status = impl_->CreateCollectionFile(table_file);
        table_file.file_type_ = milvus::engine::meta::SegmentSchema::BACKUP;
        table_file.row_count_ = 1;
        status = impl_->UpdateCollectionFile(table_file);
    }

    for (auto i = 0; i < new_files_cnt; ++i) {
        status = impl_->CreateCollectionFile(table_file);
        table_file.file_type_ = milvus::engine::meta::SegmentSchema::NEW;
        status = impl_->UpdateCollectionFile(table_file);
    }

    for (auto i = 0; i < raw_files_cnt; ++i) {
        status = impl_->CreateCollectionFile(table_file);
        table_file.file_type_ = milvus::engine::meta::SegmentSchema::RAW;
        table_file.row_count_ = 1;
        status = impl_->UpdateCollectionFile(table_file);
    }

    for (auto i = 0; i < to_index_files_cnt; ++i) {
        status = impl_->CreateCollectionFile(table_file);
        table_file.file_type_ = milvus::engine::meta::SegmentSchema::TO_INDEX;
        table_file.row_count_ = 1;
        status = impl_->UpdateCollectionFile(table_file);
    }

    for (auto i = 0; i < index_files_cnt; ++i) {
        status = impl_->CreateCollectionFile(table_file);
        table_file.file_type_ = milvus::engine::meta::SegmentSchema::INDEX;
        table_file.row_count_ = 1;
        status = impl_->UpdateCollectionFile(table_file);
    }

    uint64_t total_row_count = 0;
    status = impl_->Count(collection_id, total_row_count);
    ASSERT_TRUE(status.ok());
    ASSERT_EQ(total_row_count, raw_files_cnt + to_index_files_cnt + index_files_cnt);

    milvus::engine::meta::FilesHolder files_holder;
    status = impl_->FilesToIndex(files_holder);
    ASSERT_EQ(files_holder.HoldFiles().size(), to_index_files_cnt);

    files_holder.ReleaseFiles();
    status = impl_->FilesToMerge(collection.collection_id_, files_holder);
    ASSERT_EQ(files_holder.HoldFiles().size(), raw_files_cnt);

    files_holder.ReleaseFiles();
    status = impl_->FilesToIndex(files_holder);
    ASSERT_EQ(files_holder.HoldFiles().size(), to_index_files_cnt);

    files_holder.ReleaseFiles();
    status = impl_->FilesToSearch(collection_id, files_holder);
    ASSERT_EQ(files_holder.HoldFiles().size(), to_index_files_cnt + raw_files_cnt + index_files_cnt);

    std::vector<size_t> ids;
    for (auto& file : files_holder.HoldFiles()) {
        ids.push_back(file.id_);
    }
    size_t cnt = files_holder.HoldFiles().size();
    files_holder.ReleaseFiles();
    status = impl_->FilesByID(ids, files_holder);
    ASSERT_EQ(files_holder.HoldFiles().size(), cnt);

    files_holder.ReleaseFiles();
    ids = {9999999999UL};
    status = impl_->FilesByID(ids, files_holder);
    ASSERT_EQ(files_holder.HoldFiles().size(), 0);

    files_holder.ReleaseFiles();
    std::vector<int> file_types;
    status = impl_->FilesByType(collection.collection_id_, file_types, files_holder);
    ASSERT_TRUE(files_holder.HoldFiles().empty());
    ASSERT_FALSE(status.ok());

    file_types = {
        milvus::engine::meta::SegmentSchema::NEW,       milvus::engine::meta::SegmentSchema::NEW_MERGE,
        milvus::engine::meta::SegmentSchema::NEW_INDEX, milvus::engine::meta::SegmentSchema::TO_INDEX,
        milvus::engine::meta::SegmentSchema::INDEX,     milvus::engine::meta::SegmentSchema::RAW,
        milvus::engine::meta::SegmentSchema::BACKUP,
    };
    status = impl_->FilesByType(collection.collection_id_, file_types, files_holder);
    ASSERT_TRUE(status.ok());
    uint64_t total_cnt = new_index_files_cnt + new_merge_files_cnt + backup_files_cnt + new_files_cnt + raw_files_cnt +
                         to_index_files_cnt + index_files_cnt;
    ASSERT_EQ(files_holder.HoldFiles().size(), total_cnt);

    status = impl_->DeleteCollectionFiles({collection_id});
    ASSERT_TRUE(status.ok());

    status = impl_->CreateCollectionFile(table_file);
    table_file.file_type_ = milvus::engine::meta::SegmentSchema::NEW;
    status = impl_->UpdateCollectionFile(table_file);
    status = impl_->CleanUpShadowFiles();
    ASSERT_TRUE(status.ok());

    table_file.collection_id_ = collection.collection_id_;
    table_file.file_type_ = milvus::engine::meta::SegmentSchema::TO_DELETE;
    status = impl_->CreateCollectionFile(table_file);

    std::vector<int> files_to_delete;
    files_holder.ReleaseFiles();
    files_to_delete.push_back(milvus::engine::meta::SegmentSchema::TO_DELETE);
    status = impl_->FilesByType(collection_id, files_to_delete, files_holder);
    ASSERT_TRUE(status.ok());

    table_file.collection_id_ = collection_id;
    table_file.file_type_ = milvus::engine::meta::SegmentSchema::TO_DELETE;
    table_file.file_id_ = files_holder.HoldFiles().front().file_id_;
    status = impl_->CleanUpFilesWithTTL(1UL);
    ASSERT_TRUE(status.ok());

    status = impl_->DropCollections({collection_id});
    ASSERT_TRUE(status.ok());
}

TEST_F(MetaTest, INDEX_TEST) {
    auto collection_id = "index_test";

    milvus::engine::meta::CollectionSchema collection;
    collection.collection_id_ = collection_id;
    auto status = impl_->CreateCollection(collection);

    milvus::engine::CollectionIndex index;
    index.metric_type_ = 2;
    index.extra_params_ = {{"nlist", 1234}};
    index.engine_type_ = 3;
    status = impl_->UpdateCollectionIndex(collection_id, index);
    ASSERT_TRUE(status.ok());

    int64_t flag = 65536;
    status = impl_->UpdateCollectionFlag(collection_id, flag);
    ASSERT_TRUE(status.ok());

    milvus::engine::meta::CollectionSchema collection_info;
    collection_info.collection_id_ = collection_id;
    status = impl_->DescribeCollection(collection_info);
    ASSERT_EQ(collection_info.flag_, flag);

    milvus::engine::CollectionIndex index_out;
    status = impl_->DescribeCollectionIndex(collection_id, index_out);
    ASSERT_EQ(index_out.metric_type_, index.metric_type_);
    ASSERT_EQ(index_out.extra_params_, index.extra_params_);
    ASSERT_EQ(index_out.engine_type_, index.engine_type_);

    status = impl_->DropCollectionIndex(collection_id);
    ASSERT_TRUE(status.ok());
    status = impl_->DescribeCollectionIndex(collection_id, index_out);
    ASSERT_EQ(index_out.metric_type_, index.metric_type_);
    ASSERT_NE(index_out.engine_type_, index.engine_type_);

    status = impl_->UpdateCollectionFilesToIndex(collection_id);
    ASSERT_TRUE(status.ok());
}

TEST_F(MetaTest, LSN_TEST) {
    auto collection_id = "lsn_test";
    uint64_t lsn = 42949672960;

    milvus::engine::meta::CollectionSchema collection;
    collection.collection_id_ = collection_id;
    auto status = impl_->CreateCollection(collection);

    status = impl_->UpdateCollectionFlushLSN(collection_id, lsn);
    ASSERT_TRUE(status.ok());

    uint64_t temp_lsb = 0;
    status = impl_->GetCollectionFlushLSN(collection_id, temp_lsb);
    ASSERT_EQ(temp_lsb, lsn);

    status = impl_->SetGlobalLastLSN(lsn);
    ASSERT_TRUE(status.ok());

    temp_lsb = 0;
    status = impl_->GetGlobalLastLSN(temp_lsb);
    ASSERT_EQ(temp_lsb, lsn);
}


text:
#ifndef PRE_VARIANT_GET_HPP
#define PRE_VARIANT_GET_HPP

#include <boost/variant.hpp>
#include <mapbox/variant.hpp>

namespace pre { namespace variant {

  using ::boost::get;
  using ::mapbox::util::get;

}}

#endif


text:
/* ----------------------------------------------------------------------------

 * GTSAM Copyright 2010, Georgia Tech Research Corporation,
 * Atlanta, Georgia 30332-0415
 * All Rights Reserved
 * Authors: Frank Dellaert, et al. (see THANKS for the full author list)

 * See LICENSE for the license information

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

/**
 * @file    VariableSlots.cpp
 * @author  Richard Roberts
 * @date    Oct 5, 2010
 */

#include <gtsam/inference/VariableSlots.h>

#include <iostream>
#include <boost/foreach.hpp>

using namespace std;

namespace gtsam {

const size_t VariableSlots::Empty = numeric_limits<size_t>::max();

/** print */
void VariableSlots::print(const std::string& str) const {
  if(this->empty())
    cout << "empty" << endl;
  else {
    cout << str << "\n";
    cout << "Var:\t";
    BOOST_FOREACH(const value_type& slot, *this) { cout << slot.first << "\t"; }
    cout << "\n";

    for(size_t i=0; i<this->begin()->second.size(); ++i) {
      cout << "    \t";
      BOOST_FOREACH(const value_type& slot, *this) {
        if(slot.second[i] == Empty)
          cout << "x" << "\t";
        else
          cout << slot.second[i] << "\t";
      }
      cout << "\n";
    }
  }
}

/** equals */
bool VariableSlots::equals(const VariableSlots& rhs, double tol) const {
  return *this == rhs;
}

}


text:
/*
Copyright 2011-2015, Rogier van Dalen.

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

#ifndef RANGE_ITERATOR_RANGE_HPP_INCLUDED
#define RANGE_ITERATOR_RANGE_HPP_INCLUDED

#include <cassert>
#include <iterator>
#include <type_traits>

#include <boost/utility.hpp>
#include <boost/mpl/if.hpp>
#include <boost/mpl/and.hpp>

#include "utility/returns.hpp"

#include "core.hpp"

namespace range {

/**
Range that internally contains two iterators with the same type to denote its
begin and end.
The type of iterator determines which operations are possible.

There is a sharp difference between an iterator_range based on input iterators
on the one hand, and forward iterators or higher on the other hand.
An iterator_range based on input iterators can not be copied.
Therefore, it does not have a copy constructor; first() and drop() only take
an rvalue, as does chop(), which is the most useful operation.
An iterator_range based on forward iterators can be copied without any problems.

<c>default_direction (range)</c> just returns front.

<c>empty (range)</c> is always defined.

<c>size (range)</c> is defined only for random-access iterators.
The result type of size (range) is the unsigned version of the distance between
two iterators.

<c>first (range, front)</c> is defined for all types of iterators; but
<c>first (range, back)</c> is defined only for bidirectional iterators.

<c>drop (range, front)</c> is defined for input and forward iterators.
<c>drop (range, back)</c> is defined only for bidirectional iterators.
<c>drop (range, n, front)</c> and <c>drop (back, n, range)</c> are defined only
for random-access iterators.

The code for operations on this class is worth looking at, because it
embodies the difference between ranges and iterators.
Ranges only shrink, never grow.
In terms of the code, this means that \c begin is only ever incremented, not
decremented, and \c end is only ever decremented.
Also, ranges' ends are known, so it can be asserted that they are non-empty or
have at least a certain size for \c first() and \c drop().
This can be seen in the assertions.

\tparam Iterator
    The underlying iterator type.
    This must be an input iterator, or a forward iterator or higher.
    The things called "output iterators" are not supported.
*/

template <class Iterator, class Enable = void>
    class iterator_range;

namespace iterator_range_detail {

    /**
    Base class for both iterator_range's that can be copied, and ones that
    can't.
    */
    template <class Iterator> class iterator_range_base {
        typedef typename std::iterator_traits <Iterator>::iterator_category
            iterator_tag;
        static_assert (
            std::is_base_of <std::input_iterator_tag, iterator_tag>::value ||
            std::is_base_of <std::forward_iterator_tag, iterator_tag>::value,
            "The iterator must be an input iterator or a forward iterator.");
    public:
        typedef Iterator iterator_type;

        typedef typename std::make_unsigned <typename
            std::iterator_traits <Iterator>::difference_type>::type size_type;

        typedef typename std::iterator_traits <Iterator>::value_type value_type;

        iterator_range_base (Iterator const & begin, Iterator const & end)
        : begin_ (begin), end_ (end) {}

        iterator_range_base() = default;

        iterator_range_base (iterator_range_base const &) = default;

        // Use any move or copy constructor available, to make sure that moving
        // is defined.
        iterator_range_base (iterator_range_base && that)
        : begin_ (std::move (that.begin())), end_ (std::move (that.end())) {}

        iterator_range_base & operator = (iterator_range_base const &)
            = default;

        iterator_range_base & operator = (iterator_range_base && that) {
            this->begin_ = std::move (that.begin());
            this->end_ = std::move (that.end());
            return *this;
        }

        Iterator const & begin() const { return begin_; }
        Iterator & begin() { return begin_; }

        Iterator const & end() const { return end_; }
        Iterator & end() { return end_; }

    private:
        friend class helper::member_access;
        bool empty (direction::front) const { return begin_ == end_; }

        Iterator begin_;
        Iterator end_;
    };

} // namespace iterator_range_detail

/// \cond DONT_DOCUMENT
// Implementation for forward and higher iterators: copy is possible.
template <class Iterator>
    class iterator_range <Iterator, typename boost::enable_if <
        std::is_base_of <std::forward_iterator_tag, typename
            std::iterator_traits <Iterator>::iterator_category>
    >::type>
: public iterator_range_detail::iterator_range_base <Iterator>
{
    typedef iterator_range_detail::iterator_range_base <Iterator> base;
    typedef typename base::size_type size_type;
    typedef typename std::iterator_traits <Iterator>::iterator_category
        iterator_tag;

    // Types that can't be used, to effectively disable overloads.
    struct private_type;
    struct private_type_2;

    /// direction::back if the iterator is bidirectional, disabled otherwise.
    typedef typename boost::mpl::if_ <
        std::is_base_of <std::bidirectional_iterator_tag, iterator_tag>,
        direction::back, private_type>::type back_if_bidirectional;

    /// direction::front if the iterator is random access, disabled otherwise.
    typedef typename boost::mpl::if_ <
        std::is_base_of <std::random_access_iterator_tag, iterator_tag>,
        direction::front, private_type>::type front_if_random_access;

    /// direction::back if the iterator is random access, disabled otherwise.
    typedef typename boost::mpl::if_ <
        std::is_base_of <std::random_access_iterator_tag, iterator_tag>,
        direction::back, private_type_2>::type back_if_random_access;

    typedef decltype (*std::declval <Iterator const &>()) dereference_type;

public:
    iterator_range() = default;
    iterator_range (iterator_range const &) = default;
    iterator_range (iterator_range &&) = default;

    iterator_range (Iterator const & begin, Iterator const & end)
    : base (begin, end) {}

    iterator_range & operator = (iterator_range const &) = default;
    iterator_range & operator = (iterator_range &&) = default;

private:
    friend class helper::member_access;

    // first.
    dereference_type first (direction::front) const { return *this->begin(); }

    dereference_type first (back_if_bidirectional) const
    { return *boost::prior (this->end()); }

    // size.
    size_type size (front_if_random_access) const {
        auto distance = this->end() - this->begin();
        assert (distance >= 0);
        return typename base::size_type (distance);
    };

    // drop.
    iterator_range drop_one (direction::front) const
    { return iterator_range (boost::next (this->begin()), this->end()); }

    iterator_range drop_one (back_if_bidirectional) const
    { return iterator_range (this->begin(), boost::prior (this->end())); }

    iterator_range drop (size_type increment, front_if_random_access) const {
        assert (increment <= size (front));
        return iterator_range <Iterator> (
            this->begin() + increment, this->end());
    }

    iterator_range drop (size_type increment, back_if_random_access) const {
        assert (increment <= size (front));
        return iterator_range <Iterator> (
            this->begin(), this->end() - increment);
    }

    // chop_in_place.
    /*
    For forward iterators and up, the return type from dereferencing the
    iterator, possibly a reference type, is the appropriate return type.

    This is in contrast to chop_in_place for input iterators, below, which
    returns the value type.
    */
    dereference_type chop_in_place (direction::front)
    { return * this->begin() ++; }

    dereference_type chop_in_place (back_if_bidirectional)
    { return * -- this->end(); }
};

// Implementation for input iterators: copy is not possible; move is.
template <class Iterator>
    class iterator_range <Iterator, typename boost::enable_if <
        boost::mpl::and_ <
            std::is_base_of <std::input_iterator_tag, typename
                std::iterator_traits <Iterator>::iterator_category>,
            boost::mpl::not_ <
                std::is_base_of <std::forward_iterator_tag, typename
                    std::iterator_traits <Iterator>::iterator_category>>
    >>::type>
: public iterator_range_detail::iterator_range_base <Iterator>
{
    typedef iterator_range_detail::iterator_range_base <Iterator> base;
public:
    iterator_range() = default;
    // For input iterators, delete the copy constructor and provide only a
    // move constructor.
    iterator_range (iterator_range const &) = delete;
    iterator_range (iterator_range &&) = default;

    iterator_range (Iterator const & begin, Iterator const & end)
    : base (begin, end) {}

    iterator_range & operator = (iterator_range const &) = delete;
    iterator_range & operator = (iterator_range &&) = default;

    // Only "chop" is implemented, in namespace iterator_range_operation.

    /*
    Input iterators need special handling.
    Dereferencing an input iterator returns something that can be
    convertible to the value_type, which may apparently become impossible to
    use after it is incremented.
    Therefore, it should be converted to the value type straight away.
    */
    typename std::iterator_traits <Iterator>::value_type
        chop_in_place (direction::front)
    { return * this->begin() ++; }
};
/// \endcond

namespace iterator_range_operation {
    template <class IteratorTag> struct iterator_range_tag {};
} // namespace iterator_range_operation

template <class Iterator>
    struct tag_of_qualified <iterator_range <Iterator>>
{
    typedef iterator_range_operation::iterator_range_tag <typename
        std::iterator_traits <Iterator>::iterator_category> type;
};

/* make_iterator_range */

namespace callable {

    /// Start a new namespace so "using std::begin" does not pollute the
    /// namespace.
    namespace make_iterator_range_detail {

        using std::begin;
        using std::end;

        // From two iterators or a container.
        struct make_iterator_range {
            // IteratorCategory is merely to check that Iterator is an iterator.
            template <class Iterator, class IteratorCategory = typename
                std::iterator_traits <Iterator>::iterator_category>
            iterator_range <Iterator> operator() (
                Iterator const & begin, Iterator const & end) const
            { return iterator_range <Iterator> (begin, end); }

            template <class Container, class Iterator
                = decltype (begin (std::declval <Container &&>()))>
            iterator_range <Iterator> operator() (Container && container)
                const
            {
                return iterator_range <Iterator> (
                    begin (container), end (container));
            }
        };

        struct make_move_iterator_range {
            template <class Container,
                class RawIterator = typename std::decay <
                    decltype (begin (std::declval <Container &>()))>::type,
                class Iterator
                = typename std::conditional <
                    std::is_same <Container,
                        typename std::decay <Container>::type>::value,
                    std::move_iterator <RawIterator>, RawIterator
                >::type>
            iterator_range <Iterator> operator() (Container && container) const
            {
                return iterator_range <Iterator> (
                    Iterator (begin (container)), Iterator (end (container)));
            }
        };

    } // namespace make_iterator_range_detail

    using make_iterator_range_detail::make_iterator_range;
    using make_iterator_range_detail::make_move_iterator_range;

} // namespace callable

/**
Make an iterator_range from begin and end iterators or from a container.
Give either \a begin and \a end, or \a container.

\param begin The begin iterator.
\param end The past-the-end iterator.

\param container
    The container to iterate.
    Begin and end iterators are found with unqualified calls to \c begin
    and \c end, after <c>using std::begin</c> and <c>using std::end</c>.
*/
static constexpr auto make_iterator_range = callable::make_iterator_range();

/**
Make an iterator_range from a container that will be read only once.

\param container
    The container to iterate.
    Begin and end iterators are found with unqualified calls to \c begin
    and \c end, after <c>using std::begin</c> and <c>using std::end</c>.
    If this is an rvalue reference, then the iterator_range will use
    std::move_iterator.
*/
static constexpr auto make_move_iterator_range
    = callable::make_move_iterator_range();

namespace iterator_range_operation {

    template <class IteratorTag, class Range> inline
        auto implement_chop (iterator_range_tag <IteratorTag> const & tag,
            Range && range, direction::front const & direction)
    RETURNS (helper::chop_by_chop_in_place (
        std::forward <Range> (range), direction));

} // namespace iterator_range_operation

} // namespace range

#endif  // RANGE_ITERATOR_RANGE_HPP_INCLUDED

max_stars_repo_name: rogiervd/range

max_issues_repo_name: rogiervd/range

max_forks_repo_name: rogiervd/range


text:
#include <boost/bind.hpp>
#include <boost/array.hpp>
#include <functional>
#include <vector>
#include <iostream>
#include <cmath>

void print_number(std::string prefix, int number) {
	std::cout << prefix << number << std::endl;
}

int summation(int a, int b){
	return a + b;
}

int power(int a, int n) {
	return std::pow(a, n);
}

struct Foo {
	void say_hello_to(std::string s){
		std::cout << "Hi " << s << "!" << std::endl;
	}
};

// This solve a bug with clang and libc++
// http://stackoverflow.com/q/29324619
template class std::basic_string<char>;

int main(int argc, char* argv[]) {
	std::vector<int> vector = {1, 2, 3, 4, 5};
    boost::array<std::string, 3> str_values = {"We ", "are", "the champions!"};

	{
		// simple use of binding function
		// arbitrary function objects, functions, function pointers, and member function pointers
		std::for_each(vector.begin(), vector.end(), boost::bind(print_number, "Value: ", _1));

		std::size_t count = std::count_if(vector.begin(), vector.end(), boost::bind(std::less<int>(), 2, _1));
        count = std::count_if(str_values.begin(), str_values.end(), boost::bind(&std::string::empty, _1));
    }

	{
		// function composition
		auto composition = boost::bind(power, boost::bind(summation, _1, 2), _2);
		std::cout << composition(1, 2) << std::endl;
	}

	{
		// member function, make a copy of Foo(), if don't want a copy use ref(Foo()) instead
		auto member_function = boost::bind(&Foo::say_hello_to, Foo(), _1);
		member_function("John");
	}

	{
		// operators
		std::copy_if(vector.begin(), vector.end(),
					 std::ostream_iterator<int>(std::cout, " "),
					 !boost::bind<bool>([](int n)->bool{ return n % 2 == 0; }, _1));

        std::size_t count = std::count_if(str_values.begin(), str_values.end(),
                                          boost::bind(&std::string::size, _1) < 5);
    }

	return EXIT_SUCCESS;
}

max_stars_repo_name: dexpota/boost-api-examples

max_issues_repo_name: dexpota/boost-api-examples

max_forks_repo_name: dexpota/boost-api-examples


text:
//
// Copyright (c) 2003 Kresimir Fresl
// Copyright (c) 2010 Thomas Klimpel
//
// 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_NUMERIC_BINDINGS_DETAIL_COMPLEX_UTILS_HPP
#define BOOST_NUMERIC_BINDINGS_DETAIL_COMPLEX_UTILS_HPP

#include <iterator>
#include <boost/numeric/bindings/begin.hpp>
#include <boost/numeric/bindings/end.hpp>
#include <boost/numeric/bindings/is_complex.hpp>
#include <boost/numeric/bindings/remove_imaginary.hpp>
#include <boost/numeric/bindings/value_type.hpp>
#include <boost/numeric/bindings/vector_view.hpp>
#include <boost/utility/enable_if.hpp>

namespace boost {
namespace numeric {
namespace bindings {

namespace detail {

#ifdef BOOST_NUMERIC_BINDINGS_BY_THE_BOOK
template <typename It>
void inshuffle(It it, std::size_t n) {
  if (n==0) return;
  for (std::size_t i = 0; 2*i < n; ++i) {
    std::size_t k = 2*i + 1;
    while (2*k <= n) k *= 2;
    typename std::iterator_traits<It>::value_type tmp = it[n+i];
    it[n+i] = it[k-1];
    while (k % 2 == 0) {
      it[k-1] = it[(k/2)-1];
      k /= 2;
    }
    it[k-1] = tmp;
  }
  std::size_t kmin = 1;
  while (2*kmin <= n) kmin *= 2;
  for (std::size_t i = 0; 4*i+1 < n; ++i) {
    std::size_t k = 2*i + 1;
    while (2*k <= n) k *= 2;
    std::size_t k1 = 2*(i+1) + 1;
    while (2*k1 <= n) k1 *= 2;
    if (k > k1) {
      if (k1 < kmin) {
        kmin = k1;
        inshuffle(it+n, i+1);
      }
      else
        inshuffle(it+n+1, i);
    }
  }
  return inshuffle(it+n+(n%2), n/2);
}
#else
template <typename It>
void inshuffle(It it, std::size_t n) {
  while (n > 0) {
    std::size_t kmin = 1;
    while (kmin <= n)
      kmin *= 2;
    {
      std::size_t kk = kmin/2;
      It itn = it + n;
      for (std::size_t i = 0, s = (n+1)/2; i < s; ++i) {
        std::size_t k = (2*i+1)*kk;
        while (k > n) {
          k /= 2;
          kk /= 2;
        }
        // apply the cyclic permutation
        typename std::iterator_traits<It>::value_type tmp = itn[i];
        itn[i] = it[k-1];
        while (k % 2 == 0) {
          it[k-1] = it[(k/2)-1];
          k /= 2;
        }
        it[k-1] = tmp;
      }
    }
    // the optimized computation of k fails for n=2,
    // so skip the 'normalization' loop when possible
    if (n > 3) {
      std::size_t kk = kmin/4;
      for (std::size_t i = 1; 4*i < n+3; ++i) {
        std::size_t k = (2*i+1)*kk;
        if (k > n) {
          kk /= 2;
          if (k < kmin) {
            kmin = k;
            // if kmin is updated, do an in-shuffle
            inshuffle(it+n, i);
          }
          else
            // otherwise do an out-shuffle
            inshuffle(it+n+1, i-1);
        }
      }
    }
    // implement the tail recursion as an iteration
    it += n+(n%2);
    n /= 2;
  }
}
#endif

// Reorders a real array followed by an imaginary array to a true complex array
// where real and imaginary part of each number directly follow each other.
template <typename VectorW>
typename boost::enable_if< is_complex< typename bindings::value_type< VectorW >::type >, void >::type
interlace (VectorW& w) {
  typedef typename bindings::value_type< VectorW >::type value_type;
  typedef typename bindings::remove_imaginary< value_type >::type real_type;
  value_type* pw = bindings::begin_value(w);
  std::ptrdiff_t n = bindings::end_value(w) - pw;
  if (n < 2) return;
  inshuffle(reinterpret_cast<real_type*> (pw)+1, n-1);
}

} // namespace detail

namespace result_of {

template< typename VectorW >
struct real_part_view {
    typedef typename bindings::result_of::vector_view< typename
      bindings::remove_imaginary< typename
      bindings::value_type< VectorW >::type
      >::type >::type type;
};

template< typename VectorW >
struct imag_part_view {
    typedef typename bindings::result_of::vector_view< typename
      bindings::remove_imaginary< typename
      bindings::value_type< VectorW >::type
      >::type >::type type;
};

} // namespace result_of

namespace detail {

// Creates a real vector_view to the first half of the complex array,
// which is intended to be filled by the real part
template <typename VectorW>
typename boost::enable_if< is_complex< typename bindings::value_type< VectorW >::type >,
        typename result_of::real_part_view< VectorW >::type const >::type
real_part_view (VectorW& w) {
  typedef typename bindings::value_type< VectorW >::type value_type;
  typedef typename bindings::remove_imaginary< value_type >::type real_type;
  value_type* pw = bindings::begin_value(w);
  std::ptrdiff_t n = bindings::end_value(w) - pw;
  return bindings::vector_view(reinterpret_cast<real_type*> (pw), n);
}

// Creates a real vector_view to the second half of the complex array,
// which is intended to be filled by the imaginary part
template <typename VectorW>
typename boost::enable_if< is_complex< typename bindings::value_type< VectorW >::type >,
        typename result_of::imag_part_view< VectorW >::type const >::type
imag_part_view (VectorW& w) {
  typedef typename bindings::value_type< VectorW >::type value_type;
  typedef typename bindings::remove_imaginary< value_type >::type real_type;
  value_type* pw = bindings::begin_value(w);
  std::ptrdiff_t n = bindings::end_value(w) - pw;
  return bindings::vector_view(reinterpret_cast<real_type*> (pw)+n, n);
}

} // namespace detail

} // namespace bindings
} // namespace numeric
} // namespace boost

#endif

max_stars_repo_name: ljktest/siconos

max_issues_repo_name: ljktest/siconos

max_forks_repo_name: ljktest/siconos


text:
//               Copyright Marek Dalewski 2017
// Distributed under the Boost Software License, Version 1.0.
//        (See accompanying file LICENSE.md or copy at
//           http://www.boost.org/LICENSE_1_0.txt)

#include <commander/algorithm.hpp>

#include <boost/test/unit_test.hpp>

#include <tuple>
#include <vector>

BOOST_AUTO_TEST_CASE( tuple_visit )
{
    std::vector<uint32_t> results;

    auto call = [&results](const auto& item) -> void {
        results.emplace_back(item);
        return;
    };

    std::tuple<>                            empty_tuple;
    std::tuple<uint8_t, uint16_t, uint32_t> tuple_of_ints   = {0, 1, 2};
    std::tuple<float, double, long double>  tuple_of_floats = {3.3, 4.4, 5.5};
    std::tuple<uint64_t>                    tuple_uint64_t  = {6};

    {
        results.clear();
        commander::tuple_visit(call, empty_tuple);
        BOOST_CHECK(results.size() == 0);

        results.clear();
        commander::tuple_visit(call, empty_tuple, tuple_uint64_t);
        BOOST_CHECK(results.size() == 1);
        BOOST_CHECK(results.at(0) == 6);

        results.clear();
        commander::tuple_visit(call, tuple_uint64_t, empty_tuple);
        BOOST_CHECK(results.size() == 1);
        BOOST_CHECK(results.at(0) == 6);
    }

    {
        results.clear();
        commander::tuple_visit(call, tuple_of_ints);
        BOOST_CHECK(results.size() == 3);
        BOOST_CHECK(results.at(0) == 0);
        BOOST_CHECK(results.at(1) == 1);
        BOOST_CHECK(results.at(2) == 2);

        results.clear();
        commander::tuple_visit(call, tuple_of_ints, tuple_of_floats);
        BOOST_CHECK(results.size() == 6);
        BOOST_CHECK(results.at(0) == 0);
        BOOST_CHECK(results.at(1) == 1);
        BOOST_CHECK(results.at(2) == 2);
        BOOST_CHECK(results.at(3) == 3);
        BOOST_CHECK(results.at(4) == 4);
        BOOST_CHECK(results.at(5) == 5);
    }

    {
        results.clear();
        commander::tuple_visit(call, tuple_uint64_t);
        BOOST_CHECK(results.size() == 1);
        BOOST_CHECK(results.at(0) == 6);

        results.clear();
        commander::tuple_visit(call, tuple_uint64_t, tuple_of_ints);
        BOOST_CHECK(results.size() == 4);
        BOOST_CHECK(results.at(0) == 6);
        BOOST_CHECK(results.at(1) == 0);
        BOOST_CHECK(results.at(2) == 1);
        BOOST_CHECK(results.at(3) == 2);

        results.clear();
        commander::tuple_visit(call, tuple_of_ints, tuple_uint64_t);
        BOOST_CHECK(results.size() == 4);
        BOOST_CHECK(results.at(0) == 0);
        BOOST_CHECK(results.at(1) == 1);
        BOOST_CHECK(results.at(2) == 2);
        BOOST_CHECK(results.at(3) == 6);
    }
}

max_stars_repo_name: daishe/commander

max_issues_repo_name: daishe/commander

max_forks_repo_name: daishe/commander


text:
//
// Created by FyS on 21/05/17.
//

#ifndef FREESOULS_FYSBUS_HH
#define FREESOULS_FYSBUS_HH

#include <string>
#include <vector>
#include <map>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/ini_parser.hpp>
#include <LockFreeQueue.hh>
#include <QueueContainer.hh>

namespace fys::mq {

    /**
     * Fys Bus :
     * A bus is initialized thanks to a configuration file which contain tag
     * [bus] : which is used to configure the name of the bus (node "name")
     *         which is used to configure the number N of queue in the bus (node "number_queue")
     *
     * [queue1]   : configure the queue 1's name and min max op code assigned to this queue
     * [queue2]   : same as above for queue 2
     * [queue...] : same as above for ...
     * [queue N]  : same as above for queue N (last queue)
     *
     * Each queue has to have their configuration associated,
     * If two queue are overlapping in terms of opcode, an error is thrown at the initialization
     *
     */
    template <class T, int SIZE_QUEUES>
    class FysBus {

    public:
        using ptr = std::shared_ptr<FysBus<T, SIZE_QUEUES> >;
        using wptr = std::weak_ptr<FysBus<T, SIZE_QUEUES> >;

        ~FysBus() {
            for (unsigned i = 0; i < _queues.size(); ++i) {
                delete(_queues.at(i));
            }
        }

        explicit FysBus(int queueNumber) {
            for (int i = 0; i < queueNumber; ++i)
                _queues.emplace_back(new LockFreeQueue<QueueContainer<T>, SIZE_QUEUES>());
        }

        void pushInBus(QueueContainer<T> &&message) {
            _queues.at(message.getOpCodeMsg())->push(std::forward<QueueContainer<T> >(message));
        }

        std::optional<QueueContainer<T> > popFromBus(unsigned int indexQueueInBus) {
            if (isIndexQueueLegitimate(indexQueueInBus)) {
                return _queues.at(indexQueueInBus)->pop();
            }
            return std::optional<QueueContainer<T> > {};
        }

        inline bool isIndexQueueLegitimate(unsigned int indexQueueInBus) {
            return indexQueueInBus < _queues.size();
        }

    protected:
        std::vector<LockFreeQueue<QueueContainer<T>, SIZE_QUEUES> *> _queues;
    };

}

#endif //FREESOULS_FYSBUS_HH

max_stars_repo_name: FreeYourSoul/LockFreeMQ

max_issues_repo_name: FreeYourSoul/LockFreeMQ

max_forks_repo_name: FreeYourSoul/LockFreeMQ


text:
//
// keyvi - A key value store.
//
// Copyright 2015 Hendrik Muhs<hendrik.muhs@gmail.com>
//
// 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.
//

/*
 * json_value_test.cpp
 *
 *  Created on: Oct 27, 2016
 *      Author: hendrik
 */

#include <cmath>
#include <limits>
#include <sstream>

#include <boost/test/unit_test.hpp>

#include "rapidjson/document.h"

#include "keyvi/util/json_value.h"

namespace keyvi {
namespace util {

BOOST_AUTO_TEST_SUITE(JsonValueTests)

BOOST_AUTO_TEST_CASE(EncodeDecodeTest) {
  std::string input =
      "{\"hello\":\"world\",\"t\":true,\"f\":false,\"n\":null,\"i\":123,\"j\":-123,\"pi\":3.1415998935699465,\"a\":[1,"
      "2,3,4],\"d\":{\"k\":\"v\"}}";

  std::string encoded = EncodeJsonValue(input);
  std::string output = DecodeJsonValue(encoded);

  BOOST_CHECK_EQUAL(input, output);

  std::string encoded_single_precision_float = EncodeJsonValue(input, true);
  std::string output_single_precision_float = DecodeJsonValue(encoded_single_precision_float);

  BOOST_CHECK_EQUAL(input, output_single_precision_float);
}

BOOST_AUTO_TEST_CASE(EncodeDecodeFloats) {
  std::stringstream string_stream;
  string_stream << std::scientific;

  string_stream << "{\"f_min\":" << std::numeric_limits<float>::min()
                << ",\"f_max\":" << std::numeric_limits<float>::max()
                << ",\"d_min\":" << std::numeric_limits<double>::min()
                << ",\"d_max\":" << std::numeric_limits<double>::max()
                << ",\"nan\":NaN,\"inf\":Inf,\"ninf\":-Infinity}";

  std::string input = string_stream.str();
  std::string encoded = EncodeJsonValue(input);
  std::string output = DecodeJsonValue(encoded);

  rapidjson::Document json_document;

  json_document.Parse<rapidjson::kParseNanAndInfFlag>(output);
  BOOST_CHECK(!json_document.HasParseError());

  BOOST_CHECK(json_document["f_min"].IsNumber());
  BOOST_CHECK_CLOSE(json_document["f_min"].GetDouble(), std::numeric_limits<float>::min(), 0.0001);
  BOOST_CHECK(json_document["f_max"].IsNumber());
  BOOST_CHECK_CLOSE(json_document["f_max"].GetDouble(), std::numeric_limits<float>::max(), 0.0001);
  BOOST_CHECK(json_document["d_min"].IsNumber());
  BOOST_CHECK_CLOSE(json_document["d_min"].GetDouble(), std::numeric_limits<double>::min(), 0.0001);
  BOOST_CHECK(json_document["d_max"].IsNumber());
  BOOST_CHECK_CLOSE(json_document["d_max"].GetDouble(), std::numeric_limits<double>::max(), 0.0001);
  BOOST_CHECK(json_document["nan"].IsNumber());
  BOOST_CHECK(std::isnan(json_document["nan"].GetDouble()));
  BOOST_CHECK(json_document["inf"].IsNumber());
  BOOST_CHECK_EQUAL(json_document["inf"].GetDouble(), std::numeric_limits<double>::infinity());
  BOOST_CHECK(json_document["ninf"].IsNumber());
  BOOST_CHECK_EQUAL(json_document["ninf"].GetDouble(), -std::numeric_limits<double>::infinity());

  std::string encoded_single_precision_float = EncodeJsonValue(input, true);
  std::string output_single_precision_float = DecodeJsonValue(encoded_single_precision_float);

  json_document.Parse<rapidjson::kParseNanAndInfFlag>(output_single_precision_float);
  BOOST_CHECK(!json_document.HasParseError());

  BOOST_CHECK(json_document["f_min"].IsNumber());
  BOOST_CHECK_CLOSE(json_document["f_min"].GetDouble(), std::numeric_limits<float>::min(), 0.0001);
  BOOST_CHECK(json_document["f_max"].IsNumber());
  BOOST_CHECK_CLOSE(json_document["f_max"].GetDouble(), std::numeric_limits<float>::max(), 0.0001);
  BOOST_CHECK(json_document["d_min"].IsNumber());
  BOOST_CHECK_CLOSE(json_document["d_min"].GetDouble(), std::numeric_limits<double>::min(), 0.0001);
  BOOST_CHECK(json_document["d_max"].IsNumber());
  BOOST_CHECK_CLOSE(json_document["d_max"].GetDouble(), std::numeric_limits<double>::max(), 0.0001);
  BOOST_CHECK(json_document["nan"].IsNumber());
  BOOST_CHECK(std::isnan(json_document["nan"].GetDouble()));
  BOOST_CHECK(json_document["inf"].IsNumber());
  BOOST_CHECK_EQUAL(json_document["inf"].GetDouble(), std::numeric_limits<double>::infinity());
  BOOST_CHECK(json_document["ninf"].IsNumber());
  BOOST_CHECK_EQUAL(json_document["ninf"].GetDouble(), -std::numeric_limits<double>::infinity());

  BOOST_CHECK(encoded.size() > encoded_single_precision_float.size());
}

BOOST_AUTO_TEST_SUITE_END()

} /* namespace util */
} /* namespace keyvi */