text:
#include "Utils.h"

#include <opencv2/imgproc/imgproc.hpp>

#include <Eigen/Core>

#include <boost/spirit/include/qi.hpp>
#include <boost/tokenizer.hpp>

#include <fstream>
#include <iostream>
#include <memory>

namespace nuisken {

std::vector<std::string> getFeatureNames(FeatureType type) {
    if (type == HF || type == HF_PCA) {
        return {"intensity", "x_derivatives", "y_derivatives", "t_derivatives", "x_flow", "y_flow"};
    } else if (type == HF_WITHOUT_FLOW) {
        return {"intensity", "x_derivatives", "y_derivatives", "t_derivatives"};
    } else {
        return {};
    }
}

namespace string {

std::vector<std::string> split(const std::string& str, char delimiter) {
    std::vector<std::string> results;
    std::size_t current = 0;
    std::size_t found;
    while ((found = str.find_first_of(delimiter, current)) != std::string::npos) {
        results.emplace_back(str, current, found - current);
        current = found + 1;
    }

    results.emplace_back(str, current, str.size() - current);
    return results;
}
}

namespace io {

std::string readFile(const std::string& filePath) {
    std::ifstream inputStream(filePath);
    if (!inputStream.is_open()) {
        return "";
    }

    inputStream.seekg(0, inputStream.end);
    std::size_t size = static_cast<std::size_t>(inputStream.tellg());
    if (size == 0) {
        return "";
    }
    inputStream.seekg(0, inputStream.beg);
    auto file = std::unique_ptr<char[]>(new char[size]);
    file[size - 1] = '\0';
    inputStream.read(file.get(), size);

    return std::string(file.get(), size);
}

void readSTIPFeatures(const std::string& filePath,
                      std::vector<std::vector<Eigen::MatrixXf>>& features,
                      std::vector<cv::Vec3i>& points) {
    std::string file = readFile(filePath);
    std::vector<std::string> lines = string::split(file, '\n');
    for (const auto& line : lines) {
        if (line.find('#') != std::string::npos) {
            continue;
        }

        std::vector<std::string> splitResults = string::split(line, ' ');

        if (splitResults.size() == 1) {
            break;
        } else if (splitResults.size() != 172) {
            break;
        }

        int xIndex = 5;
        int yIndex = 4;
        int tIndex = 6;
        cv::Vec3i centerPoint;
        boost::spirit::qi::parse(std::begin(splitResults.at(tIndex)),
                                 std::end(splitResults.at(tIndex)), boost::spirit::qi::int_,
                                 centerPoint(T));
        boost::spirit::qi::parse(std::begin(splitResults.at(yIndex)),
                                 std::end(splitResults.at(yIndex)), boost::spirit::qi::int_,
                                 centerPoint(Y));
        boost::spirit::qi::parse(std::begin(splitResults.at(xIndex)),
                                 std::end(splitResults.at(xIndex)), boost::spirit::qi::int_,
                                 centerPoint(X));

        int hogBeginIndex = 9;
        int numberOfHogDimension = 72;
        Eigen::MatrixXf hog(1, numberOfHogDimension);
        for (int i = 0; i < numberOfHogDimension; ++i) {
            boost::spirit::qi::parse(std::begin(splitResults.at(i + hogBeginIndex)),
                                     std::end(splitResults.at(i + hogBeginIndex)),
                                     boost::spirit::qi::double_, hog.coeffRef(0, i));
        }

        int hofBeginIndex = 81;
        int numberOfHofDimension = 90;
        Eigen::MatrixXf hof(1, numberOfHofDimension);
        for (int i = 0; i < numberOfHofDimension; ++i) {
            boost::spirit::qi::parse(std::begin(splitResults.at(i + hofBeginIndex)),
                                     std::end(splitResults.at(i + hofBeginIndex)),
                                     boost::spirit::qi::double_, hof.coeffRef(0, i));
        }

        std::vector<Eigen::MatrixXf> featureVectors;
        featureVectors.push_back(hog);
        featureVectors.push_back(hof);

        features.push_back(featureVectors);
        points.push_back(centerPoint);
    }
}
}

namespace actionvolume {

std::vector<std::pair<double, cv::Vec3f>> readActionPositions(const std::string& filePath) {
    std::vector<std::pair<double, cv::Vec3f>> actionPositions;

    std::ifstream inputStream(filePath);
    std::string line;
    while (std::getline(inputStream, line)) {
        if (line.find("[") != std::string::npos) {
            boost::char_separator<char> separator(",[]");
            boost::tokenizer<boost::char_separator<char>> tokenizer(line, separator);
            std::vector<std::string> tokens;
            std::copy(std::begin(tokenizer), std::end(tokenizer), std::back_inserter(tokens));

            cv::Vec3f actionPosition(std::stod(tokens.at(0)), std::stod(tokens.at(1)),
                                     std::stod(tokens.at(2)));
            actionPositions.emplace_back(std::stod(tokens.at(3)), actionPosition);
        }
    }

    return actionPositions;
}

void readActionPositions(const std::string& filePath,
                         std::vector<std::pair<double, cv::Vec3f>>& actionPositions,
                         std::vector<std::vector<cv::Vec3i>>& contributionPointsOfActionPosition,
                         double rate) {
    std::ifstream inputStream(filePath);
    std::string line;

    std::vector<std::pair<double, cv::Vec3i>> contributionPointsAndScores;
    while (std::getline(inputStream, line)) {
        if (line.find("LocalMaximum") != std::string::npos) {
            if (!contributionPointsAndScores.empty()) {
                std::sort(std::begin(contributionPointsAndScores),
                          std::end(contributionPointsAndScores),
                          [=](const std::pair<double, cv::Vec3i>& a,
                              const std::pair<double, cv::Vec3i>& b) { return a.first > b.first; });
                std::vector<cv::Vec3i> contributionPoints(contributionPointsAndScores.size() *
                                                          rate);
                for (auto i = 0; i < contributionPoints.size(); ++i) {
                    contributionPoints.at(i) = contributionPointsAndScores.at(i).second;
                }
                contributionPointsOfActionPosition.push_back(contributionPoints);
                contributionPointsAndScores.clear();
            }

            boost::char_separator<char> separator(",");
            boost::tokenizer<boost::char_separator<char>> tokenizer(line, separator);
            std::vector<std::string> tokens;
            std::copy(std::begin(tokenizer), std::end(tokenizer), std::back_inserter(tokens));

            cv::Vec3f actionPosition(std::stod(tokens.at(1)), std::stod(tokens.at(2)),
                                     std::stod(tokens.at(3)));
            actionPositions.emplace_back(std::stod(tokens.at(4)), actionPosition);
        } else if (!line.empty()) {
            boost::char_separator<char> separator(",");
            boost::tokenizer<boost::char_separator<char>> tokenizer(line, separator);
            std::vector<std::string> tokens;
            std::copy(std::begin(tokenizer), std::end(tokenizer), std::back_inserter(tokens));

            auto frame = std::stoi(tokens.at(0));
            auto contributionScore = std::stod(tokens.at(1));
            auto x = std::stoi(tokens.at(2));
            auto y = std::stoi(tokens.at(3));

            cv::Vec3i point(frame, y, x);
            contributionPointsAndScores.emplace_back(contributionScore, point);
        }
    }

    if (!contributionPointsAndScores.empty()) {
        std::sort(std::begin(contributionPointsAndScores), std::end(contributionPointsAndScores),
                  [=](const std::pair<double, cv::Vec3i>& a,
                      const std::pair<double, cv::Vec3i>& b) { return a.first > b.first; });
        std::vector<cv::Vec3i> contributionPoints(contributionPointsAndScores.size() * rate);
        for (auto i = 0; i < contributionPoints.size(); ++i) {
            contributionPoints.at(i) = contributionPointsAndScores.at(i).second;
        }
        contributionPointsOfActionPosition.push_back(contributionPoints);
        contributionPointsAndScores.clear();
    }
}
}
}


text:
#include <iostream>
#include "node.hpp"
#include "expression.hpp"
#include "statement.hpp"
#include "type.hpp"
#include "monotype.hpp"
#include "repr_printer.hpp"
#include "type_printer.hpp"
#include "py_printer.hpp"
#include "compiler.hpp"
#include "cuda_printer.hpp"
#include <boost/variant.hpp>

using namespace backend;
using std::shared_ptr;
using std::make_shared;
using std::vector;

int main(void)
{
  // types
  shared_ptr<monotype_t> Int32_t = int32_mt;
  shared_ptr<monotype_t> vecInt32_t(new sequence_t(Int32_t));

  // make op_add
  shared_ptr<tuple_t> int_tuple = make_shared<tuple_t>(vector<shared_ptr<type_t> >{Int32_t, Int32_t});
  shared_ptr<monotype_t> binop_t = make_shared<fn_t>(int_tuple, Int32_t);
  shared_ptr<name> op_add_scalar(new name("op_add", binop_t));

  // make map2
  shared_ptr<tuple_t> intvec_tuple = make_shared<tuple_t>(vector<shared_ptr<type_t> >{binop_t, vecInt32_t, vecInt32_t});
  shared_ptr<monotype_t> vecop_t = make_shared<fn_t>(intvec_tuple, vecInt32_t);
  shared_ptr<name> op_add_vector(new name("map2", vecop_t));

  // a, b
  shared_ptr<name> a(new name("a", vecInt32_t));
  shared_ptr<name> b(new name("b", vecInt32_t));

  // addproc(a,b)
  //   result = map2(op_add, a, b)
  //   return result
  shared_ptr<tuple> args(new tuple(vector<shared_ptr<expression> >{op_add_scalar, a, b}));
  shared_ptr<name> result(new name("result", vecInt32_t));
  shared_ptr<bind> res =
    make_shared<bind>(result,
                      make_shared<apply>(op_add_vector, args));
  shared_ptr<ret> addret(new ret(result));
  shared_ptr<name> addprocname(new name("addproc", vecop_t));
  shared_ptr<suite> funcbody(new suite(vector<shared_ptr<statement> >{res, addret}));
  shared_ptr<tuple> funcargs(new tuple(vector<shared_ptr<expression> >{a, b}));
  shared_ptr<procedure> addproc(new procedure(addprocname, funcargs, funcbody, vecop_t));

  // the whole program
  shared_ptr<suite> program(new suite(vector<shared_ptr<statement> >{addproc}));

  // print the representation
  std::cout << *program << std::endl;

  // compile
  std::string entry("addproc");
  compiler comp(entry);
  shared_ptr<suite> functorized = comp(*program);

  // print the representation
  py_printer pp(std::cout);
  pp(*program); std::cout << "\n";

  // cuda printer
  std::ostringstream os;
  backend::cuda_printer p(entry, comp.reg(), os);
  p(*functorized);
  std::cout << os.str() << "\n";

  return 0;
}

ext: cpp

max_stars_repo_name: bryancatanzaro/copperhead-compiler

max_issues_repo_name: bryancatanzaro/copperhead-compiler

max_forks_repo_name: bryancatanzaro/copperhead-compiler


text:
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8
// test_variant.cpp
// test of non-intrusive serialization of variant types
//
// copyright (c) 2005
// troy d. straszheim <troy@resophonic.com>
// http://www.resophonic.com
//
// Use, modification and distribution is subject to the Boost Software
// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org for updates, documentation, and revision history.
//
// thanks to Robert Ramey and Peter Dimov.
//

#include <boost/config.hpp>
#include <boost/math/special_functions/next.hpp>
#include <cstddef> // NULL
#include <cstdio>  // remove
#include <fstream>
#if defined(BOOST_NO_STDC_NAMESPACE)
namespace std {
using ::remove;
}
#endif

#include <boost/mpl/eval_if.hpp>
#include <boost/mpl/identity.hpp>
#include <boost/serialization/throw_exception.hpp>
#include <boost/type_traits/is_same.hpp>

#if defined(_MSC_VER) && (_MSC_VER <= 1020)
#pragma warning(disable : 4786) // too long name, harmless warning
#endif

#include "A.hpp"
#include "A.ipp"
#include "io_fixture.hpp"
#include <boost/archive/archive_exception.hpp>
#include <boost/serialization/nvp.hpp>
#include <boost/serialization/variant.hpp>
#include <boost/test/unit_test.hpp>

class are_equal : public boost::static_visitor<bool>
{
  public:
    // note extra rigamorole for compilers which don't support
    // partial function template ordering - specfically msvc 6.x
    struct same
    {
        template <class T, class U> static bool invoke(const T& t, const U& u)
        {
            return t == u;
        }
    };

    struct not_same
    {
        template <class T, class U> static bool invoke(const T&, const U&)
        {
            return false;
        }
    };

    template <class T, class U> bool operator()(const T& t, const U& u) const
    {
        typedef typename boost::mpl::eval_if<
            boost::is_same<T, U>, boost::mpl::identity<same>,
            boost::mpl::identity<not_same>>::type type;
        return type::invoke(t, u);
    }

    bool operator()(const float& lhs, const float& rhs) const
    {
        // FIXME!!!
        return std::abs(boost::math::float_distance(lhs, rhs)) < 8;
    }
    bool operator()(const double& lhs, const double& rhs) const
    {
        // FIXME!!!
        return std::abs(boost::math::float_distance(lhs, rhs)) < 8;
    }
};

BOOST_FIXTURE_TEST_CASE(boost_variant_1, io_fixture)
{
    boost::variant<bool, int, float, double, A, std::string> v, v1;
    v = false;
    {
        output() << BOOST_SERIALIZATION_NVP(v);
    }
    {
        input() >> boost::serialization::make_nvp("v", v1);
    }
    BOOST_CHECK(boost::apply_visitor(are_equal(), v, v1));
}

BOOST_FIXTURE_TEST_CASE(boost_variant_2, io_fixture)
{
    boost::variant<bool, int, float, double, A, std::string> v, v1;
    v = 1;
    {
        output() << BOOST_SERIALIZATION_NVP(v);
    }
    {
        input() >> boost::serialization::make_nvp("v", v1);
    }
    BOOST_CHECK(boost::apply_visitor(are_equal(), v, v1));
}

BOOST_FIXTURE_TEST_CASE(boost_variant_3, io_fixture)
{
    boost::variant<bool, int, float, double, A, std::string> v, v1;
    v = 2.3f;
    {
        output() << BOOST_SERIALIZATION_NVP(v);
    }
    {
        input() >> boost::serialization::make_nvp("v", v1);
    }
    BOOST_CHECK(boost::apply_visitor(are_equal(), v, v1));
}

BOOST_FIXTURE_TEST_CASE(boost_variant_4, io_fixture)
{
    boost::variant<bool, int, float, double, A, std::string> v, v1;
    v = 6.4;
    {
        output() << BOOST_SERIALIZATION_NVP(v);
    }
    {
        input() >> boost::serialization::make_nvp("v", v1);
    }
    BOOST_CHECK(boost::apply_visitor(are_equal(), v, v1));
}

BOOST_FIXTURE_TEST_CASE(boost_variant_5, io_fixture)
{
    boost::variant<bool, int, float, double, A, std::string> v, v1;
    v = std::string("we can't stop here, this is Bat Country");
    {
        output() << BOOST_SERIALIZATION_NVP(v);
    }
    {
        input() >> boost::serialization::make_nvp("v", v1);
    }
    BOOST_CHECK(boost::apply_visitor(are_equal(), v, v1));
}

BOOST_FIXTURE_TEST_CASE(boost_variant_6, io_fixture)
{
    boost::variant<bool, int, float, double, A, std::string> v, v1;
    v = A();
    {
        output() << BOOST_SERIALIZATION_NVP(v);
    }
    {
        input() >> boost::serialization::make_nvp("v", v1);
    }
    BOOST_CHECK(boost::apply_visitor(are_equal(), v, v1));
}

BOOST_FIXTURE_TEST_CASE(boost_variant_7, io_fixture)
{
// Compiling this test invokes an ICE on msvc 6
// So, we'll just to skip it for this compiler
#if defined(_MSC_VER) && (_MSC_VER <= 1020)
    bool exception_invoked = false;
    boost::variant<bool, float, int, std::string> v;
    boost::variant<bool, float, int> v1; // note we don't have std::string
    v = std::string("adrenochrome");
    {
        output() << BOOST_SERIALIZATION_NVP(v);
    }
    BOOST_TRY { input() >> boost::serialization::make_nvp("v", v1); }
    BOOST_CATCH(boost::archive::archive_exception e)
    {
        BOOST_CHECK(boost::archive::archive_exception::unsupported_version ==
                    e.code);
        exception_invoked = true;
    }
    BOOST_CHECK(exception_invoked);
#endif
}

// EOF

max_stars_repo_name: rwols/yaml-archive

max_issues_repo_name: rwols/yaml-archive

max_forks_repo_name: rwols/yaml-archive


text:
/* CirKit: A circuit toolkit
 * Copyright (C) 2009-2015  University of Bremen
 * Copyright (C) 2015-2017  EPFL
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following
 * conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 */

/**
 * @file write_blif.hpp
 *
 * @brief Writes a circuit to a BLIF file
 *
 * @author Mathias Soeken
 * @since  1.0
 */

#ifndef WRITE_BLIF_HPP
#define WRITE_BLIF_HPP

#include <iostream>
#include <map>
#include <vector>

#include <boost/optional.hpp>

namespace cirkit
{

  class circuit;
  class gate;

  /**
   * @brief Settings for write_blif
   *
   * @since  1.0
   */
  struct write_blif_settings
  {
    /**
     * @brief Stores truth tables
     *
     * The key is the index of the respective target line.
     * The value is a map itself, which maps input monoms
     * to output values for that target.
     *
     * @since  1.1.1
     */
    using truth_table_map = std::map<unsigned, std::map<std::vector<boost::optional<bool> >, bool> >;

    /**
     * @brief Prefix for the auxiliary variables which are created by the algorithm
     *
     * Default value is \b tmp
     *
     * @since  1.0
     */
    std::string tmp_signal_name = "tmp";

    /**
     * @brief Sets if output should comply to BlifMV
     *
     * In BlifMV spaces are inserted between the elements
     * of the input cubes.
     *
     * Default value is \b false
     *
     * @since  1.2
     */
    bool blif_mv = false;

    /**
     * @brief Output prefix for output signals
     *
     * @since 2.0
     */
    std::string output_prefix;

    /**
     * @brief Sets an state prefix for output signals
     *
     * Since states have both the same input and output name
     * this prefix is prepended to the respective output names.
     *
     * Default value is \b out_
     *
     * @since  1.3
     */
    std::string state_prefix = "out_";

    /**
     * @brief Sets if constant signals should keep their name
     *
     * Keeps constant names, but only if they are unique.
     *
     * Default value is \b false
     *
     * @since  1.3
     */
    bool keep_constant_names = false;

    /**
     * @brief Operator for transforming the gates into BLIF code
     *
     * By convention the first input signals are for the target lines and then the control lines.
     * The number of output signals is the number of target lines.
     * Only the cubes have to be printed, not the \em .names declaration.
     *
     * This operator has to be overridden when new gate types should be supported.
     *
     * The signature of this operator changed in RevKit version 1.1.1
     *
     * @param g The current g to be transformed
     * @param map Truth table map to be filled with cubes (check the source code for examples) (since 1.1.1)
     *
     * @since  1.0
     */
    virtual void operator()( const gate& g, truth_table_map& map ) const;

  };

  /**
   * @brief Writes a circuit to a BLIF file
   *
   * This function writes the circuit to a BLIF file.
   * Therefore, it is required that the circuit has names for all its inputs and outputs.
   *
   * @param circ Circuit
   * @param os Output stream where to write the result to. Default is \b STDOUT.
   * @param settings Settings
   *
   * @since  1.0
   */
  void write_blif( const circuit& circ, std::ostream& os = std::cout, const write_blif_settings& settings = write_blif_settings() );

}

#endif /* WRITE_BLIF_HPP */

// Local Variables:
// c-basic-offset: 2
// eval: (c-set-offset 'substatement-open 0)
// eval: (c-set-offset 'innamespace 0)
// End:

ext: hpp

max_stars_repo_name: eletesta/cirkit

max_issues_repo_name: eletesta/cirkit

max_forks_repo_name: eletesta/cirkit


text:
//
// Copyright (c) 2016-2017 Vinnie Falco (vinnie dot falco at gmail dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// Official repository: https://github.com/boostorg/beast
//

#ifndef BOOST_BEAST_DETAIL_INTEGER_SEQUENCE_HPP
#define BOOST_BEAST_DETAIL_INTEGER_SEQUENCE_HPP

#include <boost/config.hpp>
#include <cstddef>
#include <type_traits>
#include <utility>

namespace boost {
namespace beast {
namespace detail {

template<class T, T... Ints>
struct integer_sequence
{
    using value_type = T;
    BOOST_STATIC_ASSERT(std::is_integral<T>::value);

    static std::size_t constexpr static_size = sizeof...(Ints);

    static std::size_t constexpr size()
    {
        return sizeof...(Ints);
    }
};

template<std::size_t... Ints>
using index_sequence = integer_sequence<std::size_t, Ints...>;

// This workaround is needed for broken sizeof...
template<class... Args>
struct sizeof_workaround
{
    static std::size_t constexpr size = sizeof... (Args);
};

#ifdef BOOST_MSVC

// This implementation compiles on real MSVC and clang but not gcc

template<class T, unsigned long long N, class Seq>
struct make_integer_sequence_unchecked;

template<class T, unsigned long long N, unsigned long long ...Indices>
struct make_integer_sequence_unchecked<
    T, N, integer_sequence<T, Indices...>>
{
    using type = typename make_integer_sequence_unchecked<
        T, N-1, integer_sequence<T, N-1, Indices...>>::type;
};

template<class T, unsigned long long ...Indices>
struct make_integer_sequence_unchecked<
    T, 0, integer_sequence<T, Indices...>>
{
    using type = integer_sequence<T, Indices...>;
};

template<class T, T N>
struct make_integer_sequence_checked
{
    BOOST_STATIC_ASSERT(std::is_integral<T>::value);
    BOOST_STATIC_ASSERT(N >= 0);

    using type = typename make_integer_sequence_unchecked<
        T, N, integer_sequence<T>>::type;
};

template<class T, T N>
using make_integer_sequence =
    typename make_integer_sequence_checked<T, N>::type;

template<std::size_t N>
using make_index_sequence = make_integer_sequence<std::size_t, N>;

template<class... Args>
using index_sequence_for =
    make_index_sequence<sizeof_workaround<Args...>::size>;

#else

// This implementation compiles on gcc but not MSVC

template<std::size_t... Ints>
struct index_tuple
{
    using next = index_tuple<Ints..., sizeof... (Ints)>;

};

template<std::size_t N>
struct build_index_tuple
{
    using type = typename build_index_tuple<N-1>::type::next;
};

template<>
struct build_index_tuple<0>
{
    using type = index_tuple<>;
};

template<class T, T N,
    class Seq = typename build_index_tuple<N>::type
>
struct integer_sequence_helper;

template<class T, T N, std::size_t... Ints>
struct integer_sequence_helper<T, N, index_tuple<Ints...>>
{
    BOOST_STATIC_ASSERT(std::is_integral<T>::value);
    BOOST_STATIC_ASSERT(N >= 0);

    using type = integer_sequence<T, static_cast<T> (Ints)...>;
};

template<class T, T N>
using make_integer_sequence =
    typename integer_sequence_helper<T, N>::type;

template<std::size_t N>
using make_index_sequence = make_integer_sequence<std::size_t, N>;

template<class... Args>
using index_sequence_for =
    make_index_sequence<sizeof_workaround<Args...>::size>;

#endif

} // detail
} // beast
} // boost

#endif


text:
#include <boost/python.hpp>

#include "OpenPGP/Hashes/Hash.h"

class HashWrapper : public boost::python::wrapper<Hash>, public Hash
{
    void update(const std::string & str)
    {
        this->get_override("update")(str);
    }

    std::string hexdigest()
    {
        return this->get_override("hexdigest")();
    }

    unsigned int blocksize() const
    {
        return this->get_override("blocksize")();
    }

    unsigned int digestsize() const
    {
        return this->get_override("digestsize")();
    }
};

void Hash_init()
{
boost::python::class_<HashWrapper, boost::noncopyable>("Hash")
    .def("digestsize", boost::python::pure_virtual(&Hash::digestsize))
    .def("blocksize", boost::python::pure_virtual(&Hash::blocksize))
    .def("digest", &Hash::digest)
    .def("hexdigest", boost::python::pure_virtual(&Hash::hexdigest))
    .def("update", boost::python::pure_virtual(&Hash::update))
    ;
}

max_stars_repo_name: mugwort-rc/pyOpenPGP

max_issues_repo_name: mugwort-rc/pyOpenPGP

max_forks_repo_name: mugwort-rc/pyOpenPGP


text:
#pragma once

#include <Eigen/Dense>
#include <QtWidgets>
#include <rrt/2dplane/GridStateSpace.hpp>
#include <rrt/BiRRT.hpp>

/**
 * This widget creates an RRT tree for searching a 2d space and draws it.
 * It has methods (slots) for stepping and resetting tree growth.
 * You can also draw and erase obstacles by clicking and dragging.
 */
class RRTWidget : public QWidget {
    Q_OBJECT

public:
    RRTWidget();

private slots:
    void slot_run();
    void run_step();
    void slot_stop();
    void slot_reset();
    void slot_clearObstacles();
    void slot_step();
    void slot_stepBig();
    void slot_setGoalBias(int bias);      //  bias is from 0 to 100
    void slot_setWaypointBias(int bias);  //  bias is from 0 to 100
    void slot_setASC(int checked);
    void slot_setStepSize(double step);

signals:
    void signal_stepped(int iterationCount);

protected:
    void paintEvent(QPaintEvent* p);
    void drawTree(QPainter& painter, const RRT::Tree<Eigen::Vector2f>& rrt,
                  const RRT::Node<Eigen::Vector2f>* solutionNode = NULL,
                  QColor treeColor = Qt::blue, QColor solutionColor = Qt::red);
    void drawTerminalState(QPainter& painter, const Eigen::Vector2f& pos,
                           const Eigen::Vector2f& vel, const QColor& color);

    QPointF pointFromNode(const RRT::Node<Eigen::Vector2f>* n);

    void step(int numTimes);

    void mousePressEvent(QMouseEvent* event);
    void mouseMoveEvent(QMouseEvent* event);
    void mouseReleaseEvent(QMouseEvent* event);

    static bool mouseInGrabbingRange(QMouseEvent* event,
                                     const Eigen::Vector2f& pt);

private:
    std::shared_ptr<RRT::GridStateSpace> _stateSpace;
    RRT::BiRRT<Eigen::Vector2f>* _biRRT;

    Eigen::Vector2f _startVel, _goalVel;

    //  if you click down on an obstacle, you enter erase mode
    //  if you click down where there's no obstacle, you enter draw mode
    bool _editingObstacles, _erasingObstacles;

    enum {
        DraggingNone = 0,
        DraggingStart,
        DraggingGoal,
        DraggingStartVel,
        DraggingGoalVel
    } _draggingItem;

    int _waypointCacheMaxSize;

    std::vector<Eigen::Vector2f> _previousSolution;

    QTimer* _runTimer;
};

max_stars_repo_name: zychaoqun/rrt

max_issues_repo_name: zychaoqun/rrt

max_forks_repo_name: zychaoqun/rrt


text:
//--------------------------------------------------------------------------
// Code generated by the SmartSoft MDSD Toolchain
// The SmartSoft Toolchain has been developed by:
//
// Service Robotics Research Center
// University of Applied Sciences Ulm
// Prittwitzstr. 10
// 89075 Ulm (Germany)
//
// Information about the SmartSoft MDSD Toolchain is available at:
// www.servicerobotik-ulm.de
//
// Please do not modify this file. It will be re-generated
// running the code generator.
//--------------------------------------------------------------------------
#include "CommNavigationObjects/CommGridMapCore.hh"

// serialization/deserialization operators
//#include "CommNavigationObjects/CommGridMapACE.hh"

// include the hash.idl containing the hash constant
#include "hash.hh"
#include <assert.h>
#include <cstring>
#include <iostream>

// SmartUtils used in from_xml method
#include "smartKnuthMorrisPratt.hh"

#ifdef ENABLE_HASH
	#include <boost/functional/hash.hpp>
#endif

namespace CommNavigationObjects
{
	const char* CommGridMapCore::getCompiledHash()
	{
		return CommNavigationObjectsIDL::REPO_HASH;
	}

	void CommGridMapCore::getAllHashValues(std::list<std::string> &hashes)
	{
		// get own hash value
		hashes.push_back(getCompiledHash());
		// get hash value(s) for CommBasicObjects::CommTimeStamp(idl_CommGridMap.time)
		CommBasicObjects::CommTimeStamp::getAllHashValues(hashes);
	}

	void CommGridMapCore::checkAllHashValues(std::list<std::string> &hashes)
	{
		// check own hash value
		if (strcmp(getCompiledHash(), hashes.front().c_str()) != 0)
		{
			std::cerr << "###################################################" << std::endl;
			std::cerr << "WARNING: HASHES OF COMMUNICATION OBJECTS MISSMATCH!" << std::endl;
			std::cerr << "CommGridMapCore hash" << std::endl;
			std::cerr << "Expected: " << getCompiledHash() << std::endl;
			std::cerr << "Received: " << hashes.front() << std::endl;
			std::cerr << "###################################################" << std::endl;
		}
		assert(strcmp(getCompiledHash(), hashes.front().c_str()) == 0);
		hashes.pop_front();

		// check hash value(s) for CommBasicObjects::CommTimeStamp(idl_CommGridMap.time)
		CommBasicObjects::CommTimeStamp::checkAllHashValues(hashes);
	}

	#ifdef ENABLE_HASH
	size_t CommGridMapCore::generateDataHash(const DATATYPE &data)
	{
		size_t seed = 0;

		boost::hash_combine(seed, data.id);
		boost::hash_combine(seed, data.is_valid);
		seed += CommBasicObjects::CommTimeStamp::generateDataHash(data.time);
		boost::hash_combine(seed, data.xOffsetMM);
		boost::hash_combine(seed, data.yOffsetMM);
		boost::hash_combine(seed, data.xOffsetCells);
		boost::hash_combine(seed, data.yOffsetCells);
		boost::hash_combine(seed, data.cellSizeMM);
		boost::hash_combine(seed, data.xSizeMM);
		boost::hash_combine(seed, data.ySizeMM);
		boost::hash_combine(seed, data.xSizeCells);
		boost::hash_combine(seed, data.ySizeCells);
		boost::hash_combine(seed, data.size);
		std::vector<ACE_CDR::Octet>::const_iterator data_cellIt;
		for(data_cellIt=data.cell.begin(); data_cellIt!=data.cell.end(); data_cellIt++) {
			boost::hash_combine(seed, *data_cellIt);
		}

		return seed;
	}
	#endif

	// default constructor
	CommGridMapCore::CommGridMapCore()
	:	idl_CommGridMap()
	{
		setId(0);
		setIs_valid(false);
		setTime(CommBasicObjects::CommTimeStamp());
		setXOffsetMM(0);
		setYOffsetMM(0);
		setXOffsetCells(0);
		setYOffsetCells(0);
		setCellSizeMM(0);
		setXSizeMM(0);
		setYSizeMM(0);
		setXSizeCells(0);
		setYSizeCells(0);
		setSize(0);
		setCell(std::vector<unsigned char>());
	}

	CommGridMapCore::CommGridMapCore(const DATATYPE &data)
	:	idl_CommGridMap(data)
	{  }

	CommGridMapCore::~CommGridMapCore()
	{  }

	void CommGridMapCore::to_ostream(std::ostream &os) const
	{
	  os << "CommGridMap(";
	  os << getId() << " ";
	  os << getIs_valid() << " ";
	  getTime().to_ostream(os);
	  os << getXOffsetMM() << " ";
	  os << getYOffsetMM() << " ";
	  os << getXOffsetCells() << " ";
	  os << getYOffsetCells() << " ";
	  os << getCellSizeMM() << " ";
	  os << getXSizeMM() << " ";
	  os << getYSizeMM() << " ";
	  os << getXSizeCells() << " ";
	  os << getYSizeCells() << " ";
	  os << getSize() << " ";
	  std::vector<unsigned char>::const_iterator cellIt;
	  std::vector<unsigned char> cellList = getCellCopy();
	  for(cellIt=cellList.begin(); cellIt!=cellList.end(); cellIt++) {
	  	os << *cellIt << " ";
	  }
	  os << ") ";
	}

	// convert to xml stream
	void CommGridMapCore::to_xml(std::ostream &os, const std::string &indent) const {
		size_t counter = 0;

		os << indent << "<id>" << getId() << "</id>";
		os << indent << "<is_valid>" << getIs_valid() << "</is_valid>";
		os << indent << "<time>";
		getTime().to_xml(os, indent);
		os << indent << "</time>";
		os << indent << "<xOffsetMM>" << getXOffsetMM() << "</xOffsetMM>";
		os << indent << "<yOffsetMM>" << getYOffsetMM() << "</yOffsetMM>";
		os << indent << "<xOffsetCells>" << getXOffsetCells() << "</xOffsetCells>";
		os << indent << "<yOffsetCells>" << getYOffsetCells() << "</yOffsetCells>";
		os << indent << "<cellSizeMM>" << getCellSizeMM() << "</cellSizeMM>";
		os << indent << "<xSizeMM>" << getXSizeMM() << "</xSizeMM>";
		os << indent << "<ySizeMM>" << getYSizeMM() << "</ySizeMM>";
		os << indent << "<xSizeCells>" << getXSizeCells() << "</xSizeCells>";
		os << indent << "<ySizeCells>" << getYSizeCells() << "</ySizeCells>";
		os << indent << "<size>" << getSize() << "</size>";
		std::vector<unsigned char>::const_iterator cellIt;
		std::vector<unsigned char> cellList = getCellCopy();
		counter = 0;
		os << indent << "<cellList n=\"" << cellList.size() << "\">";
		for(cellIt=cellList.begin(); cellIt!=cellList.end(); cellIt++) {
			os << indent << "<cell i=\"" << counter++ << "\">" << *cellIt << "</cell>";
		}
		os << indent << "</cellList>";
	}

	// restore from xml stream
	void CommGridMapCore::from_xml(std::istream &is) {
		size_t counter = 0;

		static const Smart::KnuthMorrisPratt kmp_id("<id>");
		static const Smart::KnuthMorrisPratt kmp_is_valid("<is_valid>");
		static const Smart::KnuthMorrisPratt kmp_time("<time>");
		static const Smart::KnuthMorrisPratt kmp_xOffsetMM("<xOffsetMM>");
		static const Smart::KnuthMorrisPratt kmp_yOffsetMM("<yOffsetMM>");
		static const Smart::KnuthMorrisPratt kmp_xOffsetCells("<xOffsetCells>");
		static const Smart::KnuthMorrisPratt kmp_yOffsetCells("<yOffsetCells>");
		static const Smart::KnuthMorrisPratt kmp_cellSizeMM("<cellSizeMM>");
		static const Smart::KnuthMorrisPratt kmp_xSizeMM("<xSizeMM>");
		static const Smart::KnuthMorrisPratt kmp_ySizeMM("<ySizeMM>");
		static const Smart::KnuthMorrisPratt kmp_xSizeCells("<xSizeCells>");
		static const Smart::KnuthMorrisPratt kmp_ySizeCells("<ySizeCells>");
		static const Smart::KnuthMorrisPratt kmp_size("<size>");
		static const Smart::KnuthMorrisPratt kmp_cellList("<cellList n=\"");
		static const Smart::KnuthMorrisPratt kmp_cell("\">");

		if(kmp_id.search(is)) {
			unsigned int idItem;
			is >> idItem;
			setId(idItem);
		}
		if(kmp_is_valid.search(is)) {
			bool is_validItem;
			is >> is_validItem;
			setIs_valid(is_validItem);
		}
		if(kmp_time.search(is)) {
			CommBasicObjects::CommTimeStamp timeItem;
			timeItem.from_xml(is);
			setTime(timeItem);
		}
		if(kmp_xOffsetMM.search(is)) {
			int xOffsetMMItem;
			is >> xOffsetMMItem;
			setXOffsetMM(xOffsetMMItem);
		}
		if(kmp_yOffsetMM.search(is)) {
			int yOffsetMMItem;
			is >> yOffsetMMItem;
			setYOffsetMM(yOffsetMMItem);
		}
		if(kmp_xOffsetCells.search(is)) {
			int xOffsetCellsItem;
			is >> xOffsetCellsItem;
			setXOffsetCells(xOffsetCellsItem);
		}
		if(kmp_yOffsetCells.search(is)) {
			int yOffsetCellsItem;
			is >> yOffsetCellsItem;
			setYOffsetCells(yOffsetCellsItem);
		}
		if(kmp_cellSizeMM.search(is)) {
			int cellSizeMMItem;
			is >> cellSizeMMItem;
			setCellSizeMM(cellSizeMMItem);
		}
		if(kmp_xSizeMM.search(is)) {
			unsigned int xSizeMMItem;
			is >> xSizeMMItem;
			setXSizeMM(xSizeMMItem);
		}
		if(kmp_ySizeMM.search(is)) {
			unsigned int ySizeMMItem;
			is >> ySizeMMItem;
			setYSizeMM(ySizeMMItem);
		}
		if(kmp_xSizeCells.search(is)) {
			unsigned int xSizeCellsItem;
			is >> xSizeCellsItem;
			setXSizeCells(xSizeCellsItem);
		}
		if(kmp_ySizeCells.search(is)) {
			unsigned int ySizeCellsItem;
			is >> ySizeCellsItem;
			setYSizeCells(ySizeCellsItem);
		}
		if(kmp_size.search(is)) {
			unsigned int sizeItem;
			is >> sizeItem;
			setSize(sizeItem);
		}
		if(kmp_cellList.search(is)) {
			size_t numberElements;
			is >> numberElements;
			unsigned char cellItem;
			std::vector<unsigned char> cellList;
			kmp_cell.search(is);
			for(counter=0; counter<numberElements; counter++) {
				if(kmp_cell.search(is)) {
					is >> cellItem;
					cellList.push_back(cellItem);
				}
			}
			setCell(cellList);
		}
	}

	/*
	void CommGridMapCore::get(ACE_Message_Block *&msg) const
	{
		// start with a default internal buffer size(will automatically grow if needed)
		ACE_OutputCDR cdr(ACE_DEFAULT_CDR_BUFSIZE);

		CommNavigationObjectsIDL::HashList hashes;
		getAllHashValues(hashes);
		cdr << static_cast<ACE_CDR::Long>(hashes.size());
		for(CommNavigationObjectsIDL::HashList::const_iterator it=hashes.begin(); it!=hashes.end(); it++)
		{
			cdr << ACE_CString(it->c_str());
		}

		// Here the actual serialization takes place using the OutputCDR serialization operator<<
		// (see CommGridMapACE.hh)
		cdr << idl_CommGridMap;

	#ifdef ENABLE_HASH
		ACE_CDR::ULong data_hash = generateDataHash(idl_CommGridMap);
		cdr << data_hash;
		// std::cout << "CommGridMapCore: current data hash: " << data_hash << std::endl;
	#endif

		// return a shallow copy of the serialized message
		// (no data is actually copied, only the internal reference counter is incremented)
		// in order to prevent memory leaks the caller of this get(msg) method must
		// manually free the memory by calling the release() method of the message block msg
		msg = cdr.begin()->duplicate();
	}

	void CommGridMapCore::set(const ACE_Message_Block *msg)
	{
		ACE_InputCDR cdr(msg);

		CommNavigationObjectsIDL::HashList hashes;
		ACE_CDR::Long hashes_size;
		cdr >> hashes_size;
		for(int i=0; i<hashes_size; ++i)
		{
			ACE_CString hash;
			cdr >> hash;
			hashes.push_back(hash.c_str());
		}
		checkAllHashValues(hashes);

		// Here the actual de-serialization takes place using the InputCDR serialization operator>>
		// (see CommGridMapACE.hh)
		cdr >> idl_CommGridMap;

	#ifdef ENABLE_HASH
		ACE_CDR::Long data_hash;
		cdr >> data_hash;
		ACE_CDR::Long own_hash = generateDataHash(idl_CommGridMap);
		assert(data_hash == own_hash);
		// std::cout << "CommGridMapCore: own data hash: " << own_hash << "; received data hash: " << data_hash << std::endl;
	#endif
	}
	*/
} /* namespace CommNavigationObjects */

ext: cc


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

#include <cstddef>
#include <boost/mpl/vector_c.hpp>
#include <nt2/extension/parameters.hpp>
#include <nt2/core/settings/meta/option.hpp>
#include <boost/preprocessor/repetition/enum.hpp>
#include <boost/preprocessor/repetition/enum_params.hpp>

////////////////////////////////////////////////////////////////////////////////
// Defines index options
////////////////////////////////////////////////////////////////////////////////
namespace nt2 { namespace options
{
  struct index_ { typedef void nt2_is_option_type; };
} }

////////////////////////////////////////////////////////////////////////////////
// Helper macros
////////////////////////////////////////////////////////////////////////////////
#define M0(z,n,t) ptrdiff_t BOOST_PP_CAT(I,BOOST_PP_INC(n)) = BOOST_PP_CAT(I,n)

////////////////////////////////////////////////////////////////////////////////
// index<I0,..,In> represents the base index over the Nth dimensions. By default
// index<I0,I1> is equivalent to index<I0,I1,I1,...,I1>.
// Indexes data are stored in a mpl::vector_c of proper size.
////////////////////////////////////////////////////////////////////////////////
namespace nt2
{
  template< std::ptrdiff_t I0 = 1
          , BOOST_PP_ENUM(BOOST_PP_DEC(NT2_MAX_DIMENSIONS),M0,~)
          >
  struct  index
        : BOOST_PP_CAT(BOOST_PP_CAT(boost::mpl::vector,NT2_MAX_DIMENSIONS),_c)
          <std::ptrdiff_t, BOOST_PP_ENUM_PARAMS(NT2_MAX_DIMENSIONS,I)>
  {};
}

////////////////////////////////////////////////////////////////////////////////
// Register index_ has a valid options::index_ type
////////////////////////////////////////////////////////////////////////////////
namespace nt2 { namespace meta
{
  template< BOOST_PP_ENUM_PARAMS(NT2_MAX_DIMENSIONS,std::ptrdiff_t I)
          , class Default
          >
  struct option < index<BOOST_PP_ENUM_PARAMS(NT2_MAX_DIMENSIONS,I)>
                , options::index_
                , Default
                , void
                >
  {
    typedef index<BOOST_PP_ENUM_PARAMS(NT2_MAX_DIMENSIONS,I)> type;
  };
} }

////////////////////////////////////////////////////////////////////////////////
// Defines some usual short-cut for C and Matlab base indexing
////////////////////////////////////////////////////////////////////////////////
namespace nt2
{
  typedef index<0> C_index_;
  typedef index<1> matlab_index_;
}

////////////////////////////////////////////////////////////////////////////////
// Macros clean-up
////////////////////////////////////////////////////////////////////////////////
#undef M0

#endif


text:
// Boost.Geometry (aka GGL, Generic Geometry Library)

// Copyright (c) 2014, Oracle and/or its affiliates.

// Contributed and/or modified by Menelaos Karavelas, on behalf of Oracle

// Licensed under the Boost Software License version 1.0.
// http://www.boost.org/users/license.html

#ifndef BOOST_GEOMETRY_STRATEGIES_DISTANCE_COMPARABLE_TO_REGULAR_HPP
#define BOOST_GEOMETRY_STRATEGIES_DISTANCE_COMPARABLE_TO_REGULAR_HPP

#include <boost/geometry/core/tags.hpp>
#include <boost/geometry/core/cs.hpp>
#include <boost/geometry/algorithms/not_implemented.hpp>

namespace boost { namespace geometry
{

namespace strategy { namespace distance
{

#ifndef DOXYGEN_NO_STRATEGY_SPECIALIZATIONS
namespace services
{

template
<
    typename ComparableStrategy,
    typename Strategy,
    typename Geometry1,
    typename Geometry2,
    typename CsTag1 = typename cs_tag<Geometry1>::type,
    typename CsTag2 = typename cs_tag<Geometry2>::type
>
struct comparable_to_regular
    : geometry::not_implemented<CsTag1, CsTag2>
{};

} // namespace services
#endif // DOXYGEN_NO_STRATEGY_SPECIALIZATIONS

}} // namespace strategy::distance

}} // namespace boost::geometry

#endif // BOOST_GEOMETRY_STRATEGIES_DISTANCE_COMPARABLE_TO_REGULAR_HPP

max_stars_repo_name: cooparation/caffe-android

max_issues_repo_name: cooparation/caffe-android

max_forks_repo_name: cooparation/caffe-android


text:
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
 * Copyright (c) 2011-2015  Regents of the University of California.
 *
 * This file is part of ndnSIM. See AUTHORS for complete list of ndnSIM authors and
 * contributors.
 *
 * ndnSIM 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.
 *
 * ndnSIM 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
 * ndnSIM, e.g., in COPYING.md file.  If not, see <http://www.gnu.org/licenses/>.
 **/

#ifndef TRIE_H_
#define TRIE_H_

/// @cond include_hidden

#include "ns3/ndnSIM/model/ndn-common.hpp"

#include "ns3/ptr.h"

#include <boost/intrusive/unordered_set.hpp>
#include <boost/intrusive/list.hpp>
#include <boost/intrusive/set.hpp>
#include <boost/functional/hash.hpp>
#include <boost/interprocess/smart_ptr/unique_ptr.hpp>
#include <tuple>
#include <boost/foreach.hpp>
#include <boost/mpl/if.hpp>

namespace ns3 {
namespace ndn {
namespace ndnSIM {

/////////////////////////////////////////////////////
// Allow customization for payload
//
template<typename Payload, typename BasePayload = Payload>
struct pointer_payload_traits {
  typedef Payload payload_type;  // general type of the payload
  typedef Payload* storage_type; // how the payload is actually stored
  typedef Payload* insert_type;  // what parameter is inserted

  typedef Payload* return_type;             // what is returned on access
  typedef const Payload* const_return_type; // what is returned on const access

  typedef BasePayload*
    base_type; // base type of the entry (when implementation details need to be hidden)
  typedef const BasePayload*
    const_base_type; // const base type of the entry (when implementation details need to be hidden)

  static Payload* empty_payload;
};

template<typename Payload, typename BasePayload>
Payload* pointer_payload_traits<Payload, BasePayload>::empty_payload = 0;

template<typename Payload, typename BasePayload = Payload>
struct smart_pointer_payload_traits {
  typedef Payload payload_type;
  typedef ns3::Ptr<Payload> storage_type;
  typedef ns3::Ptr<Payload> insert_type;

  typedef ns3::Ptr<Payload> return_type;
  typedef ns3::Ptr<const Payload> const_return_type;

  typedef ns3::Ptr<BasePayload> base_type;
  typedef ns3::Ptr<const BasePayload> const_base_type;

  static ns3::Ptr<Payload> empty_payload;
};

template<typename Payload, typename BasePayload>
ns3::Ptr<Payload> smart_pointer_payload_traits<Payload, BasePayload>::empty_payload = 0;

template<typename Payload, typename BasePayload = Payload>
struct non_pointer_traits {
  typedef Payload payload_type;
  typedef Payload storage_type;
  typedef const Payload& insert_type; // nothing to insert

  typedef Payload& return_type;
  typedef const Payload& const_return_type;

  typedef BasePayload& base_type;
  typedef const BasePayload& const_base_type;

  static Payload empty_payload;
};

template<typename Payload, typename BasePayload>
Payload non_pointer_traits<Payload, BasePayload>::empty_payload = Payload();

////////////////////////////////////////////////////
// forward declarations
//
template<typename FullKey, typename PayloadTraits, typename PolicyHook>
class trie;

template<typename FullKey, typename PayloadTraits, typename PolicyHook>
inline std::ostream&
operator<<(std::ostream& os, const trie<FullKey, PayloadTraits, PolicyHook>& trie_node);

template<typename FullKey, typename PayloadTraits, typename PolicyHook>
bool
operator==(const trie<FullKey, PayloadTraits, PolicyHook>& a,
           const trie<FullKey, PayloadTraits, PolicyHook>& b);

template<typename FullKey, typename PayloadTraits, typename PolicyHook>
std::size_t
hash_value(const trie<FullKey, PayloadTraits, PolicyHook>& trie_node);

///////////////////////////////////////////////////
// actual definition
//
template<class T, class NonConstT>
class trie_iterator;

template<class T>
class trie_point_iterator;

template<typename FullKey, typename PayloadTraits, typename PolicyHook>
class trie {
public:
  typedef typename FullKey::value_type Key;

  typedef trie* iterator;
  typedef const trie* const_iterator;

  typedef trie_iterator<trie, trie> recursive_iterator;
  typedef trie_iterator<const trie, trie> const_recursive_iterator;

  typedef trie_point_iterator<trie> point_iterator;
  typedef trie_point_iterator<const trie> const_point_iterator;

  typedef PayloadTraits payload_traits;

  inline trie(const Key& key, size_t bucketSize = 1, size_t bucketIncrement = 1)
    : key_(key)
    , initialBucketSize_(bucketSize)
    , bucketIncrement_(bucketIncrement)
    , bucketSize_(initialBucketSize_)
    , buckets_(new bucket_type[bucketSize_]) // cannot use normal pointer, because lifetime of
                                             // buckets should be larger than lifetime of the
                                             // container
    , children_(bucket_traits(buckets_.get(), bucketSize_))
    , payload_(PayloadTraits::empty_payload)
    , parent_(nullptr)
  {
  }

  inline ~trie()
  {
    payload_ = PayloadTraits::empty_payload; // necessary for smart pointers...
    children_.clear_and_dispose(trie_delete_disposer());
  }

  void
  clear()
  {
    children_.clear_and_dispose(trie_delete_disposer());
  }

  template<class Predicate>
  void
  clear_if(Predicate cond)
  {
    recursive_iterator trieNode(this);
    recursive_iterator end(0);

    while (trieNode != end) {
      if (cond(*trieNode)) {
        trieNode = recursive_iterator(trieNode->erase());
      }
      trieNode++;
    }
  }

  // actual entry
  friend bool operator==<>(const trie<FullKey, PayloadTraits, PolicyHook>& a,
                           const trie<FullKey, PayloadTraits, PolicyHook>& b);

  friend std::size_t
  hash_value<>(const trie<FullKey, PayloadTraits, PolicyHook>& trie_node);

  inline std::pair<iterator, bool>
  insert(const FullKey& key, typename PayloadTraits::insert_type payload)
  {
    trie* trieNode = this;

    BOOST_FOREACH (const Key& subkey, key) {
      typename unordered_set::iterator item = trieNode->children_.find(subkey);
      if (item == trieNode->children_.end()) {
        trie* newNode = new trie(subkey, initialBucketSize_, bucketIncrement_);
        // std::cout << "new " << newNode << "\n";
        newNode->parent_ = trieNode;

        if (trieNode->children_.size() >= trieNode->bucketSize_) {
          trieNode->bucketSize_ += trieNode->bucketIncrement_;
          trieNode->bucketIncrement_ *= 2; // increase bucketIncrement exponentially

          buckets_array newBuckets(new bucket_type[trieNode->bucketSize_]);
          trieNode->children_.rehash(bucket_traits(newBuckets.get(), trieNode->bucketSize_));
          trieNode->buckets_.swap(newBuckets);
        }

        std::pair<typename unordered_set::iterator, bool> ret =
          trieNode->children_.insert(*newNode);

        trieNode = &(*ret.first);
      }
      else
        trieNode = &(*item);
    }

    if (trieNode->payload_ == PayloadTraits::empty_payload) {
      trieNode->payload_ = payload;
      return std::make_pair(trieNode, true);
    }
    else
      return std::make_pair(trieNode, false);
  }

  /**
   * @brief Removes payload (if it exists) and if there are no children, prunes parents trie
   */
  inline iterator
  erase()
  {
    payload_ = PayloadTraits::empty_payload;
    return prune();
  }

  /**
   * @brief Do exactly as erase, but without erasing the payload
   */
  inline iterator
  prune()
  {
    if (payload_ == PayloadTraits::empty_payload && children_.size() == 0) {
      if (parent_ == 0)
        return this;

      trie* parent = parent_;
      parent->children_
        .erase_and_dispose(*this,
                           trie_delete_disposer()); // delete this; basically, committing a suicide

      return parent->prune();
    }
    return this;
  }

  /**
   * @brief Perform prune of the node, but without attempting to parent of the node
   */
  inline void
  prune_node()
  {
    if (payload_ == PayloadTraits::empty_payload && children_.size() == 0) {
      if (parent_ == 0)
        return;

      trie* parent = parent_;
      parent->children_
        .erase_and_dispose(*this,
                           trie_delete_disposer()); // delete this; basically, committing a suicide
    }
  }

  // inline std::tuple<const iterator, bool, const iterator>
  // find (const FullKey &key) const
  // {
  //   return const_cast<trie*> (this)->find (key);
  // }

  /**
   * @brief Perform the longest prefix match
   * @param key the key for which to perform the longest prefix match
   *
   * @return ->second is true if prefix in ->first is longer than key
   */
  inline std::tuple<iterator, bool, iterator>
  find(const FullKey& key)
  {
    trie* trieNode = this;
    iterator foundNode = (payload_ != PayloadTraits::empty_payload) ? this : 0;
    bool reachLast = true;

    BOOST_FOREACH (const Key& subkey, key) {
      typename unordered_set::iterator item = trieNode->children_.find(subkey);
      if (item == trieNode->children_.end()) {
        reachLast = false;
        break;
      }
      else {
        trieNode = &(*item);

        if (trieNode->payload_ != PayloadTraits::empty_payload)
          foundNode = trieNode;
      }
    }

    return std::make_tuple(foundNode, reachLast, trieNode);
  }

  /**
   * @brief Perform the longest prefix match satisfying preficate
   * @param key the key for which to perform the longest prefix match
   *
   * @return ->second is true if prefix in ->first is longer than key
   */
  template<class Predicate>
  inline std::tuple<iterator, bool, iterator>
  find_if(const FullKey& key, Predicate pred)
  {
    trie* trieNode = this;
    iterator foundNode = (payload_ != PayloadTraits::empty_payload) ? this : 0;
    bool reachLast = true;

    BOOST_FOREACH (const Key& subkey, key) {
      typename unordered_set::iterator item = trieNode->children_.find(subkey);
      if (item == trieNode->children_.end()) {
        reachLast = false;
        break;
      }
      else {
        trieNode = &(*item);

        if (trieNode->payload_ != PayloadTraits::empty_payload && pred(trieNode->payload_)) {
          foundNode = trieNode;
        }
      }
    }

    return std::make_tuple(foundNode, reachLast, trieNode);
  }

  /**
   * @brief Find next payload of the sub-trie
   * @returns end() or a valid iterator pointing to the trie leaf (order is not defined, enumeration
   * )
   */
  inline iterator
  find()
  {
    if (payload_ != PayloadTraits::empty_payload)
      return this;

    typedef trie<FullKey, PayloadTraits, PolicyHook> trie;
    for (typename trie::unordered_set::iterator subnode = children_.begin();
         subnode != children_.end(); subnode++)
    // BOOST_FOREACH (trie &subnode, children_)
    {
      iterator value = subnode->find();
      if (value != 0)
        return value;
    }

    return 0;
  }

  /**
   * @brief Find next payload of the sub-trie satisfying the predicate
   * @param pred predicate
   * @returns end() or a valid iterator pointing to the trie leaf (order is not defined, enumeration
   * )
   */
  template<class Predicate>
  inline const iterator
  find_if(Predicate pred)
  {
    if (payload_ != PayloadTraits::empty_payload && pred(payload_))
      return this;

    typedef trie<FullKey, PayloadTraits, PolicyHook> trie;
    for (typename trie::unordered_set::iterator subnode = children_.begin();
         subnode != children_.end(); subnode++)
    // BOOST_FOREACH (const trie &subnode, children_)
    {
      iterator value = subnode->find_if(pred);
      if (value != 0)
        return value;
    }

    return 0;
  }

  /**
   * @brief Find next payload of the sub-trie satisfying the predicate
   * @param pred predicate
   *
   * This version check predicate only for the next level children
   *
   * @returns end() or a valid iterator pointing to the trie leaf (order is not defined, enumeration
   *)
   */
  template<class Predicate>
  inline const iterator
  find_if_next_level(Predicate pred)
  {
    typedef trie<FullKey, PayloadTraits, PolicyHook> trie;
    for (typename trie::unordered_set::iterator subnode = children_.begin();
         subnode != children_.end(); subnode++) {
      if (pred(subnode->key())) {
        return subnode->find();
      }
    }

    return 0;
  }

  iterator
  end()
  {
    return 0;
  }

  const_iterator
  end() const
  {
    return 0;
  }

  typename PayloadTraits::const_return_type
  payload() const
  {
    return payload_;
  }

  typename PayloadTraits::return_type
  payload()
  {
    return payload_;
  }

  void
  set_payload(typename PayloadTraits::insert_type payload)
  {
    payload_ = payload;
  }

  Key
  key() const
  {
    return key_;
  }

  inline void
  PrintStat(std::ostream& os) const;

private:
  // The disposer object function
  struct trie_delete_disposer {
    void
    operator()(trie* delete_this)
    {
      delete delete_this;
    }
  };

  template<class D>
  struct array_disposer {
    void
    operator()(D* array)
    {
      delete[] array;
    }
  };

  friend std::ostream& operator<<<>(std::ostream& os, const trie& trie_node);

public:
  PolicyHook policy_hook_;

private:
  boost::intrusive::unordered_set_member_hook<> unordered_set_member_hook_;

  // necessary typedefs
  typedef trie self_type;
  typedef boost::intrusive::member_hook<trie, boost::intrusive::unordered_set_member_hook<>,
                                        &trie::unordered_set_member_hook_> member_hook;

  typedef boost::intrusive::unordered_set<trie, member_hook> unordered_set;
  typedef typename unordered_set::bucket_type bucket_type;
  typedef typename unordered_set::bucket_traits bucket_traits;

  template<class T, class NonConstT>
  friend class trie_iterator;

  template<class T>
  friend class trie_point_iterator;

  ////////////////////////////////////////////////
  // Actual data
  ////////////////////////////////////////////////

  Key key_; ///< name component

  size_t initialBucketSize_;
  size_t bucketIncrement_;

  size_t bucketSize_;
  typedef boost::interprocess::unique_ptr<bucket_type, array_disposer<bucket_type>> buckets_array;
  buckets_array buckets_;
  unordered_set children_;

  typename PayloadTraits::storage_type payload_;
  trie* parent_; // to make cleaning effective
};

template<typename FullKey, typename PayloadTraits, typename PolicyHook>
inline std::ostream&
operator<<(std::ostream& os, const trie<FullKey, PayloadTraits, PolicyHook>& trie_node)
{
  os << "# " << trie_node.key_ << ((trie_node.payload_ != PayloadTraits::empty_payload) ? "*" : "")
     << std::endl;
  typedef trie<FullKey, PayloadTraits, PolicyHook> trie;

  for (typename trie::unordered_set::const_iterator subnode = trie_node.children_.begin();
       subnode != trie_node.children_.end(); subnode++)
  // BOOST_FOREACH (const trie &subnode, trie_node.children_)
  {
    os << "\"" << &trie_node << "\""
       << " [label=\"" << trie_node.key_
       << ((trie_node.payload_ != PayloadTraits::empty_payload) ? "*" : "") << "\"]\n";
    os << "\"" << &(*subnode) << "\""
       << " [label=\"" << subnode->key_
       << ((subnode->payload_ != PayloadTraits::empty_payload) ? "*" : "") << "\"]"
                                                                              "\n";

    os << "\"" << &trie_node << "\""
       << " -> "
       << "\"" << &(*subnode) << "\""
       << "\n";
    os << *subnode;
  }

  return os;
}

template<typename FullKey, typename PayloadTraits, typename PolicyHook>
inline void
trie<FullKey, PayloadTraits, PolicyHook>::PrintStat(std::ostream& os) const
{
  os << "# " << key_ << ((payload_ != PayloadTraits::empty_payload) ? "*" : "") << ": "
     << children_.size() << " children" << std::endl;
  for (size_t bucket = 0, maxbucket = children_.bucket_count(); bucket < maxbucket; bucket++) {
    os << " " << children_.bucket_size(bucket);
  }
  os << "\n";

  typedef trie<FullKey, PayloadTraits, PolicyHook> trie;
  for (typename trie::unordered_set::const_iterator subnode = children_.begin();
       subnode != children_.end(); subnode++)
  // BOOST_FOREACH (const trie &subnode, children_)
  {
    subnode->PrintStat(os);
  }
}

template<typename FullKey, typename PayloadTraits, typename PolicyHook>
inline bool
operator==(const trie<FullKey, PayloadTraits, PolicyHook>& a,
           const trie<FullKey, PayloadTraits, PolicyHook>& b)
{
  return a.key_ == b.key_;
}

template<typename FullKey, typename PayloadTraits, typename PolicyHook>
inline std::size_t
hash_value(const trie<FullKey, PayloadTraits, PolicyHook>& trie_node)
{
  return boost::hash_value(trie_node.key_);
}

template<class Trie, class NonConstTrie> // hack for boost < 1.47
class trie_iterator {
public:
  trie_iterator()
    : trie_(0)
  {
  }
  trie_iterator(typename Trie::iterator item)
    : trie_(item)
  {
  }
  trie_iterator(Trie& item)
    : trie_(&item)
  {
  }

  Trie& operator*()
  {
    return *trie_;
  }
  const Trie& operator*() const
  {
    return *trie_;
  }
  Trie* operator->()
  {
    return trie_;
  }
  const Trie* operator->() const
  {
    return trie_;
  }
  bool
  operator==(trie_iterator<const Trie, NonConstTrie>& other) const
  {
    return (trie_ == other.trie_);
  }
  bool
  operator==(trie_iterator<Trie, NonConstTrie>& other)
  {
    return (trie_ == other.trie_);
  }
  bool
  operator!=(trie_iterator<const Trie, NonConstTrie>& other) const
  {
    return !(*this == other);
  }
  bool
  operator!=(trie_iterator<Trie, NonConstTrie>& other)
  {
    return !(*this == other);
  }

  trie_iterator<Trie, NonConstTrie>&
  operator++(int)
  {
    if (trie_->children_.size() > 0)
      trie_ = &(*trie_->children_.begin());
    else
      trie_ = goUp();
    return *this;
  }

  trie_iterator<Trie, NonConstTrie>&
  operator++()
  {
    (*this)++;
    return *this;
  }

private:
  typedef typename boost::mpl::if_<boost::is_same<Trie, NonConstTrie>,
                                   typename Trie::unordered_set::iterator,
                                   typename Trie::unordered_set::const_iterator>::type set_iterator;

  Trie*
  goUp()
  {
    if (trie_->parent_ != 0) {
      // typename Trie::unordered_set::iterator item =
      set_iterator item = const_cast<NonConstTrie*>(trie_)
                            ->parent_->children_.iterator_to(const_cast<NonConstTrie&>(*trie_));
      item++;
      if (item != trie_->parent_->children_.end()) {
        return &(*item);
      }
      else {
        trie_ = trie_->parent_;
        return goUp();
      }
    }
    else
      return 0;
  }

private:
  Trie* trie_;
};

template<class Trie>
class trie_point_iterator {
private:
  typedef typename boost::mpl::if_<boost::is_same<Trie, const Trie>,
                                   typename Trie::unordered_set::const_iterator,
                                   typename Trie::unordered_set::iterator>::type set_iterator;

public:
  trie_point_iterator()
    : trie_(0)
  {
  }
  trie_point_iterator(typename Trie::iterator item)
    : trie_(item)
  {
  }
  trie_point_iterator(Trie& item)
  {
    if (item.children_.size() != 0)
      trie_ = &*item.children_.begin();
    else
      trie_ = 0;
  }

  Trie& operator*()
  {
    return *trie_;
  }
  const Trie& operator*() const
  {
    return *trie_;
  }
  Trie* operator->()
  {
    return trie_;
  }
  const Trie* operator->() const
  {
    return trie_;
  }
  bool
  operator==(trie_point_iterator<const Trie>& other) const
  {
    return (trie_ == other.trie_);
  }
  bool
  operator==(trie_point_iterator<Trie>& other)
  {
    return (trie_ == other.trie_);
  }
  bool
  operator!=(trie_point_iterator<const Trie>& other) const
  {
    return !(*this == other);
  }
  bool
  operator!=(trie_point_iterator<Trie>& other)
  {
    return !(*this == other);
  }

  trie_point_iterator<Trie>&
  operator++(int)
  {
    if (trie_->parent_ != 0) {
      set_iterator item = trie_->parent_->children_.iterator_to(*trie_);
      item++;
      if (item == trie_->parent_->children_.end())
        trie_ = 0;
      else
        trie_ = &*item;
    }
    else {
      trie_ = 0;
    }
    return *this;
  }

  trie_point_iterator<Trie>&
  operator++()
  {
    (*this)++;
    return *this;
  }

private:
  Trie* trie_;
};

} // ndnSIM
} // ndn
} // ns3

/// @endcond

#endif // TRIE_H_

max_stars_repo_name: seanbraley/ndn-split-caching

max_issues_repo_name: seanbraley/ndn-split-caching

max_forks_repo_name: seanbraley/ndn-split-caching


text:
#ifndef WAITGROUP_H
#define WAITGROUP_H

#include <boost/noncopyable.hpp>

#include "base/Condition.hpp"

namespace tsdb {
namespace base {

class WaitGroup : boost::noncopyable {
 private:
  mutable MutexLock mutex_;
  Condition condition_;
  int count_;

 public:
  explicit WaitGroup() : mutex_(), condition_(mutex_), count_(0) {}

  void add(int i) {
    MutexLockGuard lock(mutex_);
    count_ += i;
  }

  void done() {
    MutexLockGuard lock(mutex_);
    --count_;
    if (count_ <= 0) condition_.notifyAll();
  }

  void wait() {
    MutexLockGuard lock(mutex_);
    if (count_ > 0) condition_.wait();
  }
};

}  // namespace base
}  // namespace tsdb

#endif

max_stars_repo_name: naivewong/timeunion

max_issues_repo_name: naivewong/timeunion

max_forks_repo_name: naivewong/timeunion


text:
// Copyright 2015-2019 Carnegie Mellon University.  See LICENSE file for terms.

#ifndef Config_H
#define Config_H

#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wshadow"
#include <yaml-cpp/yaml.h>
#pragma GCC diagnostic pop
#include <fstream>
#include <boost/algorithm/string.hpp>
#include <boost/optional.hpp>

// Default config path separator
#define CONFIG_PATH_SEPERATOR '.'

namespace pharos {
namespace detail {

/// Iterator template for ConfigNode elements.  This needs to be a template in order to handle
/// mutual dependency.  'Base' is included in the template so that Node::iterator or
/// Node::const_iterator can be adapted.  Currently, only the latter is being adapted.
template <typename Node, typename Base>
class ConfigNode_iterator :
    public boost::iterator_adaptor<ConfigNode_iterator<Node, Base>,
                                   Base, std::pair<Node, Node>,
                                   boost::use_default,
                                   std::pair<Node, Node> >
{
  using base_t = boost::iterator_adaptor<ConfigNode_iterator<Node, Base>,
                                         Base,
                                         std::pair<Node, Node>,
                                         boost::use_default,
                                         std::pair<Node, Node> >;
 public:
  ConfigNode_iterator(const ConfigNode_iterator<Node, Base> &i) : base_t(i) {}
  ConfigNode_iterator(const Node &parent, const Base &i) :
    base_t(i), parent_(parent) {}

  // Return the key/value pair, wrapped as ConfigNode objects
  std::pair<Node, Node> dereference() const {
    auto & node = this->base();
    if (parent_.IsSequence()) {
      Node key;
      Node value(*node);
      // the following shiould really have the sequence index as the second argument.
      // Currently that's hard to get.  Save it for a later version of yaml-cpp.
      // value.add_path(parent_, node->first);
      value.filemap_ = parent_.filemap_;
      return std::make_pair(key, value);
    } else {
      Node key(node->first);
      Node value(node->second);
      value.add_path(parent_, node->first);
      key.filemap_ = parent_.filemap_;
      value.filemap_ = parent_.filemap_;
      return std::make_pair(key, value);
    }
  }

 private:
  Node parent_;
};

} // namespace detail

/// An exception representing an invalid node value
class BadFileError : public std::runtime_error {
 public:
  BadFileError() : std::runtime_error("Cannot open file") {}
  BadFileError(const std::string &filename) : std::runtime_error(build_what(filename)) {}
 private:
  static std::string build_what(const std::string &filename);
};

class ConfigNode;

/// Exceptions from the ConfigNode module that can output information about a failed node's
/// path and source
class ConfigException : public std::runtime_error {
 public:
  ConfigException(const ConfigNode &node, const std::string & msg)
    : std::runtime_error(build_what(node, msg)) {}
 private:
  static std::string build_what(const ConfigNode &node, const std::string & msg);
};

/// An exception representing an invalid node value
class BadNodeError : public ConfigException {
 public:
  BadNodeError(const ConfigNode &node, const std::string &msg)
    : ConfigException(node, msg) {}
};

class ConfigNode : public YAML::Node {
 public:
  /// Define the iterator type, which will iterate over std::pair<ConfigNode,ConfigNode>
  /// elements
  using iterator = detail::ConfigNode_iterator<ConfigNode, Node::const_iterator>;

  /// Create an empty config
  ConfigNode() : filemap_(YAML::NodeType::Map) {}

  /// Copy constructor
  ConfigNode(ConfigNode const &) = default;

  /// Look up the value of the current ConfigNode's 'key' attribute.  If there is no attribute
  /// for 'key', a ConfigNode that is undefined (!IsDefined()) will be returned.  If a
  /// ConfigNode has no key named 'A', a construction of cfg["A"]["B"] will still work, and
  /// will return a ConfigNode that is undefined, and has a path of just "A".
  template <typename Key>
  ConfigNode operator[](const Key& key) const {
    ConfigNode c;
    if (IsScalar()) {
      c = new_node(YAML::Node());
    } else if (IsDefined()) {
      c = new_node(cnode(*this)[key]);
    } else {
      c = new_node(*this);
    }
    c.add_path(*this, key);
    return c;
  }

  /// Look up the given path in the ConfigNode.  If the seperator is '.', cfg.path_get("A.B.C")
  /// is equivalent to cfg["A"]["B"]["C"].
  virtual ConfigNode path_get(const std::string &path,
                              char sep = CONFIG_PATH_SEPERATOR) const;

  /// If 'value' is a scalar, this is a map, and the map contains the value, return the value
  /// in the map.  Otherwise, return 'value'.
  ConfigNode lookup(const ConfigNode &value) const;

  /// Replace this ConfigNode with the contents of 'rhs'
  ConfigNode& operator=(const ConfigNode& rhs);

  /// Return the value of this node as the given type.  If the conversion fails, the value will
  /// be boost::none.
  template <typename T>
  boost::optional<T> as() const {
    try {
      return Node::as<T>();
    } catch (const YAML::BadConversion &) {
      return boost::none;
    }
  }

  /// Return the value of this node as the given type.  Throw a BadNodeError exception if the
  /// conversion fails.
  template <typename T>
  const T expect(const char *msg = "Illegal conversion") const {
    try {
      return Node::as<T>();
    } catch (const YAML::BadConversion &) {
      throw BadNodeError(*this, msg);
    }
  }

  /// Return the value of this node as the given type.  Throw a BadNodeError exception if the
  /// conversion fails.
  template <typename T>
  const T expect(const std::string &msg) const {
    return as<T>(msg.c_str());
  }

  /// Return the value of this node as the given type.  Return 'fallback' if the conversion
  /// fails.
  template <typename T, typename S>
  const T as_fallback(const S& fallback) const {
    return Node::as<T, S>(fallback);
  }

  /// Return the path to this ConfigNode.  If this ConfigNode was returned by
  /// baseconfig["A"]["B"], where baseconfig was generated by ConfigNode() or
  /// ConfigNode::default_config(), the path to this config would be "A.B".
  std::string path(char sep = CONFIG_PATH_SEPERATOR) const {
    return path_->path(sep);
  }

  /// Return the source of this ConfigNode.  The source of a ConfigNode is the name that was
  /// passed to merge() or mergeFile().
  const std::string &source() const;

  /// Return an iterator over the node.  For maps and sequences this iterator will return
  /// values of the type std::pair<ConfigNode, ConfigNode>, where the first ConfigNode is the
  /// key, and the second is the value.  For sequences, the keys are integers, beginning with
  /// zero.
  iterator begin() const {
    return iterator(*this, Node::begin());
  }

  /// Return an end iterator
  iterator end() const {
    return iterator(*this, Node::end());
  }

  // Return as YAML::Node
  Node as_node() const {
    return *this;
  }

 protected:
  /// Construct an empty ConfigNode from a Node
  ConfigNode(const Node &o) : Node(o) {}

  // Our iterators need access to our private members
  friend class detail::ConfigNode_iterator<ConfigNode, Node::const_iterator>;

  // Stream operator needs access to our private base class
  friend std::ostream &operator<<(std::ostream &, const ConfigNode &);

  // An empty string that can be used as a default parameter
  static const std::string empty_string;

  /// Create a ConfigNode from a node with the same filemap as this one
  ConfigNode new_node(const Node &n) const {
    ConfigNode node(n);
    node.filemap_ = filemap_;
    return node;
  }

  /// Maintains a linked list of key values that led to this config
  struct Pathlist {
    std::string key;
    std::shared_ptr<const Pathlist> next;
    void path(std::ostream& s, char sep) const;
    std::string path(char sep) const;
  };
  std::shared_ptr<Pathlist> path_;

  /// Merge node 'b' into node 'a', returning 'a'.
  static
  Node merge_nodes(Node a, Node b);

  Node merge_nodes(Node a) {
    return merge_nodes(*this, a);
  }

  /// Return a constant reference to n (used to guarantee calling operator[] const even on
  /// non-const nodes)
  static
  const Node &cnode(const Node &n) {
    return n;
  }

  /// Add an element to this ConfigNode's path
  template<typename Key>
  void add_path(const ConfigNode &base, const Key &key) {
    if (!path_) {
      path_.reset(new Pathlist());
    }
    path_->next = base.path_;
    std::ostringstream s;
    s << key;
    path_->key = s.str();
  }

  /// A map of nodes to source identifiers
  Node filemap_;

  /// Update the filemap_ from node 'item', adding all elements from 'item' not currently in
  /// filemap_ with the value 'src'.
  void update_map(const Node &src, const Node &item);

  /// Update the filemap_ from node 'item', adding all elements from 'item' not currently in
  /// filemap_ with the value 'src'.
  void update_map(const std::string &src, const Node &item) {
    update_map(Node(src), item);
  }
};

inline std::ostream &operator<<(std::ostream &stream, const ConfigNode &conf) {
  return stream << static_cast<const YAML::Node &>(conf);
}

class Config : public ConfigNode {
 public:
  /// Default constructor
  Config() {}

  /// Primary constructor
  Config(const std::string &_appname) : appname(_appname) {}

  /// Create a config with pharos's default values
  static Config default_config(const std::string &appname);

  /// Load a config starting with default_config, merging from file at default_location,
  /// overriden by a file name in the env_override environment variable, followed by the file
  /// named home_config in the $HOME directory.  Any of these arguments are nullable.
  static Config load_config(
    const std::string &appname,
    const char *default_location,
    const char *env_override,
    const char *home_config);

  Config
  include(const ConfigNode &config,
          const std::string &name = empty_string) const
  {
    YAML::Node m = merge_nodes(*this, config);
    Config r = new_node(m);
    r.update_map(name, r);
    return r;
  }

  /// Return a Config representing the merged state of this Config and he YAML representation
  /// identified by source with a given name.  Source may be a std::string, a const char *, or
  /// a std::istream &.  In all three cases, the contents are the YAML representation, not the
  /// name of a file.
  template <typename Source>
  Config
  include(Source &src, const std::string &name = empty_string) const {
    YAML::Node n = YAML::Load(src);
    YAML::Node m = merge_nodes(*this, n);
    Config r = new_node(m);
    r.update_map(name, r);
    return r;
  }

  /// Return a Config representing the merged state of this Config and a YAML representation
  /// read from the given filename.  If 'name' is left empty, 'filename' will be used as the
  /// source's name.
  Config
  include(const std::string &filename,
          const std::string &name = empty_string) const
  {
    std::ifstream s(filename.c_str());
    if (!s) {
      throw BadFileError(filename);
    }
    return include<std::ifstream&>(s, name.empty() ? filename : name);
  }

  /// Change this Config to represent the merged state of this Config and he YAML
  /// representation identified by source with a given name.  Source may be a std::string, a
  /// const char *, or a std::istream &.  In all three cases, the contents are the YAML
  /// representation, not the name of a file.
  template <typename Source>
  Config &
  merge(Source &src, const std::string &name = empty_string) {
    *static_cast<ConfigNode *>(this) = include(src, name);
    return *this;
  }

  /// Change this Config to represent the merged state of this Config and a YAML representation
  /// read from the given filename.  If 'name' is left empty, 'filename' will be used as the
  /// source's name.
  Config &
  mergeFile(const std::string &filename,
            const std::string &name = empty_string);

  /// Look up the value of the current ConfigNode's 'key' attribute.  The attribute will first
  /// be looked up in the "application.<appname>" path.  Otherwise it will be looked for from
  /// the root of the config.  If there is no attribute for 'key', a ConfigNode that is
  /// undefined (!IsDefined()) will be returned.  If a ConfigNode has no key named 'A', a
  /// construction of cfg["A"]["B"] will still work, and will return a ConfigNode that is
  /// undefined, and has a path of just "A".
  template <typename Key>
  ConfigNode operator[](const Key& key) const {
    ConfigNode appnode = (*static_cast<const ConfigNode *>(const_cast<const Config *>(this)))
                         ["application"][appname];
    if (appnode) {
      ConfigNode val = appnode[key];
      if (val) {
        return val;
      }
    }
    return ConfigNode::operator[](key);
  }

  /// Look up the given path in the ConfigNode.  If the seperator is '.', cfg.path_get("A.B.C")
  /// is equivalent to cfg["A"]["B"]["C"].
  virtual ConfigNode path_get(const std::string &p,
                              char sep = CONFIG_PATH_SEPERATOR) const
  {
    ConfigNode appnode = (*static_cast<const ConfigNode *>(const_cast<const Config *>(this)))
                         ["application"][appname];
    if (appnode) {
      ConfigNode val = appnode.path_get(p, sep);
      if (val) {
        return val;
      }
    }
    return ConfigNode::path_get(p, sep);
  }

 private:
  /// Construct an empty Config from a Node
  Config(const YAML::Node &o) : ConfigNode(o) {}

  /// Create a ConfigNode from a node with the same filemap as this one
  ConfigNode
  new_node(const YAML::Node &n) const {
    Config node(n);
    node.filemap_ = filemap_;
    return node;
  }

  std::string appname;
};

} // namespace pharos

#endif // Config_H

/* Local Variables:   */
/* mode: c++          */
/* fill-column:    95 */
/* comment-column: 0  */
/* End:               */

max_stars_repo_name: tjschweizer/pharos

max_issues_repo_name: tjschweizer/pharos

max_forks_repo_name: tjschweizer/pharos


text:
#define BOOST_TEST_MODULE My Test
#include <boost/test/included/unit_test.hpp>
#include "../src/component1/myComp1.hpp"

BOOST_AUTO_TEST_CASE(first_test) {
  BOOST_TEST(myComp1(64) == true);
  BOOST_TEST(myComp1(3) == false);
}

max_stars_repo_path: examples/Native project/tests/test1.cpp

max_issues_repo_path: examples/Native project/tests/test1.cpp

max_forks_repo_path: examples/Native project/tests/test1.cpp