text:
/*
 * @CopyRight:
 * FISCO-BCOS 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.
 *
 * FISCO-BCOS 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 FISCO-BCOS.  If not, see <http://www.gnu.org/licenses/>
 * (c) 2016-2019 fisco-dev contributors.
 */

/**
 * @brief : SyncTreeTopologyTest
 * @author: yujiechen
 * @date: 2019-9-29
 */
#include <libdevcrypto/Common.h>
#include <libsync/SyncTreeTopology.h>
#include <test/tools/libutils/TestOutputHelper.h>
#include <boost/test/unit_test.hpp>

using namespace dev::sync;

namespace dev
{
namespace test
{
BOOST_FIXTURE_TEST_SUITE(SyncTreeTopologyTest, TestOutputHelperFixture)

class FakeSyncTreeTopology : public SyncTreeTopology
{
public:
    using Ptr = std::shared_ptr<FakeSyncTreeTopology>;
    FakeSyncTreeTopology(dev::h512 const& _nodeId, unsigned const& _treeWidth = 2)
      : SyncTreeTopology(_nodeId, _treeWidth)
    {}

    virtual dev::h512s const& currentConsensusNodes() { return *m_currentConsensusNodes; }

    virtual dev::h512s const& nodeList() { return *m_nodeList; }
    void recursiveSelectChildNodesWrapper(std::shared_ptr<dev::h512s> selectedNodeList,
        ssize_t const& parentIndex, std::shared_ptr<std::set<dev::h512>> peers)
    {
        int64_t offset = m_startIndex - 1;
        if (m_consIndex > 0)
        {
            return SyncTreeTopology::recursiveSelectChildNodes(selectedNodeList, 0, peers, offset);
        }
        else
        {
            int64_t nodeIndex = parentIndex + 1 - m_startIndex;
            return SyncTreeTopology::recursiveSelectChildNodes(
                selectedNodeList, nodeIndex, peers, offset);
        }
    }
    // select the parent nodes by tree
    void selectParentNodesWrapper(std::shared_ptr<dev::h512s> selectedNodeList,
        std::shared_ptr<std::set<dev::h512>> peers, int64_t const& _nodeIndex)
    {
        int64_t offset = m_startIndex - 1;
        int64_t nodeIndex = _nodeIndex + 1 - m_startIndex;
        return SyncTreeTopology::selectParentNodes(selectedNodeList, peers, nodeIndex, offset);
    }
    virtual int64_t nodeNum() { return m_nodeNum; }

    virtual dev::h512 nodeId() { return m_nodeId; }

    virtual int64_t nodeIndex() const { return m_nodeIndex; }
    virtual int64_t consIndex() const { return m_consIndex; }
    virtual int64_t endIndex() const { return m_endIndex; }
    virtual int64_t startIndex() const { return m_startIndex; }
};

class SyncTreeToplogyFixture
{
public:
    using Ptr = std::shared_ptr<SyncTreeToplogyFixture>;
    SyncTreeToplogyFixture(unsigned const& _treeWidth = 2)
    {
        dev::h512 nodeId = KeyPair::create().pub();
        // create a 2-tree rounter
        m_syncTreeRouter = std::make_shared<FakeSyncTreeTopology>(nodeId, _treeWidth);
        m_peers = std::make_shared<std::set<dev::h512>>();
    }

    void addNodeIntoConsensusList(dev::h512 const& nodeId)
    {
        m_nodeList.push_back(nodeId);
        m_consensusList.push_back(nodeId);
        m_peers->insert(nodeId);
    }

    void addNodeIntoObserverList(dev::h512 const& nodeId)
    {
        m_nodeList.push_back(nodeId);
        m_peers->insert(nodeId);
    }

    // fake ConsensusList
    void fakeConsensusList(size_t size)
    {
        for (size_t i = 0; i < size; i++)
        {
            dev::h512 nodeId = KeyPair::create().pub();
            m_consensusList.push_back(nodeId);
            m_nodeList.push_back(nodeId);
            m_peers->insert(nodeId);
        }
    }

    // fake observerList
    void fakeObserverList(size_t size)
    {
        for (size_t i = 0; i < size; i++)
        {
            dev::h512 nodeId = KeyPair::create().pub();
            m_nodeList.push_back(nodeId);
            m_peers->insert(nodeId);
        }
    }

    // clear both nodeList and consensusList
    void clearNodeList()
    {
        m_consensusList.clear();
        m_nodeList.clear();
        m_peers->clear();
    }

    void updateNodeListInfo() { m_syncTreeRouter->updateNodeListInfo(m_nodeList); }

    void updateConsensusNodeInfo()
    {
        m_syncTreeRouter->updateAllNodeInfo(m_consensusList, m_nodeList);
    }
    std::shared_ptr<FakeSyncTreeTopology> syncTreeRouter() { return m_syncTreeRouter; }
    dev::h512s const& consensusList() { return m_consensusList; }
    dev::h512s const& nodeList() { return m_nodeList; }
    std::shared_ptr<std::set<dev::h512>> peers() { return m_peers; }

private:
    std::shared_ptr<FakeSyncTreeTopology> m_syncTreeRouter = nullptr;
    dev::h512s m_consensusList;  // faked consensus list
    dev::h512s m_nodeList;       // faked node list
    std::shared_ptr<std::set<dev::h512>> m_peers;
};

void checkSelectedNodes(SyncTreeToplogyFixture::Ptr fakeSyncTreeTopology,
    dev::h512s const& selectedNodes, std::vector<size_t> idxVec)
{
    BOOST_CHECK(selectedNodes.size() == idxVec.size());
    size_t i = 0;
    for (auto const& node : selectedNodes)
    {
        BOOST_CHECK(node == fakeSyncTreeTopology->syncTreeRouter()->nodeList()[idxVec[i]]);
        i++;
    }
}

/// case1: the node doesn't locate in the node list (free node)
BOOST_AUTO_TEST_CASE(testFreeNode)
{
    SyncTreeToplogyFixture::Ptr fakeSyncTreeTopology = std::make_shared<SyncTreeToplogyFixture>();

    fakeSyncTreeTopology->fakeConsensusList(2);

    // updateConsensusNodeInfo and check consensusList
    fakeSyncTreeTopology->updateConsensusNodeInfo();
    BOOST_CHECK(fakeSyncTreeTopology->consensusList() ==
                fakeSyncTreeTopology->syncTreeRouter()->currentConsensusNodes());
    BOOST_CHECK(fakeSyncTreeTopology->syncTreeRouter()->consIndex() == -1);
    // check node list
    BOOST_CHECK(
        fakeSyncTreeTopology->syncTreeRouter()->nodeList() == fakeSyncTreeTopology->nodeList());
    // check startIndex and endIndex
    BOOST_CHECK(fakeSyncTreeTopology->syncTreeRouter()->startIndex() == 0);
    BOOST_CHECK(fakeSyncTreeTopology->syncTreeRouter()->endIndex() == 0);

    // updateNodeInfo and check NodeInfo
    fakeSyncTreeTopology->updateNodeListInfo();
    BOOST_CHECK(
        fakeSyncTreeTopology->nodeList() == fakeSyncTreeTopology->syncTreeRouter()->nodeList());
    BOOST_CHECK(fakeSyncTreeTopology->syncTreeRouter()->nodeNum() ==
                (int64_t)fakeSyncTreeTopology->nodeList().size());
    BOOST_CHECK(fakeSyncTreeTopology->syncTreeRouter()->nodeIndex() == -1);
    BOOST_CHECK(fakeSyncTreeTopology->syncTreeRouter()->consIndex() == -1);
    BOOST_CHECK(fakeSyncTreeTopology->syncTreeRouter()->startIndex() == 0);
    BOOST_CHECK(fakeSyncTreeTopology->syncTreeRouter()->endIndex() == 0);

    // selectNodes: no need to send blocks to any nodes
    std::shared_ptr<dev::h512s> selectedNodeList = std::make_shared<dev::h512s>();
    fakeSyncTreeTopology->syncTreeRouter()->recursiveSelectChildNodesWrapper(
        selectedNodeList, -1, fakeSyncTreeTopology->peers());
    BOOST_CHECK(*selectedNodeList == dev::h512s());
}

/// case2: the node locates in the observerList
BOOST_AUTO_TEST_CASE(testForTheObserverNode)
{
    SyncTreeToplogyFixture::Ptr fakeSyncTreeTopology = std::make_shared<SyncTreeToplogyFixture>();

    fakeSyncTreeTopology->fakeConsensusList(2);
    fakeSyncTreeTopology->updateConsensusNodeInfo();
    fakeSyncTreeTopology->updateNodeListInfo();

    BOOST_CHECK(fakeSyncTreeTopology->syncTreeRouter()->consIndex() == -1);
    BOOST_CHECK(fakeSyncTreeTopology->syncTreeRouter()->nodeIndex() == -1);

    // push the node into the observerList
    /// case1: nodeIndex is 2, no need to broadcast to any node
    fakeSyncTreeTopology->addNodeIntoObserverList(fakeSyncTreeTopology->syncTreeRouter()->nodeId());
    fakeSyncTreeTopology->updateNodeListInfo();
    BOOST_CHECK(fakeSyncTreeTopology->syncTreeRouter()->consIndex() == -1);
    BOOST_CHECK(fakeSyncTreeTopology->syncTreeRouter()->nodeIndex() == 2);
    // check NodeList
    BOOST_CHECK(
        fakeSyncTreeTopology->nodeList() == fakeSyncTreeTopology->syncTreeRouter()->nodeList());
    BOOST_CHECK(fakeSyncTreeTopology->syncTreeRouter()->nodeNum() ==
                (int64_t)fakeSyncTreeTopology->nodeList().size());

    // select target nodes from peers for this node
    std::shared_ptr<dev::h512s> selectedNodeList = std::make_shared<dev::h512s>();
    fakeSyncTreeTopology->syncTreeRouter()->recursiveSelectChildNodesWrapper(
        selectedNodeList, 2, fakeSyncTreeTopology->peers());
    BOOST_CHECK(*selectedNodeList == dev::h512s());

    // select parent for the 2th nodes
    selectedNodeList->clear();
    fakeSyncTreeTopology->syncTreeRouter()->selectParentNodesWrapper(
        selectedNodeList, fakeSyncTreeTopology->peers(), 1);
    BOOST_CHECK(*selectedNodeList == dev::h512s());

    /// case2: nodeIndex is 0
    fakeSyncTreeTopology->clearNodeList();
    fakeSyncTreeTopology->addNodeIntoObserverList(fakeSyncTreeTopology->syncTreeRouter()->nodeId());
    fakeSyncTreeTopology->fakeObserverList(10);
    fakeSyncTreeTopology->fakeConsensusList(2);
    fakeSyncTreeTopology->updateConsensusNodeInfo();
    fakeSyncTreeTopology->updateNodeListInfo();
    BOOST_CHECK(
        fakeSyncTreeTopology->syncTreeRouter()->nodeList() == fakeSyncTreeTopology->nodeList());
    BOOST_CHECK(fakeSyncTreeTopology->syncTreeRouter()->nodeNum() ==
                (int64_t)fakeSyncTreeTopology->nodeList().size());
    BOOST_CHECK(fakeSyncTreeTopology->syncTreeRouter()->nodeIndex() == 0);
    BOOST_CHECK(fakeSyncTreeTopology->syncTreeRouter()->consIndex() == -1);
    BOOST_CHECK(fakeSyncTreeTopology->syncTreeRouter()->startIndex() == 0);
    BOOST_CHECK(fakeSyncTreeTopology->syncTreeRouter()->endIndex() == 7);

    // check and select nodes for the 0th node
    selectedNodeList->clear();
    fakeSyncTreeTopology->syncTreeRouter()->recursiveSelectChildNodesWrapper(
        selectedNodeList, 0, fakeSyncTreeTopology->peers());
    std::vector<size_t> idxVec = {2, 3};
    checkSelectedNodes(fakeSyncTreeTopology, *selectedNodeList, idxVec);

    // check and select nodes for the 1th node
    selectedNodeList->clear();
    fakeSyncTreeTopology->syncTreeRouter()->recursiveSelectChildNodesWrapper(
        selectedNodeList, 1, fakeSyncTreeTopology->peers());
    idxVec = {4, 5};
    checkSelectedNodes(fakeSyncTreeTopology, *selectedNodeList, idxVec);

    // check and select nodes for the 2th node
    selectedNodeList->clear();
    fakeSyncTreeTopology->syncTreeRouter()->recursiveSelectChildNodesWrapper(
        selectedNodeList, 2, fakeSyncTreeTopology->peers());
    idxVec = {6};
    checkSelectedNodes(fakeSyncTreeTopology, *selectedNodeList, idxVec);

    // check other nodes that has no child
    for (size_t i = 3; i <= 6; i++)
    {
        selectedNodeList->clear();
        fakeSyncTreeTopology->syncTreeRouter()->recursiveSelectChildNodesWrapper(
            selectedNodeList, i, fakeSyncTreeTopology->peers());
        checkSelectedNodes(fakeSyncTreeTopology, *selectedNodeList, {});
    }
    /// check parent
    for (size_t i = 0; i <= 1; i++)
    {
        selectedNodeList->clear();
        fakeSyncTreeTopology->syncTreeRouter()->selectParentNodesWrapper(
            selectedNodeList, fakeSyncTreeTopology->peers(), i);
        BOOST_CHECK(*selectedNodeList == dev::h512s());
    }
    // check parent for 2th node
    for (size_t i = 2; i <= 3; i++)
    {
        selectedNodeList->clear();
        fakeSyncTreeTopology->syncTreeRouter()->selectParentNodesWrapper(
            selectedNodeList, fakeSyncTreeTopology->peers(), i);
        checkSelectedNodes(fakeSyncTreeTopology, *selectedNodeList, {0});
    }

    for (size_t i = 4; i <= 5; i++)
    {
        selectedNodeList->clear();
        fakeSyncTreeTopology->syncTreeRouter()->selectParentNodesWrapper(
            selectedNodeList, fakeSyncTreeTopology->peers(), i);
        checkSelectedNodes(fakeSyncTreeTopology, *selectedNodeList, {1});
    }
    selectedNodeList->clear();
    fakeSyncTreeTopology->syncTreeRouter()->selectParentNodesWrapper(
        selectedNodeList, fakeSyncTreeTopology->peers(), 6);
    checkSelectedNodes(fakeSyncTreeTopology, *selectedNodeList, {2});

    /// case3: nodeIndex is 13
    fakeSyncTreeTopology->clearNodeList();
    fakeSyncTreeTopology->fakeObserverList(10);
    fakeSyncTreeTopology->fakeConsensusList(2);
    fakeSyncTreeTopology->addNodeIntoObserverList(fakeSyncTreeTopology->syncTreeRouter()->nodeId());
    fakeSyncTreeTopology->updateConsensusNodeInfo();
    fakeSyncTreeTopology->updateNodeListInfo();

    BOOST_CHECK(fakeSyncTreeTopology->syncTreeRouter()->nodeIndex() == 12);
    BOOST_CHECK(fakeSyncTreeTopology->syncTreeRouter()->consIndex() == -1);
    BOOST_CHECK(fakeSyncTreeTopology->syncTreeRouter()->startIndex() == 7);
    BOOST_CHECK(fakeSyncTreeTopology->syncTreeRouter()->endIndex() == 6);

    // check the 7th nodes
    selectedNodeList->clear();
    fakeSyncTreeTopology->syncTreeRouter()->recursiveSelectChildNodesWrapper(
        selectedNodeList, 7, fakeSyncTreeTopology->peers());
    idxVec = {9, 10};
    checkSelectedNodes(fakeSyncTreeTopology, *selectedNodeList, idxVec);
    // check parent for 9th and 10th
    for (size_t i = 9; i <= 10; i++)
    {
        selectedNodeList->clear();
        fakeSyncTreeTopology->syncTreeRouter()->selectParentNodesWrapper(
            selectedNodeList, fakeSyncTreeTopology->peers(), i);
        checkSelectedNodes(fakeSyncTreeTopology, *selectedNodeList, {7});
    }

    // check the 8th nodes
    selectedNodeList->clear();
    fakeSyncTreeTopology->syncTreeRouter()->recursiveSelectChildNodesWrapper(
        selectedNodeList, 8, fakeSyncTreeTopology->peers());
    idxVec = {11, 12};
    checkSelectedNodes(fakeSyncTreeTopology, *selectedNodeList, idxVec);
    for (size_t i = 11; i <= 12; i++)
    {
        selectedNodeList->clear();
        fakeSyncTreeTopology->syncTreeRouter()->selectParentNodesWrapper(
            selectedNodeList, fakeSyncTreeTopology->peers(), i);
        checkSelectedNodes(fakeSyncTreeTopology, *selectedNodeList, {8});
    }
}

/// case3: the node locates in the consensus nodeList
BOOST_AUTO_TEST_CASE(testForTheConsensusNode)
{
    // init SyncTreeToplogyFixture
    SyncTreeToplogyFixture::Ptr fakeSyncTreeTopology = std::make_shared<SyncTreeToplogyFixture>(2);
    fakeSyncTreeTopology->fakeObserverList(11);
    fakeSyncTreeTopology->fakeConsensusList(1);
    fakeSyncTreeTopology->addNodeIntoConsensusList(
        fakeSyncTreeTopology->syncTreeRouter()->nodeId());
    fakeSyncTreeTopology->updateConsensusNodeInfo();
    fakeSyncTreeTopology->updateNodeListInfo();
    BOOST_CHECK(
        fakeSyncTreeTopology->syncTreeRouter()->nodeList() == fakeSyncTreeTopology->nodeList());
    BOOST_CHECK(fakeSyncTreeTopology->syncTreeRouter()->nodeNum() ==
                (int64_t)fakeSyncTreeTopology->nodeList().size());
    BOOST_CHECK(fakeSyncTreeTopology->syncTreeRouter()->nodeIndex() == 12);
    BOOST_CHECK(fakeSyncTreeTopology->syncTreeRouter()->consIndex() == 1);
    BOOST_CHECK(fakeSyncTreeTopology->syncTreeRouter()->startIndex() == 7);
    BOOST_CHECK(fakeSyncTreeTopology->syncTreeRouter()->endIndex() == 6);

    // get childNodes and parentNodes for this node
    std::shared_ptr<dev::h512s> selectedNodeList = std::make_shared<dev::h512s>();
    fakeSyncTreeTopology->syncTreeRouter()->recursiveSelectChildNodesWrapper(
        selectedNodeList, 0, fakeSyncTreeTopology->peers());
    checkSelectedNodes(fakeSyncTreeTopology, *selectedNodeList, {7, 8});

    // check parent
    selectedNodeList->clear();
    fakeSyncTreeTopology->syncTreeRouter()->selectParentNodesWrapper(selectedNodeList,
        fakeSyncTreeTopology->peers(), fakeSyncTreeTopology->syncTreeRouter()->nodeIndex());
    BOOST_CHECK(
        *selectedNodeList == fakeSyncTreeTopology->syncTreeRouter()->currentConsensusNodes());
}

BOOST_AUTO_TEST_SUITE_END()
}  // namespace test
}  // namespace dev

max_stars_repo_name: imtypist/FISCO-BCOS

max_issues_repo_name: imtypist/FISCO-BCOS

max_forks_repo_name: imtypist/FISCO-BCOS


text:
/*
 * Copyright 2020 INRIA
 */

#ifndef __eigenpy_decomposition_llt_hpp__
#define __eigenpy_decomposition_llt_hpp__

#include "eigenpy/eigenpy.hpp"

#include <Eigen/Core>
#include <Eigen/Cholesky>

#include "eigenpy/utils/scalar-name.hpp"

namespace eigenpy
{

  template<typename _MatrixType>
  struct LLTSolverVisitor
  : public boost::python::def_visitor< LLTSolverVisitor<_MatrixType> >
  {

    typedef _MatrixType MatrixType;
    typedef typename MatrixType::Scalar Scalar;
    typedef typename MatrixType::RealScalar RealScalar;
    typedef Eigen::Matrix<Scalar,Eigen::Dynamic,1,MatrixType::Options> VectorType;
    typedef Eigen::LLT<MatrixType> Solver;

    template<class PyClass>
    void visit(PyClass& cl) const
    {
      namespace bp = boost::python;
      cl
      .def(bp::init<>("Default constructor"))
      .def(bp::init<Eigen::DenseIndex>(bp::arg("size"),
                                       "Default constructor with memory preallocation"))
      .def(bp::init<MatrixType>(bp::arg("matrix"),
                                "Constructs a LLT factorization from a given matrix."))

      .def("matrixL",&matrixL,bp::arg("self"),
           "Returns the lower triangular matrix L.")
      .def("matrixU",&matrixU,bp::arg("self"),
           "Returns the upper triangular matrix U.")
      .def("matrixLLT",&Solver::matrixLLT,bp::arg("self"),
           "Returns the LLT decomposition matrix.",
           bp::return_internal_reference<>())

#if EIGEN_VERSION_AT_LEAST(3,3,90)
      .def("rankUpdate",(Solver& (Solver::*)(const VectorType &, const RealScalar &))&Solver::template rankUpdate<VectorType>,
           bp::args("self","vector","sigma"), bp::return_self<>())
#else
      .def("rankUpdate",(Solver (Solver::*)(const VectorType &, const RealScalar &))&Solver::template rankUpdate<VectorType>,
           bp::args("self","vector","sigma"))
#endif

#if EIGEN_VERSION_AT_LEAST(3,3,0)
      .def("adjoint",&Solver::adjoint,bp::arg("self"),
           "Returns the adjoint, that is, a reference to the decomposition itself as if the underlying matrix is self-adjoint.",
           bp::return_self<>())
#endif

      .def("compute",(Solver & (Solver::*)(const Eigen::EigenBase<MatrixType> & matrix))&Solver::compute,
           bp::args("self","matrix"),
           "Computes the LLT of given matrix.",
           bp::return_self<>())

      .def("info",&Solver::info,bp::arg("self"),
           "NumericalIssue if the input contains INF or NaN values or overflow occured. Returns Success otherwise.")
#if EIGEN_VERSION_AT_LEAST(3,3,0)
      .def("rcond",&Solver::rcond,bp::arg("self"),
           "Returns an estimate of the reciprocal condition number of the matrix.")
#endif
      .def("reconstructedMatrix",&Solver::reconstructedMatrix,bp::arg("self"),
           "Returns the matrix represented by the decomposition, i.e., it returns the product: L L^*. This function is provided for debug purpose.")
      .def("solve",&solve<VectorType>,bp::args("self","b"),
           "Returns the solution x of A x = b using the current decomposition of A.")
      ;
    }

    static void expose()
    {
      static const std::string classname = "LLT" + scalar_name<Scalar>::shortname();
      expose(classname);
    }

    static void expose(const std::string & name)
    {
      namespace bp = boost::python;
      bp::class_<Solver>(name.c_str(),
                         "Standard Cholesky decomposition (LL^T) of a matrix and associated features.\n\n"
                         "This class performs a LL^T Cholesky decomposition of a symmetric, positive definite matrix A such that A = LL^* = U^*U, where L is lower triangular.\n\n"
                         "While the Cholesky decomposition is particularly useful to solve selfadjoint problems like D^*D x = b, for that purpose, we recommend the Cholesky decomposition without square root which is more stable and even faster. Nevertheless, this standard Cholesky decomposition remains useful in many other situations like generalised eigen problems with hermitian matrices.",
                         bp::no_init)
      .def(LLTSolverVisitor());
    }

  private:

    static MatrixType matrixL(const Solver & self) { return self.matrixL(); }
    static MatrixType matrixU(const Solver & self) { return self.matrixU(); }

    template<typename VectorType>
    static VectorType solve(const Solver & self, const VectorType & vec)
    {
      return self.solve(vec);
    }
  };

} // namespace eigenpy

#endif // ifndef __eigenpy_decomposition_llt_hpp__

ext: hpp

max_stars_repo_name: cmastalli/eigenpy

max_issues_repo_name: cmastalli/eigenpy

max_forks_repo_name: cmastalli/eigenpy


text:
//  (C) Copyright Gennadiy Rozental 2005-2014.
//  Use, modification, and distribution are subject to the
//  Boost Software License, Version 1.0. (See accompanying file
//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

//  See http://www.boost.org/libs/test for the library home page.
//
//  File        : $RCSfile$
//
//  Version     : $Revision$
//
//  Description : defines models configuration file, it's parameter and parameter namespaces
// ***************************************************************************

#ifndef BOOST_TEST_UTILS_RUNTIME_FILE_CONFIG_FILE_HPP
#define BOOST_TEST_UTILS_RUNTIME_FILE_CONFIG_FILE_HPP

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

#include <boost/test/utils/runtime/file/config_file_iterator.hpp>

// Boost.Test
#include <boost/test/utils/class_properties.hpp>
#include <boost/test/utils/named_params.hpp>

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

// STL
#include <list>

namespace boost {

namespace BOOST_TEST_UTILS_RUNTIME_PARAM_NAMESPACE {

namespace file {

// ************************************************************************** //
// **************           runtime::file::parameter           ************** //
// ************************************************************************** //

class param_namespace;

class parameter {
public:
    // Constructor
    parameter( cstring name, cstring value, param_namespace const& parent );

    BOOST_READONLY_PROPERTY( dstring, (parameter))  p_name;
    BOOST_READONLY_PROPERTY( dstring, (parameter))  p_value;

    friend std::ostream& operator<<( std::ostream& os, parameter const& );

private:
    // Data members
    param_namespace const&  m_parent;
};

// ************************************************************************** //
// **************           runtime::file::modifiers           ************** //
// ************************************************************************** //

namespace {
nfp::typed_keyword<cstring, struct value_marker_t>          value_marker;
nfp::typed_keyword<cstring, struct value_delimeter_t>       value_delimeter;
nfp::typed_keyword<cstring, struct namespace_delimeter_t>   namespace_delimeter;
} // local namespace

// ************************************************************************** //
// **************        runtime::file::param_namespace        ************** //
// ************************************************************************** //

class param_namespace {
public:
    typedef std::list<parameter>::iterator              iterator;
    typedef std::list<parameter>::const_iterator        const_iterator;
    typedef std::list<param_namespace>::iterator        sub_ns_iterator;
    typedef std::list<param_namespace>::const_iterator  sub_ns_const_iterator;

    // Public properties
    BOOST_READONLY_PROPERTY( dstring, (param_namespace))    p_name;
    unit_test::readonly_property<param_namespace const*>    p_parent;

    void                    load( config_file_iterator cf_it ) { load( cf_it, nfp::no_params );  }
    template<typename Modifier>
    void                    load( config_file_iterator cf_it, Modifier const& m )
    {
        cstring vm = m.has( value_marker )        ? m[value_marker]        : BOOST_TEST_UTILS_RUNTIME_PARAM_CSTRING_LITERAL( "\"" );
        cstring vd = m.has( value_delimeter )     ? m[value_delimeter]     : BOOST_TEST_UTILS_RUNTIME_PARAM_CSTRING_LITERAL( "= \t\n\r" );
        cstring nd = m.has( namespace_delimeter ) ? m[namespace_delimeter] : BOOST_TEST_UTILS_RUNTIME_PARAM_CSTRING_LITERAL( "::" );

        load_impl( cf_it, vm, vd, nd );
    }
    void                    load( cstring file_name )
    {
        load( file_name, nfp::no_params );
    }
    template<typename Modifier>
    void                    load( cstring file_name, Modifier const& m )
    {
        config_file_iterator cfi( file_name, m );

        load( cfi, m );
    }

    void                    insert_param( cstring param_name, cstring param_value );
    param_namespace&        subnamespace( cstring namespace_name );         // find and insert if not present
    void                    clear();

    iterator                begin()                 { return m_parameters.begin(); }
    const_iterator          begin() const           { return m_parameters.begin(); }

    iterator                end()                   { return m_parameters.end(); }
    const_iterator          end() const             { return m_parameters.end(); }

    sub_ns_iterator         sub_ns_begin()          { return m_subnamespaces.begin(); }
    sub_ns_const_iterator   sub_ns_begin() const    { return m_subnamespaces.begin(); }

    sub_ns_iterator         sub_ns_end()            { return m_subnamespaces.end(); }
    sub_ns_const_iterator   sub_ns_end()  const     { return m_subnamespaces.end(); }

    void                    print_full_name( std::ostream& os ) const;

protected:
    explicit                param_namespace( cstring name, param_namespace const* parent = 0 );

private:
    void                    load_impl( config_file_iterator cf_it,
                                       cstring value_marker_, cstring value_delimeter_, cstring namespace_delimeter_ );

    // Data members
    std::list<parameter>        m_parameters;
    std::list<param_namespace>  m_subnamespaces;
};

//____________________________________________________________________________//

boost::optional<cstring>
get_param_value( param_namespace const& where_from,
                 cstring                name_part1,
                 cstring                name_part2 = cstring(),
                 cstring                name_part3 = cstring(),
                 cstring                name_part4 = cstring(),
                 cstring                name_part5 = cstring() );

//____________________________________________________________________________//

cstring
get_requ_param_value( param_namespace const& where_from,
                      cstring                name_part1,
                      cstring                name_part2 = cstring(),
                      cstring                name_part3 = cstring(),
                      cstring                name_part4 = cstring(),
                      cstring                name_part5 = cstring() );

//____________________________________________________________________________//

param_namespace const*
get_param_subns( param_namespace const& where_from,
                 cstring                namespace_name );

//____________________________________________________________________________//

// ************************************************************************** //
// **************          runtime::file::config_file          ************** //
// ************************************************************************** //

class config_file : public param_namespace {
public:
    // Constructor
    config_file();
    config_file( cstring file_name );
};

} // namespace file

} // namespace BOOST_TEST_UTILS_RUNTIME_PARAM_NAMESPACE

} // namespace boost

#endif // BOOST_TEST_UTILS_RUNTIME_FILE_CONFIG_FILE_HPP_010105GER

max_stars_repo_name: BruceNUAA/gaze-detection-android-app

max_issues_repo_name: BruceNUAA/gaze-detection-android-app

max_forks_repo_name: BruceNUAA/gaze-detection-android-app


text:
/**
 * Copyright Soramitsu Co., Ltd. All Rights Reserved.
 * SPDX-License-Identifier: Apache-2.0
 */

#ifndef IROHA_BATCH_HELPER_HPP
#define IROHA_BATCH_HELPER_HPP

#include <boost/range/irange.hpp>

#include "framework/result_fixture.hpp"
#include "interfaces/iroha_internal/transaction_batch.hpp"
#include "module/shared_model/builders/protobuf/test_transaction_builder.hpp"
#include "validators/transactions_collection/batch_order_validator.hpp"

namespace framework {
  namespace batch {

    /**
     * Creates transaction builder with set creator
     * @tparam TransactionBuilderType type of tranasction builder
     * @return prepared transaction builder
     */
    template <typename TransactionBuilderType = TestTransactionBuilder>
    auto prepareTransactionBuilder(
        const std::string &creator,
        const size_t &created_time = iroha::time::now(),
        const shared_model::interface::types::QuorumType &quorum = 1) {
      return TransactionBuilderType()
          .setAccountQuorum(creator, 1)
          .creatorAccountId(creator)
          .createdTime(created_time)
          .quorum(quorum);
    }

    /**
     * Creates unsigned transaction builder with set creator
     * @return prepared transaction builder
     */
    auto prepareUnsignedTransactionBuilder(
        const std::string &creator,
        const size_t &created_time = iroha::time::now(),
        const shared_model::interface::types::QuorumType &quorum = 1) {
      return prepareTransactionBuilder<TestUnsignedTransactionBuilder>(
          creator, created_time, quorum);
    }

    /**
     * Create unsigned batch with given fields of transactions: batch type and
     * creator account.
     * @param btype_creator_pairs vector of pairs. First element in every pair
     * is batch type and second is creator account
     * @param now created time for every transaction
     * @return batch with the same size as size of range of pairs
     */
    auto createUnsignedBatchTransactions(
        std::vector<std::pair<shared_model::interface::types::BatchType,
                              std::string>> btype_creator_pairs,
        size_t now = iroha::time::now()) {
      std::vector<shared_model::interface::types::HashType> reduced_hashes;
      for (const auto &btype_creator : btype_creator_pairs) {
        auto tx = prepareTransactionBuilder(btype_creator.second, now).build();
        reduced_hashes.push_back(tx.reducedHash());
      }

      shared_model::interface::types::SharedTxsCollectionType txs;

      std::transform(
          btype_creator_pairs.begin(),
          btype_creator_pairs.end(),
          std::back_inserter(txs),
          [&now, &reduced_hashes](const auto &btype_creator)
              -> shared_model::interface::types::SharedTxsCollectionType::
                  value_type {
                    return clone(
                        prepareTransactionBuilder(btype_creator.second, now)
                            .batchMeta(btype_creator.first, reduced_hashes)
                            .build());
                  });
      return txs;
    }

    /**
     * Creates batch transactions, where every transaction has single signature
     * @param btype_creator_pairs vector of pairs of batch type and creator
     * account id
     * @param now created time for every transaction
     * @param quorum quorum for every transaction
     * @return batch with the same size as size of range of pairs
     */
    auto createBatchOneSignTransactions(
        std::vector<std::pair<shared_model::interface::types::BatchType,
                              std::string>> btype_creator_pairs,
        size_t now = iroha::time::now(),
        const shared_model::interface::types::QuorumType &quorum = 1) {
      std::vector<shared_model::interface::types::HashType> reduced_hashes;
      for (const auto &btype_creator : btype_creator_pairs) {
        auto tx =
            prepareUnsignedTransactionBuilder(btype_creator.second, now, quorum)
                .build();
        reduced_hashes.push_back(tx.reducedHash());
      }

      shared_model::interface::types::SharedTxsCollectionType txs;

      std::transform(
          btype_creator_pairs.begin(),
          btype_creator_pairs.end(),
          std::back_inserter(txs),
          [&now, &reduced_hashes, &quorum](const auto &btype_creator)
              -> shared_model::interface::types::SharedTxsCollectionType::
                  value_type {
                    return clone(
                        prepareUnsignedTransactionBuilder(
                            btype_creator.second, now, quorum)
                            .batchMeta(btype_creator.first, reduced_hashes)
                            .build()
                            .signAndAddSignature(
                                shared_model::crypto::
                                    DefaultCryptoAlgorithmType::
                                        generateKeypair())
                            .finish());
                  });
      return txs;
    }

    /**
     * Creates atomic batch from provided creator accounts
     * @param creators vector of creator account ids
     * @return unsigned batch of the same size as the size of creator account
     * ids
     */
    auto createUnsignedBatchTransactions(
        shared_model::interface::types::BatchType batch_type,
        const std::vector<std::string> &creators,
        size_t now = iroha::time::now()) {
      std::vector<std::pair<decltype(batch_type), std::string>> fields;
      std::transform(creators.begin(),
                     creators.end(),
                     std::back_inserter(fields),
                     [&batch_type](const auto creator) {
                       return std::make_pair(batch_type, creator);
                     });
      return createUnsignedBatchTransactions(fields, now);
    }

    /**
     * Creates transaction collection for the batch of given type and size
     * @param batch_type type of the creted transactions
     * @param batch_size size of the created collection of transactions
     * @param now created time for every transactions
     * @return unsigned batch
     */
    auto createUnsignedBatchTransactions(
        shared_model::interface::types::BatchType batch_type,
        uint32_t batch_size,
        size_t now = iroha::time::now()) {
      auto range = boost::irange(0, (int)batch_size);
      std::vector<std::string> creators;

      std::transform(range.begin(),
                     range.end(),
                     std::back_inserter(creators),
                     [](const auto &id) {
                       return std::string("account") + std::to_string(id)
                           + "@domain";
                     });

      return createUnsignedBatchTransactions(batch_type, creators, now);
    }

    auto createValidBatch(const size_t &size) {
      using namespace shared_model::validation;
      using TxValidator =
          TransactionValidator<FieldValidator,
                               CommandValidatorVisitor<FieldValidator>>;

      using TxsValidator =
          UnsignedTransactionsCollectionValidator<TxValidator,
                                                  BatchOrderValidator>;

      auto batch_type = shared_model::interface::types::BatchType::ATOMIC;
      std::vector<std::pair<decltype(batch_type), std::string>>
          transaction_fields;
      for (size_t i = 0; i < size; ++i) {
        transaction_fields.push_back(std::make_pair(
            batch_type, "account" + std::to_string(i) + "@domain"));
      }

      auto txs = createBatchOneSignTransactions(transaction_fields);
      auto result_batch =
          shared_model::interface::TransactionBatch::createTransactionBatch(
              txs, TxsValidator());

      return framework::expected::val(result_batch).value().value;
    }

    /**
     * Namespace provides useful functions which are related to implementation
     * but they are internal API
     */
    namespace internal {

      /**
       * Create list of hashes
       * @tparam TxBuilderCollection - type of builder
       * @param builders - initializer list which contains all builders
       * @return vector with transactions hashes
       */
      template <typename TxBuilder>
      auto fetchReducedHashes(
          const std::initializer_list<TxBuilder> &builders) {
        std::vector<shared_model::interface::types::HashType> hashes;
        std::transform(
            builders.begin(),
            builders.end(),
            std::back_inserter(hashes),
            [](const auto &builder) { return builder.build().reducedHash(); });
        return hashes;
      }

      /**
       * Variadic to initializer list adapter
       */
      template <typename... TxBuilders>
      auto fetchReducedHashes(const TxBuilders &... builders) {
        return fetchReducedHashes({builders...});
      }

      /**
       * Function create transactions from builder and passed hashes
       * @tparam TxBuilder - type of one builder
       * @param hashes - vector of hashes of transactions
       * @param builders - initializer list of tx builders
       * @return transactions with correct batch meta
       */
      template <typename TxBuilder>
      auto makeTxBatchCollection(
          const std::vector<shared_model::interface::types::HashType> &hashes,
          std::initializer_list<TxBuilder> builders) {
        shared_model::interface::types::SharedTxsCollectionType transactions;

        std::transform(
            builders.begin(),
            builders.end(),
            std::back_inserter(transactions),
            [&hashes](const auto &builder) {
              return makePolyTxFromBuilder(builder.batchMeta(
                  shared_model::interface::types::BatchType::ATOMIC, hashes));
            });
        return transactions;
      }

      /**
       * Variadic to initializer list adapter
       */
      template <typename... TxBuilders>
      auto makeTxBatchCollection(TxBuilders &&... builders) {
        auto hashes = fetchReducedHashes(builders...);
        return makeTxBatchCollection(std::move(hashes),
                                     {std::forward<TxBuilders>(builders)...});
      }
    }  // namespace internal

    /**
     * Create test batch from passed transaction builders
     * @tparam TxBuilders - variadic types of tx builders
     * @return shared_ptr for batch
     */
    template <typename... TxBuilders>
    auto makeTestBatch(TxBuilders &&... builders) {
      auto transactions = internal::makeTxBatchCollection(
          std::forward<TxBuilders>(builders)...);

      using namespace shared_model::validation;
      using TxValidator =
          TransactionValidator<FieldValidator,
                               CommandValidatorVisitor<FieldValidator>>;

      using TxsValidator =
          UnsignedTransactionsCollectionValidator<TxValidator,
                                                  BatchOrderValidator>;

      auto batch =
          shared_model::interface::TransactionBatch::createTransactionBatch(
              transactions, TxsValidator());

      return std::make_shared<shared_model::interface::TransactionBatch>(
          framework::expected::val(batch).value().value);
    }

  }  // namespace batch
}  // namespace framework

#endif  // IROHA_BATCH_HELPER_HPP

max_stars_repo_name: truongnmt/iroha

max_issues_repo_name: truongnmt/iroha

max_forks_repo_name: truongnmt/iroha


text:
#include "test.h"

#include <iostream>
#include <string>
#include <vector>

#include "baldr/graphconstants.h"
#include "baldr/graphid.h"
#include "baldr/graphreader.h"
#include "baldr/nodeinfo.h"
#include "midgard/util.h"
#include "mjolnir/graphtilebuilder.h"

#include "baldr/rapidjson_utils.h"
#include <boost/property_tree/ptree.hpp>

using namespace valhalla::baldr;
using namespace valhalla::mjolnir;
using namespace valhalla::midgard;

namespace {

boost::property_tree::ptree json_to_pt(const std::string& json) {
  std::stringstream ss;
  ss << json;
  boost::property_tree::ptree pt;
  rapidjson::read_json(ss, pt);
  return pt;
}

const auto config = json_to_pt(R"({
    "mjolnir":{"tile_dir":"test/data/utrecht_tiles", "concurrency": 1}
  })");

} // namespace

void test_predictive_traffic() {
  boost::property_tree::ptree hierarchy_properties = config.get_child("mjolnir");
  GraphReader reader(hierarchy_properties);

  uint32_t count = 0;
  auto level = TileHierarchy::levels().rbegin();
  for (; level != TileHierarchy::levels().rend(); ++level) {
    // Create a randomized queue of tiles to work from
    auto tile_level = level->second;
    auto level_tiles = reader.GetTileSet(tile_level.level);
    for (const auto& tile_id : level_tiles) {
      const GraphTile* tile = reader.GetGraphTile(tile_id);
      uint32_t nodecount = tile->header()->nodecount();
      GraphId node = tile_id;
      for (uint32_t i = 0; i < nodecount; i++, ++node) {
        // The node we will modify
        auto ni = tile->node(i);
        uint32_t idx = ni->edge_index();
        GraphId edgeid(node.tileid(), node.level(), idx);
        for (uint32_t j = 0, n = ni->edge_count(); j < n; j++, idx++, ++edgeid) {
          auto de = tile->directededge(idx);

          if (edgeid.value == 67134432) {
            if (de->free_flow_speed() != 5)
              throw std::runtime_error("Free flow speed should be 5 for edge 67134432, but it is: " +
                                       std::to_string(de->free_flow_speed()));
            if (de->constrained_flow_speed() != 6)
              throw std::runtime_error(
                  "Constrained flow speed should be 6 for edge 67134432, but it is: " +
                  std::to_string(de->constrained_flow_speed()));
          } else if (edgeid.value == 264348364578) {
            if (de->free_flow_speed() != 13)
              throw std::runtime_error(
                  "Free fow speed should be 13 for edge 264348364578, but it is: " +
                  std::to_string(de->free_flow_speed()));
            if (de->constrained_flow_speed() != 9)
              throw std::runtime_error(
                  "Constrained flow speed should be 9 for edge 264348364578, but it is: " +
                  std::to_string(de->constrained_flow_speed()));
          }
          if (de->constrained_flow_speed() || de->free_flow_speed())
            count++;
        }
      }
    }
  }
  if (count != 23751)
    throw std::runtime_error("Incorrect number of edges updated.  Count: " + std::to_string(count));
}

void test_get_speed() {
  GraphReader reader(config.get_child("mjolnir"));

  // fixture traffic tile 0/003/196.gph
  GraphId id("0/3196/0");
  auto tile = reader.GetGraphTile(id);
  auto de = tile->directededge(id);

  if (!de->has_predicted_speed())
    throw std::runtime_error("No predicted speed on edge " + std::to_string(id));

  if (!de->constrained_flow_speed())
    throw std::runtime_error("No constrained speed on edge " + std::to_string(id));

  if (!de->free_flow_speed())
    throw std::runtime_error("No freeflow speed on edge " + std::to_string(id));

  // Test cases where constrained flow speed is returned
  auto expected = 35;
  std::vector<uint32_t> actuals = {tile->GetSpeed(de), tile->GetSpeed(de, kConstrainedFlowMask),
                                   tile->GetSpeed(de, kConstrainedFlowMask, 25201)};
  for (auto actual : actuals) {
    if (actual != expected) {
      throw std::runtime_error("Expected constrained speed | " + std::to_string(actual) +
                               " != " + std::to_string(expected));
    }
  }

  // Test cases where free flow speed is returned
  expected = 45;
  actuals = {tile->GetSpeed(de, kFreeFlowMask), tile->GetSpeed(de, kFreeFlowMask, kSecondsPerDay),
             tile->GetSpeed(de, kFreeFlowMask, 0)};
  for (auto actual : actuals) {
    if (actual != expected) {
      throw std::runtime_error("Expected freeflow speed | " + std::to_string(actual) +
                               " != " + std::to_string(expected));
    }
  }

  // Test cases where predicted flow speed is returned
  expected = 23;
  auto actual = tile->GetSpeed(de, kPredictedFlowMask, kConstrainedFlowSecondOfDay);
  if (actual != expected) {
    throw std::runtime_error("Expected predicted speed | " + std::to_string(actual) +
                             " != " + std::to_string(expected));
  }

  // Test cases where we has for a time of day that is huge
  expected = 23;
  actual = tile->GetSpeed(de, kPredictedFlowMask, kConstrainedFlowSecondOfDay + kSecondsPerWeek);
  if (actual != expected) {
    throw std::runtime_error("Expected predicted speed | " + std::to_string(actual) +
                             " != " + std::to_string(expected));
  }

  // Test flow_sources
  uint8_t flow_sources;
  tile->GetSpeed(de, kPredictedFlowMask, kConstrainedFlowSecondOfDay, &flow_sources);
  if (!(flow_sources & kPredictedFlowMask)) {
    throw std::runtime_error("Expected flow_sources to include predicted");
  }

  tile->GetSpeed(de, kConstrainedFlowMask, kConstrainedFlowSecondOfDay, &flow_sources);
  if (flow_sources & kPredictedFlowMask) {
    throw std::runtime_error("Expected flow_sources not to include predicted");
  }

  tile->GetSpeed(de, kNoFlowMask, kConstrainedFlowSecondOfDay, &flow_sources);
  if (flow_sources & kPredictedFlowMask) {
    throw std::runtime_error("Expected flow_sources not to include predicted");
  }
}

int main(int argc, char* argv[]) {
  test::suite suite("predictive_traffic");
  // TODO - add this back in when updated data is available!
  //  suite.test(TEST_CASE(test_predictive_traffic));

  suite.test(TEST_CASE(test_get_speed));

  return suite.tear_down();
}

ext: cc

max_stars_repo_name: elsa-pato/valhalla

max_issues_repo_name: elsa-pato/valhalla

max_forks_repo_name: elsa-pato/valhalla


text:
/*
    This file is part of cpp-ethereum.

    cpp-ethereum 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.

    cpp-ethereum 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 cpp-ethereum.  If not, see <http://www.gnu.org/licenses/>.
*/
/** @file ClientTest.cpp
 * @author Dimitry Khokhlov <dimitry@ethdev.com>
 * @date 2016
 */

#include <libdevcore/CommonJS.h>
#include <libethashseal/Ethash.h>
#include <libethereum/ClientTest.h>
#include <libethereum/EthereumCapability.h>
#include <boost/filesystem/path.hpp>
#include <future>

using namespace std;
using namespace dev;
using namespace dev::eth;
using namespace p2p;
namespace fs = boost::filesystem;

ClientTest& dev::eth::asClientTest(Interface& _c)
{
    return dynamic_cast<ClientTest&>(_c);
}

ClientTest* dev::eth::asClientTest(Interface* _c)
{
    return &dynamic_cast<ClientTest&>(*_c);
}

ClientTest::ClientTest(ChainParams const& _params, int _networkID, p2p::Host& _host,
    std::shared_ptr<GasPricer> _gpForAdoption, fs::path const& _dbPath, WithExisting _forceAction,
    TransactionQueue::Limits const& _limits)
  : Client(
        _params, _networkID, _host, _gpForAdoption, _dbPath, std::string(), _forceAction, _limits)
{}

ClientTest::~ClientTest()
{
    m_signalled.notify_all(); // to wake up the thread from Client::doWork()
    terminate();
}

void ClientTest::setChainParams(string const& _genesis)
{
    ChainParams params;
    try
    {
        params = params.loadConfig(_genesis);
        if (params.sealEngineName != NoProof::name() && params.sealEngineName != Ethash::name())
            BOOST_THROW_EXCEPTION(
                ChainParamsInvalid() << errinfo_comment("Seal engine is not supported!"));

        reopenChain(params, WithExisting::Kill);
    }
    catch (std::exception const& ex)
    {
        BOOST_THROW_EXCEPTION(ChainParamsInvalid() << errinfo_comment(ex.what()));
    }
}

void ClientTest::modifyTimestamp(int64_t _timestamp)
{
    Block block(chainParams().accountStartNonce);
    DEV_READ_GUARDED(x_preSeal)
        block = m_preSeal;

    Transactions transactions;
    DEV_READ_GUARDED(x_postSeal)
        transactions = m_postSeal.pending();
    block.resetCurrent(_timestamp);

    DEV_WRITE_GUARDED(x_preSeal)
        m_preSeal = block;

    auto& lastHashes = bc().lastBlockHashes();
    assert(bc().currentHash() == block.info().parentHash());
    for (auto const& t: transactions)
        block.execute(lastHashes, t);

    DEV_WRITE_GUARDED(x_working)
        m_working = block;
    DEV_READ_GUARDED(x_postSeal)
        m_postSeal = block;

    onPostStateChanged();
}

bool ClientTest::mineBlocks(unsigned _count) noexcept
{
    if (wouldSeal())
        return false;
    try
    {
        unsigned sealedBlocks = 0;
        auto sealHandler = setOnBlockSealed([this, _count, &sealedBlocks](bytes const&) {
            if (++sealedBlocks == _count)
                stopSealing();
        });

        std::promise<void> allBlocksImported;
        unsigned importedBlocks = 0;
        auto chainChangedHandler = setOnChainChanged(
            [_count, &importedBlocks, &allBlocksImported](h256s const&, h256s const& _newBlocks) {
                importedBlocks += _newBlocks.size();
                if (importedBlocks == _count)
                    allBlocksImported.set_value();
            });

        startSealing();
        future_status ret = allBlocksImported.get_future().wait_for(
            std::chrono::seconds(m_singleBlockMaxMiningTimeInSeconds * _count));
        return (ret == future_status::ready);
    }
    catch (std::exception const&)
    {
        LOG(m_logger) << boost::current_exception_diagnostic_information();
        return false;
    }
}

bool ClientTest::completeSync()
{
    auto h = m_host.lock();
    if (!h)
        return false;

    h->completeSync();
    return true;
}

h256 ClientTest::importRawBlock(const string& _blockRLP)
{
    bytes blockBytes = jsToBytes(_blockRLP, OnFailed::Throw);
    h256 blockHash = BlockHeader::headerHashFromBlock(blockBytes);
    ImportResult result = queueBlock(blockBytes, true);
    if (result != ImportResult::Success)
        BOOST_THROW_EXCEPTION(ImportBlockFailed() << errinfo_importResult(result));

    if (auto h = m_host.lock())
        h->noteNewBlocks();

    bool moreToImport = true;
    while (moreToImport)
    {
        tie(ignore, moreToImport, ignore) = syncQueue(100000);
        this_thread::sleep_for(chrono::milliseconds(100));
    }
    return blockHash;
}

ext: cpp

max_stars_repo_name: nccproject/ncc

max_issues_repo_name: estxcoin/estcore

max_forks_repo_name: estxcoin/estcore


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

// Copyright (c) 2007-2020 Barend Gehrels, Amsterdam, the Netherlands.

// This file was modified by Oracle on 2020.
// Modifications copyright (c) 2020 Oracle and/or its affiliates.
// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle

// 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)

#ifndef BOOST_GEOMETRY_GEOMETRY_POLICIES_RELATE_INTERSECTION_POLICY_HPP
#define BOOST_GEOMETRY_GEOMETRY_POLICIES_RELATE_INTERSECTION_POLICY_HPP

#include <string>
#include <tuple>

#include <boost/geometry/policies/relate/direction.hpp>
#include <boost/geometry/policies/relate/intersection_points.hpp>

#include <boost/geometry/strategies/side_info.hpp>

namespace boost { namespace geometry
{

namespace policies { namespace relate
{

template <typename IntersectionPointsReturnType>
struct segments_intersection_policy
{
private:
    typedef policies::relate::segments_intersection_points
        <
            IntersectionPointsReturnType
        > pts_policy;
    typedef policies::relate::segments_direction dir_policy;

public:
    struct return_type
    {
        typedef typename pts_policy::return_type intersection_points_type;
        typedef typename dir_policy::return_type direction_type;

        return_type(intersection_points_type const& pts_result,
                    direction_type const& dir_result)
            : intersection_points(pts_result)
            , direction(dir_result)
        {}

        intersection_points_type intersection_points;
        direction_type direction;
    };

    template <typename Segment1, typename Segment2, typename SegmentIntersectionInfo>
    static inline return_type segments_crosses(side_info const& sides,
                                        SegmentIntersectionInfo const& sinfo,
                                        Segment1 const& s1, Segment2 const& s2)
    {
        return return_type
            (
                pts_policy::segments_crosses(sides, sinfo, s1, s2),
                dir_policy::segments_crosses(sides, sinfo, s1, s2)
            );
    }

    template <typename Segment1, typename Segment2, typename Ratio>
    static inline return_type segments_collinear(
                                        Segment1 const& segment1,
                                        Segment2 const& segment2,
                                        bool opposite,
                                        int pa1, int pa2, int pb1, int pb2,
                                        Ratio const& ra1, Ratio const& ra2,
                                        Ratio const& rb1, Ratio const& rb2)
    {
        return return_type
            (
                pts_policy::segments_collinear(segment1, segment2,
                                               opposite,
                                               pa1, pa2, pb1, pb2,
                                               ra1, ra2, rb1, rb2),
                dir_policy::segments_collinear(segment1, segment2,
                                               opposite,
                                               pa1, pa2, pb1, pb2,
                                               ra1, ra2, rb1, rb2)
            );
    }

    template <typename Segment>
    static inline return_type degenerate(Segment const& segment,
                                         bool a_degenerate)
    {
        return return_type
            (
                pts_policy::degenerate(segment, a_degenerate),
                dir_policy::degenerate(segment, a_degenerate)
            );
    }

    template <typename Segment, typename Ratio>
    static inline return_type one_degenerate(Segment const& segment,
                                             Ratio const& ratio,
                                             bool a_degenerate)
    {
        return return_type
            (
                pts_policy::one_degenerate(segment, ratio, a_degenerate),
                dir_policy::one_degenerate(segment, ratio, a_degenerate)
            );
    }

    static inline return_type disjoint()
    {
        return return_type
            (
                pts_policy::disjoint(),
                dir_policy::disjoint()
            );
    }

    static inline return_type error(std::string const& msg)
    {
        return return_type
            (
                pts_policy::error(msg),
                dir_policy::error(msg)
            );
    }
};

}} // namespace policies::relate

}} // namespace boost::geometry

#endif // BOOST_GEOMETRY_GEOMETRY_POLICIES_RELATE_INTERSECTION_POLICY_HPP


text:
/*=============================================================================
    Copyright (c) 1998-2003 Joel de Guzman
    Copyright (c)      2003 Martin Wille
    http://spirit.sourceforge.net/

    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)
=============================================================================*/
#include <iostream>
#include <string>
#include <boost/detail/lightweight_test.hpp>
#include <boost/spirit/include/classic_core.hpp>
#include <boost/spirit/include/classic_symbols.hpp>
#include <boost/detail/lightweight_test.hpp>

///////////////////////////////////////////////////////////////////////////////
using namespace std;
using namespace BOOST_SPIRIT_CLASSIC_NS;

///////////////////////////////////////////////////////////////////////////////

template <typename IteratorT>
bool
equal(IteratorT p, IteratorT q)
{
    while (*p && *p == *q)
    {
        ++p;
        ++q;
    }
    return *p == *q;
}

template <class SymbolsT, typename CharT>
void
docheck
(
    SymbolsT const &sym,
    CharT    const *candidate,
    bool           hit,
    CharT    const *result,
    int            length
)
{
    parse_info<CharT const*> info = parse(candidate, sym);

#define correctly_matched hit == info.hit
#define correct_match_length unsigned(length) == info.length
#define correct_tail equal(candidate + (hit?1:0)*length, result)

    BOOST_TEST(correctly_matched);

    if (hit)
    {
        BOOST_TEST(correct_match_length);
        BOOST_TEST(correct_tail);
    }
    else
    {
        BOOST_TEST(correct_tail);
    }
}

template <typename T>
struct store_action
{
    store_action(T const &v) : value(v) {}
    void operator()(T &v) const { v = value; }
private:
    T const value;
};

template <typename T>
store_action<T>
store(T const &v)
{
    return v;
}

template <typename T>
struct check_action
{
    check_action(T const &v) : value(v) {}

#define correct_value_stored (v==value)
    void operator()(T const &v) const { BOOST_TEST(correct_value_stored); }
private:
    T const value;
};

template <typename T>
check_action<T>
docheck(T const &v)
{
    return v;
}

static void
default_constructible()
{   // this actually a compile time test
    symbols<>                     ns1;
    symbols<int, wchar_t>         ws1;
    symbols<std::string, char>    ns2;
    symbols<std::string, wchar_t> ws2;

    (void)ns1; (void)ws1; (void)ns2; (void)ws2;
}

static void
narrow_match_tests()
{
    symbols<>   sym;
    sym = "pineapple", "orange", "banana", "applepie", "apple";

    docheck(sym, "pineapple", true, "", 9);
    docheck(sym, "orange", true, "", 6);
    docheck(sym, "banana", true, "", 6);
    docheck(sym, "apple", true, "", 5);
    docheck(sym, "pizza", false, "pizza", -1);
    docheck(sym, "steak", false, "steak", -1);
    docheck(sym, "applepie", true, "", 8);
    docheck(sym, "bananarama", true, "rama", 6);
    docheck(sym, "applet", true, "t", 5);
    docheck(sym, "applepi", true, "pi", 5);
    docheck(sym, "appl", false, "appl", -1);

    docheck(sym, "pineapplez", true, "z", 9);
    docheck(sym, "orangez", true, "z", 6);
    docheck(sym, "bananaz", true, "z", 6);
    docheck(sym, "applez", true, "z", 5);
    docheck(sym, "pizzaz", false, "pizzaz", -1);
    docheck(sym, "steakz", false, "steakz", -1);
    docheck(sym, "applepiez", true, "z", 8);
    docheck(sym, "bananaramaz", true, "ramaz", 6);
    docheck(sym, "appletz", true, "tz", 5);
    docheck(sym, "applepix", true, "pix", 5);
}

static void
narrow_copy_ctor_tests()
{
    symbols<>   sym;
    sym = "pineapple", "orange", "banana", "applepie", "apple";

    symbols<>   sym2(sym);
    docheck(sym2, "pineapple", true, "", 9);
    docheck(sym2, "pizza", false, "pizza", -1);
    docheck(sym2, "bananarama", true, "rama", 6);
}

static void
narrow_assigment_operator_tests()
{
    symbols<>   sym;
    sym = "pineapple", "orange", "banana", "applepie", "apple";

    symbols<>   sym2;
    sym2 = sym;

    docheck(sym2, "pineapple", true, "", 9);
    docheck(sym2, "pizza", false, "pizza", -1);
    docheck(sym2, "bananarama", true, "rama", 6);
}

static void
narrow_value_tests()
{   // also tests the add member functions
    symbols<>   sym;

    sym = "orange", "banana";
    sym.add("pineapple",1234);
    sym.add("lemon");

    parse("orange", sym[store(12345)]);
    parse("orange", sym[docheck(12345)]);
    parse("pineapple", sym[docheck(1234)]);
    parse("banana", sym[docheck(int())]);
    parse("lemon", sym[docheck(int())]);
}

static void
narrow_free_functions_tests()
{
    symbols<>   sym;

#define add_returned_non_null_value (res!=0)
#define add_returned_null (res==0)
#define find_returned_non_null_value (res!=0)
#define find_returned_null (res==0)

    int *res = add(sym,"pineapple");
    BOOST_TEST(add_returned_non_null_value);
    res = add(sym,"pineapple");
    BOOST_TEST(add_returned_null);

    res = find(sym, "pineapple");
    BOOST_TEST(find_returned_non_null_value);
    res = find(sym, "banana");
    BOOST_TEST(find_returned_null);
}

static void
wide_match_tests()
{
    symbols<int, wchar_t>   sym;
    sym = L"pineapple", L"orange", L"banana", L"applepie", L"apple";

    docheck(sym, L"pineapple", true, L"", 9);
    docheck(sym, L"orange", true, L"", 6);
    docheck(sym, L"banana", true, L"", 6);
    docheck(sym, L"apple", true, L"", 5);
    docheck(sym, L"pizza", false, L"pizza", -1);
    docheck(sym, L"steak", false, L"steak", -1);
    docheck(sym, L"applepie", true, L"", 8);
    docheck(sym, L"bananarama", true, L"rama", 6);
    docheck(sym, L"applet", true, L"t", 5);
    docheck(sym, L"applepi", true, L"pi", 5);
    docheck(sym, L"appl", false, L"appl", -1);

    docheck(sym, L"pineapplez", true, L"z", 9);
    docheck(sym, L"orangez", true, L"z", 6);
    docheck(sym, L"bananaz", true, L"z", 6);
    docheck(sym, L"applez", true, L"z", 5);
    docheck(sym, L"pizzaz", false, L"pizzaz", -1);
    docheck(sym, L"steakz", false, L"steakz", -1);
    docheck(sym, L"applepiez", true, L"z", 8);
    docheck(sym, L"bananaramaz", true, L"ramaz", 6);
    docheck(sym, L"appletz", true, L"tz", 5);
    docheck(sym, L"applepix", true, L"pix", 5);
}

static void
wide_copy_ctor_tests()
{
    symbols<int, wchar_t>   sym;
    sym = L"pineapple", L"orange", L"banana", L"applepie", L"apple";

    symbols<int, wchar_t>   sym2(sym);
    docheck(sym2, L"pineapple", true, L"", 9);
    docheck(sym2, L"pizza", false, L"pizza", -1);
    docheck(sym2, L"bananarama", true, L"rama", 6);
}

static void
wide_assigment_operator_tests()
{
    symbols<int, wchar_t>   sym;
    sym = L"pineapple", L"orange", L"banana", L"applepie", L"apple";

    symbols<int, wchar_t>   sym2;
    sym2 = sym;

    docheck(sym2, L"pineapple", true, L"", 9);
    docheck(sym2, L"pizza", false, L"pizza", -1);
    docheck(sym2, L"bananarama", true, L"rama", 6);
}

static void
wide_value_tests()
{   // also tests the add member functions
    symbols<int, wchar_t>   sym;

    sym = L"orange", L"banana";
    sym.add(L"pineapple",1234);
    sym.add(L"lemon");

    parse(L"orange", sym[store(12345)]);
    parse(L"orange", sym[docheck(12345)]);
    parse(L"pineapple", sym[docheck(1234)]);
    parse(L"banana", sym[docheck(int())]);
    parse(L"lemon", sym[docheck(int())]);
}

static void
wide_free_functions_tests()
{
    symbols<int, wchar_t>   sym;

    int *res = add(sym,L"pineapple");
    BOOST_TEST(add_returned_non_null_value);
    res = add(sym,L"pineapple");
    BOOST_TEST(add_returned_null);

    res = find(sym, L"pineapple");
    BOOST_TEST(find_returned_non_null_value);
    res = find(sym, L"banana");
    BOOST_TEST(find_returned_null);
}

static
void free_add_find_functions_tests()
{
    symbols<> sym;
    BOOST_TEST(*add(sym, "a", 0) == 0);
    BOOST_TEST(*add(sym, "a2", 1) == 1);
    BOOST_TEST(find(sym, "a2"));
    BOOST_TEST(find(sym, "a"));
}

int
main()
{
    default_constructible();
    narrow_match_tests();
    narrow_copy_ctor_tests();
    narrow_assigment_operator_tests();
    narrow_value_tests();
    narrow_free_functions_tests();
    wide_match_tests();
    wide_copy_ctor_tests();
    wide_assigment_operator_tests();
    wide_value_tests();
    wide_free_functions_tests();
    free_add_find_functions_tests();
    return boost::report_errors();
}


text:
#include <fstream>
#include <iostream>
#include <string>
#include <utility>
#include <vector>
#include <map>
#include <algorithm>
#include <stdint.h>

#include "caffe/minihand/minihand_data_layer.hpp"
#include "caffe/util/benchmark.hpp"
#include "caffe/util/math_functions.hpp"
#include "caffe/util/rng.hpp"

#include <boost/foreach.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>

namespace caffe {

using namespace boost::property_tree;

template <typename Dtype>
MinihandDataLayer<Dtype>::~MinihandDataLayer<Dtype>() {
  this->StopInternalThread();
}

template <typename Dtype>
void MinihandDataLayer<Dtype>::DataLayerSetUp(const vector<Blob<Dtype>*>& bottom,
      const vector<Blob<Dtype>*>& top) {
  minihand_transformer_.reset(
     new MinihandTransformer<Dtype>(minihand_transform_param_, this->phase_));
  // 获取数据Layer参数
  const MinihandDataParameter& minihand_data_param = this->layer_param_.minihand_data_param();
  CHECK_EQ(minihand_data_param.mean_value_size(), 3);
  for (int i = 0; i < 3; ++i) {
    mean_values_.push_back(minihand_data_param.mean_value(i));
  }
  if(minihand_data_param.has_xml_list()){
    string xml_list = minihand_data_param.xml_list();
    string xml_root = minihand_data_param.xml_root();
    LOG(INFO) << "Opening file " << xml_list;
    std::ifstream infile(xml_list.c_str());
    CHECK(infile.good()) << "Failed to open file "<< xml_list;
    std::string xmlname;
    while (infile >> xmlname) {
      lines_.push_back(make_pair(xml_root, xmlname));
    }
  } else{
    LOG(INFO)<<"size of minihand_data_param.xml_list_multiple_size() "<<minihand_data_param.xml_list_multiple_size();
    for (int i=0; i<minihand_data_param.xml_list_multiple_size(); i++){
      string xml_list = minihand_data_param.xml_list_multiple(i);
      string xml_root = minihand_data_param.xml_root_multiple(i);
      LOG(INFO) << "Opening file \"" << xml_list << "\"";
      std::ifstream infile(xml_list.c_str());
      CHECK(infile.good()) << "Failed to open file "<< xml_list;
      std::string xmlname;
      while (infile >> xmlname) {
        lines_.push_back(make_pair(xml_root, xmlname));
      }
      LOG(INFO) << "Finished Reading " << xml_list;
    }
  }

  base_bindex_ = 0;
  if (minihand_data_param.has_base_bindex()){
    base_bindex_ = minihand_data_param.base_bindex();
  }

  CHECK(!lines_.empty()) << "File is empty.";
  // 随机乱序
  if (minihand_data_param.shuffle()) {
    LOG(INFO) << "Shuffling data";
    const unsigned int prefetch_rng_seed = caffe_rng_rand();
    prefetch_rng_.reset(new Caffe::RNG(prefetch_rng_seed));
    ShuffleLists();
  }
  LOG(INFO) << "A total of " << lines_.size() << " images.";
  lines_id_ = 0;
  if (minihand_data_param.rand_skip()) {
    unsigned int skip = caffe_rng_rand() % minihand_data_param.rand_skip();
    LOG(INFO) << "Skipping first " << skip << " instances.";
    CHECK_GT(lines_.size(), skip) << "Not enough points to skip";
    lines_id_ = skip;
  }

  // data
  const int batch_size = minihand_data_param.batch_size();
  const int height = minihand_transform_param_.resized_height();
  const int width = minihand_transform_param_.resized_width();
  top[0]->Reshape(batch_size, 3, height, width);
  for (int i = 0; i < this->PREFETCH_COUNT; ++i) {
    this->prefetch_[i].data_.Reshape(batch_size, 3, height, width);
  }
  LOG(INFO) << "output data size: " << top[0]->num() << ","
    << top[0]->channels() << "," << top[0]->height() << ","
    << top[0]->width();
  // label
  top[1]->Reshape(1,1,1,9);
  for (int i = 0; i < this->PREFETCH_COUNT; ++i) {
    this->prefetch_[i].label_.Reshape(1,1,1,9);
  }
  LOG(INFO) << "output label size: " << top[1]->num() << ","
    << top[1]->channels() << "," << top[1]->height() << ","
    << top[1]->width();
}

template <typename Dtype>
void MinihandDataLayer<Dtype>::ShuffleLists() {
  caffe::rng_t* prefetch_rng =
      static_cast<caffe::rng_t*>(prefetch_rng_->generator());
  shuffle(lines_.begin(), lines_.end(), prefetch_rng);
}

template <typename Dtype>
void MinihandDataLayer<Dtype>::load_batch(Batch<Dtype>* batch) {
  CHECK(batch->data_.count());
  const MinihandDataParameter& minihand_data_param = this->layer_param_.minihand_data_param();
  string xml_root = minihand_data_param.xml_root();
  string image_root = minihand_data_param.image_root();
  const int batch_size = minihand_data_param.batch_size();
  const int height = minihand_transform_param_.resized_height();
  const int width = minihand_transform_param_.resized_width();
  const int lines_size = lines_.size();
  // 输出Label
  vector<cv::Mat> all_images;   // RGB图像
  vector<vector<LabeledBBox<Dtype> > > all_bboxes;  // Labels
  // 获取batch_size个样本
  for (int item_id = 0; item_id < batch_size; ++item_id) {
    CHECK_GT(lines_size, lines_id_);
    string xml_root = lines_[lines_id_].first;
    string xml_path = xml_root + '/' + lines_[lines_id_].second;
    // Read Anno
    HandAnnoData<Dtype> anno;
    ReadHandDataFromXml(item_id, xml_path, xml_root, &anno);
    // 转换
    cv::Mat image;
    vector<LabeledBBox<Dtype> > bboxes;
    bool flag = minihand_transformer_->Transform(anno, &image, &bboxes);
    if (! flag) { // 增广失败
      item_id--;  // 回滚到下一条记录
    } else {
      all_images.push_back(image);
      all_bboxes.push_back(bboxes);
    }
    lines_id_++;
    if (lines_id_ >= lines_.size()) {
      DLOG(INFO) << "Restarting data prefetching from start.";
      lines_id_ = 0;
      if (minihand_data_param.shuffle()) {
        ShuffleLists();
      }
    }
  }
  // 检查数据完整性
  CHECK_EQ(all_images.size(), all_bboxes.size());
  CHECK_EQ(all_images.size(), batch_size);
  // 拷贝数据
  // top[0]
  batch->data_.Reshape(batch_size,3,height,width);
  Dtype* top_data = batch->data_.mutable_cpu_data();
  bool normalize = false;
  const int offset = height * width;
  for (int i = 0; i < batch_size; ++i) {
    Dtype* top_data_item = top_data + i * 3 * offset;
    cv::Mat& image = all_images[i];
    CHECK_EQ(image.rows, height);
    CHECK_EQ(image.cols, width);
    if(minihand_transform_param_.flag_eqhist()){
      vector<cv::Mat> BGR;
      cv::split(image, BGR);
      cv::equalizeHist(BGR[0],BGR[0]);
      cv::equalizeHist(BGR[1],BGR[1]);
      cv::equalizeHist(BGR[2],BGR[2]);
      cv::merge(BGR, image);
    }
    for (int y = 0; y < image.rows; ++y) {
      for (int x = 0; x < image.cols; ++x) {
        const cv::Vec3b& rgb = image.at<cv::Vec3b>(y, x);
        if (normalize) {
          top_data_item[y * image.cols + x] = (rgb[0] - 128)/256.0;
          top_data_item[offset + y * image.cols + x] = (rgb[1] - 128)/256.0;
          top_data_item[2 * offset + y * image.cols + x] = (rgb[2] - 128)/256.0;
        } else {
          top_data_item[             y * image.cols + x] = rgb[0] - mean_values_[0];
          top_data_item[    offset + y * image.cols + x] = rgb[1] - mean_values_[1];
          top_data_item[2 * offset + y * image.cols + x] = rgb[2] - mean_values_[2];
        }
      }
    }
  }
  // top[1]
  int num_gt = 0;
  for (int i = 0; i < all_bboxes.size(); ++i) {
    num_gt += all_bboxes[i].size();
  }
  CHECK_GT(num_gt, 0) << "Found No Ground-Truth.";
  batch->label_.Reshape(1,1,num_gt,9);
  Dtype* top_label = batch->label_.mutable_cpu_data();
  int idx = 0;
  for (int i = 0; i < all_bboxes.size(); ++i) {
    for (int j = 0; j < all_bboxes[i].size(); ++j) {
      LabeledBBox<Dtype>& box = all_bboxes[i][j];
      top_label[idx++] = box.bindex + base_bindex_;
      top_label[idx++] = box.cid;
      top_label[idx++] = box.pid;
      top_label[idx++] = box.is_diff;
      top_label[idx++] = box.iscrowd;
      top_label[idx++] = box.bbox.x1_;
      top_label[idx++] = box.bbox.y1_;
      top_label[idx++] = box.bbox.x2_;
      top_label[idx++] = box.bbox.y2_;
    }
  }
}

template <typename Dtype>
void MinihandDataLayer<Dtype>::ReadHandDataFromXml(const int bindex, const string& xml_file, const string& image_root,
                                                  HandAnnoData<Dtype>* anno) {
  ptree pt;
  read_xml(xml_file, pt);
  anno->image_path = image_root + '/' + pt.get<string>("Annotations.ImagePath");
  anno->image_width = pt.get<int>("Annotations.ImageWidth");
  anno->image_height = pt.get<int>("Annotations.ImageHeight");
  int num;
  try {
    num = pt.get<int>("Annotations.NumPerson");
  } catch (const ptree_error &e) {
    num = pt.get<int>("Annotations.NumPart");
  }
  anno->hands.clear();
  for (int i = 0; i < num; ++i) {
    LabeledBBox<Dtype> ins;
    char temp_cid[128];
    char temp_xmin[128], temp_ymin[128], temp_xmax[128], temp_ymax[128];
    sprintf(temp_cid, "Annotations.Object_%d.cid", i+1);
    sprintf(temp_xmin, "Annotations.Object_%d.xmin", i+1);
    sprintf(temp_ymin, "Annotations.Object_%d.ymin", i+1);
    sprintf(temp_xmax, "Annotations.Object_%d.xmax", i+1);
    sprintf(temp_ymax, "Annotations.Object_%d.ymax", i+1);
    // bindex & cid & pid
    ins.bindex = bindex;
    ins.cid = pt.get<int>(temp_cid);
    // NOTE: 只提取cid == 1 的记录
    //if (ins.cid != 1) continue;
    // bbox: must be defined
    ins.bbox.x1_ = pt.get<Dtype>(temp_xmin);
    ins.bbox.y1_ = pt.get<Dtype>(temp_ymin);
    ins.bbox.x2_ = pt.get<Dtype>(temp_xmax);
    ins.bbox.y2_ = pt.get<Dtype>(temp_ymax);
    // 默认score = 1
    ins.score = 1;
    anno->hands.push_back(ins);
  }
  anno->num_hands = anno->hands.size();
}

INSTANTIATE_CLASS(MinihandDataLayer);
REGISTER_LAYER_CLASS(MinihandData);
}  // namespace caffe


text:
// Boost.Geometry (aka GGL, Generic Geometry Library)
//
// Copyright (c) 2015 Barend Gehrels, Amsterdam, the Netherlands.

// 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)

#ifndef BOOST_GEOMETRY_ALGORITHMS_INVERSE_HPP
#define BOOST_GEOMETRY_ALGORITHMS_INVERSE_HPP

#include <boost/geometry.hpp>

namespace boost { namespace geometry
{

// TODO: this is shared with sectionalize, move to somewhere else (assign?)
template <typename Box, typename Value>
inline void enlarge_box(Box& box, Value value)
{
    geometry::set<0, 0>(box, geometry::get<0, 0>(box) - value);
    geometry::set<0, 1>(box, geometry::get<0, 1>(box) - value);
    geometry::set<1, 0>(box, geometry::get<1, 0>(box) + value);
    geometry::set<1, 1>(box, geometry::get<1, 1>(box) + value);
}

// TODO: when this might be moved outside extensions it should of course
// input/output a Geometry, instead of a WKT
template <typename Geometry, typename Value>
inline std::string inverse(std::string const& wkt, Value margin)
{
    Geometry geometry;
    read_wkt(wkt, geometry);

    geometry::correct(geometry);

    geometry::model::box<typename point_type<Geometry>::type> env;
    geometry::envelope(geometry, env);

    // Make its envelope a bit larger
    enlarge_box(env, margin);

    Geometry env_as_polygon;
    geometry::convert(env, env_as_polygon);

    Geometry inversed_result;
    geometry::difference(env_as_polygon, geometry, inversed_result);

    std::ostringstream out;

    out << geometry::wkt(inversed_result);
    return out.str();
}

}} // namespace boost::geometry

#endif // BOOST_GEOMETRY_ALGORITHMS_INVERSE_HPP


text:
#include "cxxopts.hpp"

// see https://www.gitmemory.com/issue/ddemidov/amgcl/162/668662041 for inspiration

#include <amgcl/io/mm.hpp>
#include <amgcl/adapter/crs_tuple.hpp>
#include <amgcl/amg.hpp>

#if defined(SOLVER_BACKEND_VEXCL)
#  include <amgcl/value_type/static_matrix.hpp>
#  include <amgcl/adapter/block_matrix.hpp>
#  include <amgcl/backend/vexcl.hpp>
#  include <amgcl/backend/vexcl_static_matrix.hpp>
   typedef amgcl::backend::vexcl<double> Backend;
#elif defined(SOLVER_BACKEND_CUDA)
#  include <amgcl/adapter/eigen.hpp>
#  include <amgcl/backend/cuda.hpp>
#  include <amgcl/relaxation/cusparse_ilu0.hpp>
   using Backend = amgcl::backend::cuda<double>;
#else
   using Backend = amgcl::backend::builtin<double>;
#endif

#include <amgcl/make_solver.hpp>
#include <amgcl/make_block_solver.hpp>
#include <amgcl/solver/bicgstab.hpp>
#include <amgcl/solver/gmres.hpp>
#include <amgcl/solver/runtime.hpp>
#include <amgcl/preconditioner/runtime.hpp>
#include <amgcl/amg.hpp>
#include <amgcl/coarsening/smoothed_aggregation.hpp>
#include <amgcl/coarsening/plain_aggregates.hpp>
#include <amgcl/coarsening/ruge_stuben.hpp>
#include <amgcl/coarsening/aggregation.hpp>
#include <amgcl/relaxation/spai0.hpp>
#include <amgcl/relaxation/ilu0.hpp>
#include <amgcl/adapter/crs_tuple.hpp>
#include <boost/program_options.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>

// ./amgcl-block-matrices -A ../data/B_test.mtx  -b 3

#include <amgcl/profiler.hpp>

namespace amgcl { profiler<> prof; }
using amgcl::prof;
using amgcl::precondition;

//---------------------------------------------------------------------------
std::tuple<size_t, double> scalar_solve(
        const boost::property_tree::ptree &prm,
        size_t rows,
        std::vector<ptrdiff_t> const &ptr,
        std::vector<ptrdiff_t> const &col,
        std::vector<double>    const &val,
        std::vector<double>    const &rhs,
        std::vector<double>          &x,
        bool reorder
        )
{
    Backend::params bprm;
    // We use the tuple of CRS arrays to represent the system matrix.
    // Note that std::tie creates a tuple of references, so no data is actually
    // copied here:
    auto A = std::tie(rows, ptr, col, val);

#if defined(SOLVER_BACKEND_VEXCL)
    vex::Context ctx(vex::Filter::Env);
    std::cout << ctx << std::endl;
    bprm.q = ctx;
#elif defined(SOLVER_BACKEND_VIENNACL)
    std::cout
        << viennacl::ocl::current_device().name()
        << " (" << viennacl::ocl::current_device().vendor() << ")\n\n";
#elif defined(SOLVER_BACKEND_CUDA)
    cusparseCreate(&bprm.cusparse_handle);
    {
        int dev;
        cudaGetDevice(&dev);

        cudaDeviceProp prop;
        cudaGetDeviceProperties(&prop, dev);
        std::cout << prop.name << std::endl << std::endl;
    }
#endif

    using Solver1 = amgcl::make_solver<
    amgcl::runtime::preconditioner<Backend>,
    amgcl::runtime::solver::wrapper<Backend>>;

    //using Solver2 = amgcl::make_block_solver<
    using Solver2 = amgcl::make_solver<
    // Use AMG as preconditioner:
    amgcl::amg<
        Backend,
        amgcl::coarsening::smoothed_aggregation,
        //amgcl::relaxation::spai0
        amgcl::relaxation::damped_jacobi
        >,
    // And BiCGStab as iterative solver:
    amgcl::solver::bicgstab<Backend>>;

    using Solver3 = amgcl::make_solver<
    // Use AMG as preconditioner:
    amgcl::amg<
        Backend,
        amgcl::coarsening::ruge_stuben,
        amgcl::relaxation::spai0
        //amgcl::relaxation::ilu0
        >,
    // And GMRES as iterative solver:
    amgcl::solver::gmres<Backend>>;

    try {
        Solver2::params prm;
        Solver2::backend_params bprm;
        // prm.precond.direct_coarse = false;
        prm.precond.direct_coarse = true;
        prm.solver.maxiter = 1200;
        prm.solver.verbose = true;
        prm.solver.tol = 1e-5;
        //prm.precond.coarsening ...

#if defined(SOLVER_BACKEND_VEXCL)
        vex::Context ctx(vex::Filter::Env);
        std::cout << ctx << std::endl;
        bprm.q = ctx;
#elif defined(SOLVER_BACKEND_VIENNACL)
        std::cout
            << viennacl::ocl::current_device().name()
            << " (" << viennacl::ocl::current_device().vendor() << ")\n\n";
#elif defined(SOLVER_BACKEND_CUDA)
        cusparseCreate(&bprm.cusparse_handle);
        {
            int dev;
            cudaGetDevice(&dev);

            cudaDeviceProp prop;
            cudaGetDeviceProperties(&prop, dev);
            std::cout << prop.name << std::endl << std::endl;
        }
#endif

        Solver2 solve( A, prm, bprm );

        auto f_b = Backend::copy_vector(rhs, bprm);
        auto x_b = Backend::copy_vector(x,   bprm);

        //auto [iters, error] = solve(A, rhs, x);
        auto [iters, error] = solve(A, *f_b, *x_b);

#if defined(SOLVER_BACKEND_VEXCL)
        vex::copy(*x_b, x);
#elif defined(SOLVER_BACKEND_VIENNACL)
        viennacl::fast_copy(*x_b, x);
#elif defined(SOLVER_BACKEND_CUDA)
        thrust::copy(x_b->begin(), x_b->end(), x.begin());
#else
        std::copy(&(*x_b)[0], &(*x_b)[0] + rows, &x[0]);
#endif

        // Output the number of iterations, the relative error:
        std::cout << "Iters: " << iters << std::endl
                  << "Error: " << error << std::endl;
        // std::cout << "x = [ ";
        // for (auto el : x) {
        //     std::cout << el << ", ";
        // }
        // std::cout << "]\n";
        return {iters, error};
    } catch(std::runtime_error &e) {
        std::cout << "caught exception: " << e.what() << std::endl;
    }

    return {0, 0.0};
}

int main(int argc, char *argv[])
{
    //namespace po = boost::program_options;
    namespace io = amgcl::io;

    using std::vector;
    using std::string;

    cxxopts::Options options("amgcl_block_matrices", "check AMG for different block sizes");
    options
        .allow_unrecognised_options()
        .add_options()
        ("A,matrix", "System matrix in the MatrixMarket format.",
         cxxopts::value<std::string>())
        ("b,block-size", "The block size of the system matrix. ",
         cxxopts::value<int>()->default_value("1"))
        ("h,help", "Print help")
        ;

    auto vm = options.parse(argc, argv);

    if (vm.count("help")) {
        std::cout << options.help() << std::endl;
        return 0;
    }

    for (int i = 0; i < argc; ++i) {
        if (i) std::cout << " ";
        std::cout << argv[i];
    }
    std::cout << std::endl;

    boost::property_tree::ptree prm;
    if (vm.count("prm-file")) {
        read_json(vm["prm-file"].as<string>(), prm);
    }

    if (vm.count("prm")) {
        for(const string &v : vm["prm"].as<vector<string>>()) {
            amgcl::put(prm, v);
        }
    }

    size_t n, block_size = 1;
    vector<ptrdiff_t> ptr, col;
    vector<double> val;

    if (vm.count("block-size")) {
        block_size = vm["block-size"].as<int>();
    }

    if (vm.count("matrix")) {
        string Afile  = vm["matrix"].as<string>();
        auto [rows, cols] = io::mm_reader(Afile)(ptr, col, val);

        std::cout << "rows: " << rows << std::endl;
        std::cout << "cols: " << cols << std::endl;
        n = rows;
    }

    // We use the tuple of CRS arrays to represent the system matrix.
    // Note that std::tie creates a tuple of references, so no data is actually
    // copied here:
    auto A = std::tie(n, ptr, col, val);
    std::vector<double> rhs (n, 0.0);
    std::vector<double> x   (n, 0.0);

    // Set RHS := Ax where x = 1
    for (size_t i = 0; i < n; ++i) {
        double s = 0;
        for (ptrdiff_t j = ptr[i], e = ptr[i+1]; j < e; ++j) {
            s += val[j];
        }
        rhs[i] = s;
    }

    if (block_size == 1) { // scalar case
        scalar_solve(prm, n, ptr,col, val, rhs, x, false);
    } else {
        // Compose the solver type
        constexpr size_t B = 6; // 3
        using dmat_type = amgcl::static_matrix<double, B, B>;
        using dvec_type = amgcl::static_matrix<double, B, 1>;
        using SBackend = amgcl::backend::builtin<double>;    // the outer iterative solver backend
        using PBackend = amgcl::backend::builtin<float>;     // the PSolver backend
        using UBackend = amgcl::backend::builtin<dmat_type>; // the USolver backend
        using BlockSolver = amgcl::make_block_solver<
                // preconditioner
                amgcl::amg<
                    UBackend,
                    amgcl::coarsening::aggregation,
                    amgcl::relaxation::ilu0
                    >,
                // solver
                amgcl::solver::gmres<UBackend>>;
        using Solver = amgcl::make_solver<
                // preconditioner
                amgcl::amg<
                    UBackend,
                    amgcl::coarsening::aggregation,
                    amgcl::relaxation::ilu0
                    >,
                // solver
                amgcl::solver::gmres<UBackend>>;
        try {
            // see `tutorial/3.CoupCons3D/coupcons3d.cpp`
#if 1
            BlockSolver::params prm;
            prm.solver.maxiter = 1200;
            prm.solver.verbose = true;
            BlockSolver::backend_params bprm;
            prm.precond.direct_coarse = false;
            prm.precond.allow_rebuild = true;
            auto Ab = amgcl::adapter::block_matrix<dmat_type>(A);
            auto rhsb = reinterpret_cast<dvec_type*>(rhs.data());
            auto xb = reinterpret_cast<dvec_type*>(x.data());
            auto RHS = amgcl::make_iterator_range(rhsb, rhsb + n / 3);
            auto X = amgcl::make_iterator_range(xb, xb + n / block_size);
            Solver solve0( Ab, prm, bprm );
            auto [iters0, error0] = solve0(Ab, RHS, X);
            std::cout << "Iters0: " << iters0 << std::endl
                      << "Error0: " << error0 << std::endl;

            BlockSolver solve( A, prm, bprm );
            auto [iters, error] = solve(A, rhs, x);

            std::cout << "Iters: " << iters << std::endl
                      << "Error: " << error << std::endl;
            // std::cout << "x = [ ";
            // for (auto el : x) {
            //     std::cout << el << ", ";
            // }
            // std::cout << "]\n";
#endif
        } catch(std::runtime_error &e) {
            std::cout << "caught exception: " << e.what() << std::endl;
        }
    }
}

max_stars_repo_name: alsam/cpp-samples

max_issues_repo_name: alsam/cpp-samples

max_forks_repo_name: alsam/cpp-samples


text:
////////////////////////////////////////////////////////////////////////////////
// IncompressibleBalloonEnergyWithHessProjection.hh
////////////////////////////////////////////////////////////////////////////////
/*! @file
//  Implementation of the incompressible neo-Hookean-based strain energy
//  density used in Skouras 2014: Designing Inflatable Structures, expressed
//  in terms of the 3x2 deformation gradient F instead of the 2x2 Cauchy-Green
//  deformation tensor F^T F. We also provide analytical expressions for the
//  eigenvalues and eigenvectors of the Hessian (wrt F), enabling Hessian
//  projection to resolve indefiniteness.
*/
//  Author:  Julian Panetta (jpanetta), julian.panetta@gmail.com
//  Created:  07/09/2019 10:56:53
////////////////////////////////////////////////////////////////////////////////
#ifndef INCOMPRESSIBLEBALLOONENERGYWITHHESSPROJECTION_HH
#define INCOMPRESSIBLEBALLOONENERGYWITHHESSPROJECTION_HH

#include <Eigen/Dense>
#include <array>

template<typename Real>
struct IncompressibleBalloonEnergyWithHessProjection {
    using V2d  = Eigen::Matrix<Real, 2, 1>;
    using M2d  = Eigen::Matrix<Real, 2, 2>;
    using M3d  = Eigen::Matrix<Real, 3, 3>;
    using M32d = Eigen::Matrix<Real, 3, 2>;

    IncompressibleBalloonEnergyWithHessProjection() { }

    template<typename Derived>
    IncompressibleBalloonEnergyWithHessProjection(const Eigen::MatrixBase<Derived> &F) { setF(F); }

    template<typename Derived>
    void setF(const Eigen::MatrixBase<Derived> &F) {
        static_assert((Derived::RowsAtCompileTime == 3) && (Derived::ColsAtCompileTime == 2), "F must be 3x2");
        m_F = F.template cast<Real>();

        Eigen::JacobiSVD<M32d> svd(m_F, Eigen::ComputeFullU | Eigen::ComputeFullV);
        m_sigma = svd.singularValues();
        m_V = svd.matrixV();
        m_U = svd.matrixU();

        m_det32_F = m_sigma.prod();
        m_det_C = m_det32_F * m_det32_F;

        m_d_det32_F = (m_U.col(0) * m_sigma[1] * m_V.col(0).transpose() +
                       m_U.col(1) * m_sigma[0] * m_V.col(1).transpose());

        m_trace_C = m_F.squaredNorm();

        m_d_psi_ddet = -2.0 / (m_det_C * m_det32_F);

        // Compute eigendecomposition of det32_F's Hessian
        /* static constexpr */ const Real inv_sqrt2 = 1.0 / std::sqrt(2.0); // std::sqrt is not constexpr!

        // T = U [0 -1; 1 0; 0 0] V^T / sqrt(2)
        m_eigmat[2] = (-inv_sqrt2 * m_U.col(0)) * m_V.col(1).transpose() +
                       (inv_sqrt2 * m_U.col(1)) * m_V.col(0).transpose();
        m_eigval[2] = 2.0 + m_d_psi_ddet;
        // L = U [0 1; 1 0; 0 0] V^T / sqrt(2)
        m_eigmat[3] = (inv_sqrt2 * m_U.col(0)) * m_V.col(1).transpose() +
                      (inv_sqrt2 * m_U.col(1)) * m_V.col(0).transpose();
        m_eigval[3] = 2.0 - m_d_psi_ddet;
        // NX = U [0 0; 0 0; 1 0] V^T
        m_eigmat[4] = m_U.col(2) * m_V.col(0).transpose();
        m_eigval[4] = 2.0 + m_d_psi_ddet * m_sigma[1] / m_sigma[0];
        // NY = U [0 0; 0 0; 0 1] V^T
        m_eigmat[5] = m_U.col(2) * m_V.col(1).transpose();
        m_eigval[5] = 2.0 + m_d_psi_ddet * m_sigma[0] / m_sigma[1];

        // The "R" and "P" modes [1 0; 0 1; 0 0] and [1 0; 0 -1; 0 0]
        // are not orthogonal to d_det32_F and thus will not
        // be eigenmatrices of the energy density Hessian (after addition of the
        // rank 1 term proportional to (d_det32_F otimes d_det32_F)).
        // We need to compute the compute the eigendecomposition of the Hessian
        // in this subspace by solving a 2x2 matrix eigenvalue problem.
        // We first probe the Hessian with an orthonormal basis for this space:
        //      d0 := U [1, 0; 0, 0; 0, 0] V^T and d1 := U [0, 1; 0, 0; 0, 0] V^T
        // to obtain the reduced Hessian:
        //      A_ij = di : d2psi / dF2 : dj
        //  A = 2 I + 1 / det(c)^2 [6 sigma_2^2  4 det32_F  ]
        //                         [4 det32_F    6 sigma_1^2]
        // Whose eigendecomposition is:
        Real e = 3 * (m_sigma[1] * m_sigma[1] - m_sigma[0] * m_sigma[0]),
             x = std::sqrt(16 * m_det_C + e * e);
        Eigen::Vector2d v0(e - x, 4 * m_det32_F),
                        v1(e + x, 4 * m_det32_F);
        v0.normalize();
        v1.normalize();
        m_eigmat[0] = (v0[0] * m_U.col(0)) * m_V.col(0).transpose() +
                      (v0[1] * m_U.col(1)) * m_V.col(1).transpose();
        m_eigmat[1] = (v1[0] * m_U.col(0)) * m_V.col(0).transpose() +
                      (v1[1] * m_U.col(1)) * m_V.col(1).transpose();
        m_eigval[0] = 2 + (3 * m_trace_C - x) / (m_det_C * m_det_C);
        m_eigval[1] = 2 + (3 * m_trace_C + x) / (m_det_C * m_det_C);
    }

    Real energy() const {
        return stiffness * (m_trace_C + 1.0 / m_det_C - 3.0);
    }

    M32d denergy() const {
        return 2 * m_F + m_d_psi_ddet * m_d_det32_F;
    }

    template<class DeltaF>
    Real denergy(const DeltaF &dF) const {
        const Real d_det32_F = m_sigma[1] * m_U.col(0).dot(dF * m_V.col(0)) +
                               m_sigma[0] * m_U.col(1).dot(dF * m_V.col(1));

        return 2.0 * doubleContract(m_F, dF) + m_d_psi_ddet * d_det32_F;
    }

    template<class DeltaF>
    M32d delta_denergy(const DeltaF &dF) const {
        M32d result(M32d::Zero());
        for (size_t i = 0; i < 6; ++i) {
            if (applyHessianProjection && (m_eigval[i] <= 0)) continue;
            result += (m_eigval[i] * doubleContract(m_eigmat[i], dF)) * m_eigmat[i];
        }

        return result;
    }

    template<class DeltaF>
    Real d2energy(const DeltaF &dF_a, const DeltaF &dF_b) const {
        return doubleContract(delta_denergy(dF_a), dF_b);
    }

    Real stiffness = 1.0;

    // Whether to project d2energy/denergy onto the space of positive semi-semidefinite tensors.
    bool applyHessianProjection = false;

    EIGEN_MAKE_ALIGNED_OPERATOR_NEW
private:
    // We need the singular value decomposition for our gradient/Hessian formulas.
    M32d m_F, m_d_det32_F;

    // Eigenmatrices of the determinant: "R", "P", "T", "L", "NX", and "NY"
    std::array<M32d, 6> m_eigmat;
    std::array<Real, 6> m_eigval;

    M2d  m_V;
    M3d  m_U;
    V2d  m_sigma;
    Real m_trace_C, m_det32_F, m_det_C, m_d_psi_ddet;
};

#endif /* end of include guard: INCOMPRESSIBLEBALLOONENERGYWITHHESSPROJECTION_HH */

ext: hh

max_stars_repo_name: jpanetta/Inflatables

max_issues_repo_name: jpanetta/Inflatables

max_forks_repo_name: jpanetta/Inflatables


text:
#include "parsers.hpp"

#include <boost/filesystem/fstream.hpp>
#include <boost/preprocessor/stringize.hpp>
#include <sstream>
#include <iostream>
#include <vector>

#include <graphene/chain/genesis_state.hpp>

#include <graphene/chain/protocol/fee_schedule.hpp>
#include <fc/io/json.hpp>

namespace playchain {
namespace util {

using graphene::chain::public_key_type;
using graphene::chain::share_type;
using graphene::chain::address;

using graphene::chain::genesis_state_type;
using account_type = genesis_state_type::initial_account_type;
using balance_type = genesis_state_type::initial_balance_type;

struct user_info
{
    public_key_type key;
    bool single_key = true;
    share_type balance;
};
}
}

FC_REFLECT(playchain::util::user_info, (key)(single_key)(balance))

namespace playchain {
namespace util {

using graphene::chain::chain_id_type;

void load(const std::string& path, genesis_state_type& genesis)
{
    boost::filesystem::path path_to_load(path);
    FC_ASSERT(boost::filesystem::exists(path_to_load), "Path ${p} does not exists.", ("p", path_to_load.string()));

    path_to_load.normalize();

    ilog("Loading ${file}.", ("file", path_to_load.string()));

    boost::filesystem::ifstream fl;
    fl.open(path_to_load.string(), std::ios::in);

    FC_ASSERT((bool)fl, "Can't read file ${p}.", ("p", path_to_load.string()));

    std::stringstream ss;

    ss << fl.rdbuf();

    fl.close();

    genesis = fc::json::from_string(ss.str()).as<genesis_state_type>(20);
}

void check_users(const genesis_state_type& genesis, const std::vector<std::string>& users)
{
    ilog("Checking users '${users}'.", ("users", users));
    std::map<std::string, user_info> checked_users;
    for (const auto& user : users)
    {
        account_type initial_account;
        for (const auto& account : genesis.initial_accounts)
        {
            if (account.name == user)
            {
                initial_account = account;
                break;
            }
        }

        if (!initial_account.name.empty())
        {
            for (const auto& balance : genesis.initial_balances)
            {
                if (balance.owner == address{initial_account.active_key})
                {
                    auto &info = checked_users[initial_account.name];
                    info.balance = balance.amount;
                    info.key = initial_account.active_key;
                    info.single_key = (initial_account.active_key == initial_account.owner_key);
                    break;
                }
            }
        }
    }
    for (const auto& info : checked_users)
    {
        ilog("${user}: ${info}", ("user", info.first)("info", info.second));
    }
    FC_ASSERT(checked_users.size() == users.size(), "Not all users from list exist in genesis");
}

void save_to_string(genesis_state_type& genesis, std::string& output_json, bool pretty_print)
{
    fc::variant vo;
    fc::to_variant(genesis, vo, 20);

    if (pretty_print)
    {
        output_json = fc::json::to_pretty_string(vo);
        output_json.append("\n");
    }
    else
    {
        output_json = fc::json::to_string(vo);
    }
}

void save_to_file(genesis_state_type& genesis, const std::string& path, bool pretty_print)
{
    std::string output_json;
    save_to_string(genesis, output_json, pretty_print);

    boost::filesystem::path path_to_save(path);

    path_to_save.normalize();

    ilog("Saving ${file}.", ("file", path_to_save.string()));

    boost::filesystem::ofstream fl;
    fl.open(path_to_save);

    FC_ASSERT((bool)fl, "Can't write to file ${p}.", ("p", path_to_save.string()));

    fl << output_json;
    fl.close();
}

void print(genesis_state_type& genesis, bool pretty_print)
{
    std::string output_json;
    save_to_string(genesis, output_json, pretty_print);
    std::cout << output_json << std::endl;
}
}
}

max_stars_repo_name: totalgames/playchain-core

max_issues_repo_name: totalgames/playchain-core

max_forks_repo_name: totalgames/playchain-core


text:
#ifndef HERMIT_URI_HPP
#define HERMIT_URI_HPP

#include <string>
#include <vector>
#include <cstdint>
#include <boost/optional.hpp>
#include <boost/variant.hpp>
#include <boost/fusion/adapted/struct/adapt_struct.hpp>
#include <boost/fusion/include/adapt_struct.hpp>
#include <hermit/integer.hpp>
#include <hermit/ip.hpp>

namespace hermit {
  typedef boost::variant< ipv4, ipv6, std::string > host;
  struct authority {
    std::vector< std::string > userinfo;
    hermit::host host;
    boost::optional< uint16_t > port;
  };
  struct path {
    bool absolute;
    std::vector< std::string > segments;
  };
  struct uri {
    std::string scheme;
    boost::optional< hermit::authority > authority;
    hermit::path path;
    boost::optional< std::string > query;
    boost::optional< std::string > fragment;
  };
}

BOOST_FUSION_ADAPT_STRUCT(
  hermit::authority,
  (std::vector< std::string >, userinfo)
  (hermit::host, host)
  (boost::optional< uint16_t >, port)
)

BOOST_FUSION_ADAPT_STRUCT(
  hermit::path,
  (bool, absolute)
  (std::vector< std::string >, segments)
)

BOOST_FUSION_ADAPT_STRUCT(
  hermit::uri,
  (std::string, scheme)
  (boost::optional< hermit::authority >, authority)
  (hermit::path, path)
  (boost::optional< std::string >, query)
  (boost::optional< std::string >, fragment)
)

#endif

max_stars_repo_name: Fadis/hermit

max_issues_repo_name: Fadis/hermit

max_forks_repo_name: Fadis/hermit