text:
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <array>
#include <valarray>
#include <algorithm>
#include <numeric>
#include <boost/format.hpp>
extern "C" {
    #include <sys/mman.h>
    #include <sys/stat.h>
    #include <sys/types.h>
    #include <fcntl.h>
    #include <unistd.h>
}

char const * const file_name = "/Users/arnold/Downloads/CentOS-7-x86_64-DVD-1708.iso";
//char const * const file_name = "/Users/arnold/Downloads/SmartSwitch_for_Mac.dmg";

template<typename T, typename D, typename S = bool(&)(T)>
class AutoHandle {
public:
    AutoHandle(const T& handle, D&& deleter, S&& success)
    : handle_{handle}
    , deleter_{std::forward<D>(deleter)}
    , success_{success(handle_)}
    {
        std::cout << "AutoHandle(const T& handle, D&& deleter, S&& success)" << std::endl;
        if (!success_) {
            throw "Fehler";
        }
    }
    // AutoHandle(const T& handle, D&& deleter, bool(*success)(T) = nullptr)
    // : handle_{handle}
    // , deleter_{std::forward<D>(deleter)}
    // , success_{success != nullptr ? success(handle_) : true}
    // {
    //     std::cout << "AutoHandle(const T& handle, D&& deleter, bool(*success)(T) = nullptr) " << std::endl;
    //     if (!success_) {
    //         throw "Fehler";
    //     }
    // }
    AutoHandle(const AutoHandle&) = delete;
    AutoHandle(AutoHandle&& ah)
    : handle_{ah.handle_}
    , deleter_{std::forward<D>(ah.deleter_)}
    , success_{ah.success_}
    {
        ah.success_ = false;
    }
    ~AutoHandle() noexcept {
        if (success_) {
            deleter_(handle_);
        }
    }
    AutoHandle& operator=(const AutoHandle&) = delete;
    operator const T&() const noexcept { return handle_; }
    const T& get() const noexcept { return handle_; }
private:
    const T handle_;
    const D& deleter_;
    bool success_ { false };
};

// class MappedFile {
// public:
//     static bool check_fd(int i) { std::cout << "check_fd(int i)" << std::endl; return i > -1;  }
//     static bool check_mm(void* p) { std::cout << "check_mm(void* p)" << std::endl; return p != MAP_FAILED;  }

//     MappedFile(char const * const file_name)
//     : file_name(file_name)
//     {

//     }
//     MappedFile(const MappedFile&) = delete;
//     MappedFile(MappedFile&& mf)
//     {}
//     ~MappedFile();

// private:
//      const std::string&                     file_name_;
//      struct stat                            st_;
//      AutoHandle<int, decltype(close)>       ahF_;
//      AutoHandle<void*, decltype(fct_unmap)> ahMM_;
// };

bool check_fd(int i) { std::cout << "check_fd(int i)" << std::endl; return i > -1;  }
bool check_mm(void* p) { std::cout << "check_mm(void* p)" << std::endl; return p != MAP_FAILED;  }

std::valarray<size_t> build_hist(uint8_t const * begin, uint8_t const * end) {
    std::valarray<size_t> hist(0x100);
    hist = 0;
    std::for_each( begin
                 , end
                 , [&hist](const uint8_t& e) { ++hist[e]; } );
    return hist;
}

int main(int argc, char const *argv[])
{
    int ret = 0;
    char const* fname = file_name;
    if (argc > 1)
        fname = argv[1];
    std::ios_base::sync_with_stdio(false);
    try {
        AutoHandle<int, decltype(close)> ahF(open(fname, O_RDONLY), close, check_fd);
        struct stat st;
        fstat(ahF, &st);
        std::cout << "file size: " << st.st_size << std::endl;
        const auto fct_unmap = [st](void* p){munmap(p, st.st_size);};
        AutoHandle<void*, decltype(fct_unmap)> ahMM(
              mmap(nullptr, st.st_size, PROT_READ, MAP_PRIVATE | MAP_FILE, ahF, 0)
            , std::forward<decltype(fct_unmap)>(fct_unmap)
            , check_mm);
        std::cout << "Ptr: " << ahMM.get() << std::endl;
        auto hist = build_hist( static_cast<uint8_t const *>(ahMM.get())
                              , static_cast<uint8_t const *>(ahMM.get()) + st.st_size);
        float sum = static_cast<float>(hist.sum());
        std::array<float, 0x100> histpcnt;
        std::transform(std::begin(hist), std::end(hist), std::begin(histpcnt)
            , [sum](const size_t& i){ return i / sum * 100.0f; }
            );
        boost::format fmt{"%02x: %7d (%04.1f%%)"};
        for(auto i = 0; i < hist.size(); ++i) {
            std::cout << fmt % i % hist[i] % histpcnt[i]
                      << ((i % 8 == 7) ? "\n" : "  ");
        }
    } catch(char const * const e) {
        std::cout << "Fehler: " << e << std::endl;
    }
    return ret;
}

max_stars_repo_name: noeld/cpp

max_issues_repo_name: noeld/cpp

max_forks_repo_name: noeld/cpp


text:
// Copyright 2019 Lawrence Livermore National Security, LLC and other Metall Project Developers.
// See the top-level COPYRIGHT file for details.
//
// SPDX-License-Identifier: (Apache-2.0 OR MIT)

#ifndef METALL_EXAMPLE_GRAPH_DATA_STRUCTURE_CSR_USING_VECTOR_HPP
#define METALL_EXAMPLE_GRAPH_DATA_STRUCTURE_CSR_USING_VECTOR_HPP

#include <memory>
#include <boost/container/vector.hpp>

namespace bc = boost::container;

/// \brief Simple CSR graph data structure that can take a custom C++ allocator and be stored in persistent memory
/// This class uses vector containers to allocate internal arrays.
/// \tparam index_t Index type
/// \tparam vid_t Vertex ID type
/// \tparam allocator_t Allocator type
template <typename index_t = uint64_t, typename vid_t = uint64_t, typename allocator_t = std::allocator<char>>
class csr_using_vector {
 private:
  // Here, we declare allocator and vector types we need.
  // To store the indices array and edges array in persistent memory,
  // we have to pass the allocator type (allocator_t) to the vectors.

  // Allocator and vector types for the indices array
  using index_allocator_t = typename std::allocator_traits<allocator_t>::template rebind_alloc<index_t>;
  using index_vector_t = bc::vector<index_t, index_allocator_t>;

  // Allocator and vector types for the edges array
  using edge_allocator_t = typename std::allocator_traits<allocator_t>::template rebind_alloc<vid_t>;
  using edge_vector_t = bc::vector<vid_t, edge_allocator_t>;

 public:
  csr_using_vector(const std::size_t num_vertices, const std::size_t num_edges, allocator_t allocator = allocator_t())
      : m_num_vertices(num_vertices),
        m_num_edges(num_edges),
        m_indices(m_num_vertices + 1, allocator),
        m_edges(m_num_edges, allocator) {}

  /// \brief Returns a raw pointer to the indices array
  index_t *indices() {
    return m_indices.data();
  }

  /// \brief Returns a raw pointer to the edges array
  vid_t *edges() {
    return m_edges.data();
  }

 private:
  const std::size_t m_num_vertices;
  const std::size_t m_num_edges;
  index_vector_t m_indices;
  edge_vector_t m_edges;
};

#endif //METALL_EXAMPLE_GRAPH_DATA_STRUCTURE_CSR_USING_VECTOR_HPP

ext: hpp

max_stars_repo_name: dice-group/metall

max_issues_repo_name: dice-group/metall

max_forks_repo_name: dice-group/metall


text:
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */

/*
 Copyright (C) 2015 Peter Caspers

 This file is part of QuantLib, a free-software/open-source library
 for financial quantitative analysts and developers - http://quantlib.org/

 QuantLib is free software: you can redistribute it and/or modify it
 under the terms of the QuantLib license.  You should have received a
 copy of the license along with this program; if not, please email
 <quantlib-dev@lists.sf.net>. The license is also available online at
 <http://quantlib.org/license.shtml>.

 This program is distributed in the hope that it will be useful, but WITHOUT
 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 FOR A PARTICULAR PURPOSE.  See the license for more details.
*/

#include <ql/experimental/volatility/stickybpvolswaptioncube.hpp>
#include <ql/experimental/volatility/multiplicativesmilesection.hpp>
#include <ql/math/interpolations/bilinearinterpolation.hpp>
#include <ql/math/interpolations/flatextrapolation2d.hpp>
#include <ql/quotes/simplequote.hpp>

#include <boost/make_shared.hpp>

namespace QuantLib {

StickyBpVolSwaptionCube::StickyBpVolSwaptionCube(
    const boost::shared_ptr<SwaptionVolatilityCube> &sourceCube,
    Handle<Quote> atmVolatilitySpread)
    : SwaptionVolatilityCube(
          sourceCube->atmVol(), sourceCube->optionTenors(),
          sourceCube->swapTenors(), sourceCube->strikeSpreads(),
          sourceCube->volSpreads(), sourceCube->swapIndexBase(),
          sourceCube->shortSwapIndexBase(), sourceCube->vegaWeightedSmileFit()),
      sourceCube_(sourceCube),
      atmVolatilitySpread_(atmVolatilitySpread) {

    registerWith(sourceCube_);
    registerWith(atmVolatilitySpread_);

    boost::shared_ptr<SwaptionVolatilityDiscrete> atm =
        boost::dynamic_pointer_cast<SwaptionVolatilityDiscrete>(
            *sourceCube->atmVol());

    // this should never happen (?)
    QL_REQUIRE(atm != NULL, "atm is not of type SwaptionVolatilityDiscrete");

    atmLevel_ = Matrix(optionDates().size(), swapTenors().size());

    for (Size j = 0; j < atm->swapTenors().size(); ++j)
        for (Size i = 0; i < atm->optionDates().size(); ++i)
            atmLevel_[i][j] = sourceCube->atmStrike(atm->optionDates()[i],
                                                    atm->swapTenors()[j]);

    originalAtm_ = FlatExtrapolator2D(boost::make_shared<BilinearInterpolation>(
        atm->swapLengths().begin(), atm->swapLengths().end(),
        atm->optionTimes().begin(), atm->optionTimes().end(), atmLevel_));

    originalAtm_.enableExtrapolation();
}

boost::shared_ptr<SmileSection>
StickyBpVolSwaptionCube::smileSectionImpl(Time optionTime,
                                          Time swapLength) const {

    boost::shared_ptr<SmileSection> source =
        sourceCube_->smileSection(optionTime, swapLength, true);

    Real newAtm = source->atmLevel();

    QL_REQUIRE(newAtm != Null<Real>(),
               "source smile section does not provide atm level");

    Real mul = originalAtm_(optionTime, swapLength) / newAtm;
    Real add = 0.0;
    if(!atmVolatilitySpread_.empty()) {
        if(atmVolatilitySpread_->isValid()) {
            add = atmVolatilitySpread_->value() * mul;
        }
    }

    boost::shared_ptr<SmileSection> tmp =
        boost::make_shared<MultiplicativeSmileSection>(
            source, Handle<Quote>(boost::make_shared<SimpleQuote>(mul)),
            Handle<Quote>(boost::make_shared<SimpleQuote>(add)));
    return tmp;
}

Volatility StickyBpVolSwaptionCube::volatilityImpl(Time optionTime,
                                                   Time swapLength,
                                                   Rate strike) const {
    return smileSectionImpl(optionTime, swapLength)->volatility(strike);
}
}

ext: cpp

max_forks_repo_name: pcaspers/quantlib


text:
#define BOOST_TEST_MODULE lue shared no_data
#include <boost/test/unit_test.hpp>
#include "lue/no_data.hpp"

BOOST_AUTO_TEST_CASE(integral)
{
    std::int32_t value{5};

    BOOST_CHECK(!lue::is_no_data(value));

    lue::set_no_data(value);

    BOOST_CHECK(lue::is_no_data(value));
}

BOOST_AUTO_TEST_CASE(floating_point)
{
    double value{5.5};

    BOOST_CHECK(!lue::is_no_data(value));

    lue::set_no_data(value);

    BOOST_CHECK(lue::is_no_data(value));
}

max_stars_repo_name: computationalgeography/lue

max_issues_repo_name: pcraster/lue

max_forks_repo_name: computationalgeography/lue


text:
/*
// Copyright (c) 2000-2009, Texas Engineering Experiment Station (TEES), a
// component of the Texas A&M University System.

// All rights reserved.

// The information and source code contained herein is the exclusive
// property of TEES and may not be disclosed, examined or reproduced
// in whole or in part without explicit written authorization from TEES.
*/

#ifndef STAPL_CONTAINERS_MULTIARRAY_TRAVERSALS_HPP
#define STAPL_CONTAINERS_MULTIARRAY_TRAVERSALS_HPP

#include <boost/mpl/int.hpp>

#include <stapl/utility/tuple.hpp>

namespace stapl {

//////////////////////////////////////////////////////////////////////
/// @brief Typedef for 2D row-major traversal for a @ref multiarray.
/// @ingroup pmultiarrayManip
//////////////////////////////////////////////////////////////////////
typedef tuple<
  boost::mpl::int_<1>,
  boost::mpl::int_<0>
>                         row_major;

//////////////////////////////////////////////////////////////////////
/// @brief Typedef for 2D column-major traversal for a @ref multiarray.
/// @ingroup pmultiarrayManip
//////////////////////////////////////////////////////////////////////
typedef tuple<
  boost::mpl::int_<0>,
  boost::mpl::int_<1>
>                         column_major;

//////////////////////////////////////////////////////////////////////
/// @brief Typedef for 3D traversal for a @ref multiarray, where the
/// X-Y plane is traversed first in the 2D row-major order, then
/// the Z-component is traversed.
/// @ingroup pmultiarrayManip
//////////////////////////////////////////////////////////////////////
typedef tuple<
  boost::mpl::int_<2>,
  boost::mpl::int_<1>,
  boost::mpl::int_<0>
>                         xyplane_major;

//////////////////////////////////////////////////////////////////////
/// @brief Typedef for 3D traversal for a @ref multiarray, where the
/// X-Z plane is traversed first in the 2D X-major order, then
/// the Y-component is traversed.
/// @ingroup pmultiarrayManip
//////////////////////////////////////////////////////////////////////
typedef tuple<
  boost::mpl::int_<2>,
  boost::mpl::int_<0>,
  boost::mpl::int_<1>
>                         xzplane_major;

} // namespace stapl

#endif


text:
#include <iostream>
#include <boost/shared_ptr.hpp>

#include "ShellContext.h"
#include "ShellState.h"

#include "thrift/lib/cpp/protocol/TBinaryProtocol.h"
#include "thrift/lib/cpp/transport/TSocket.h"
#include "thrift/lib/cpp/transport/TTransportUtils.h"

using namespace std;
using namespace boost;
using namespace Tleveldb;
using namespace rocksdb;
using namespace apache::thrift::protocol;
using namespace apache::thrift::transport;

void ShellContext::changeState(ShellState * pState) {
  pShellState_ = pState;
}

void ShellContext::stop(void) {
  exit_ = true;
}

bool ShellContext::ParseInput(void) {
  if(argc_ != 3) {
    printf("leveldb_shell host port\n");
    return false;
  }

  port_ = atoi(argv_[2]);
  if(port_ <= 0) {
    printf("Error while parse port : %s\n", argv_[2]);
    return false;
  }

  clientProxy_.reset(new DBClientProxy(argv_[1], port_));
  if(!clientProxy_.get()) {
    return false;
  } else {
    return true;
  }
}

void ShellContext::connect(void) {
  clientProxy_->connect();
}

void ShellContext::create(const string & db) {
  if (clientProxy_->create(db)) {
    printf("%s created\n", db.c_str());
  }
}

void ShellContext::get(const string & db,
                       const string & key) {
  string v;
  if (clientProxy_->get(db, key, v)) {
    printf("%s\n", v.c_str());
  }
}

void ShellContext::put(const string & db,
                       const string & key,
                       const string & value) {
  if (clientProxy_->put(db, key, value)) {
    printf("(%s, %s) has been set\n", key.c_str(), value.c_str());
  }
}

void ShellContext::scan(const string & db,
                        const string & start_key,
                        const string & end_key,
                        const string & limit) {
  vector<pair<string, string> > kvs;
  if (clientProxy_->scan(db, start_key, end_key, limit, kvs)) {
    for(unsigned int i = 0; i < kvs.size(); ++i) {
      printf("%d (%s, %s)\n", i, kvs[i].first.c_str(), kvs[i].second.c_str());
    }
  }
}

void ShellContext::run(void) {
  while(!exit_) {
    pShellState_->run(this);
  }
}

ShellContext::ShellContext(int argc, char ** argv) :
  pShellState_(ShellStateStart::getInstance()),
  exit_(false),
  argc_(argc),
  argv_(argv),
  port_(-1),
  clientProxy_() {
}

max_stars_repo_name: latcoin/rippled


text:
#define BOOST_TEST_MODULE SeparatorTest
#define BOOST_TEST_DYN_LINK

#include <boost/test/unit_test.hpp>
#include <treeDAG/separatorCache.hpp>

#include "util.hpp"

typedef treeDAG::SeparatorConfig::Graph Graph;

BOOST_AUTO_TEST_CASE( path_test )
{
    static const std::size_t MAX_SIZE = 10;

    for(std::size_t size = 2; size < MAX_SIZE; ++size)
    {
        Graph g = make_path(size);
        treeDAG::SeparatorCache cache(1, &g);
        cache.initialize();

        for(std::size_t i = 0; i < size; ++i)
        {
            std::vector<std::size_t> sep;
            sep.push_back(i);

            if(i == 0 || i == size-1)
                BOOST_CHECK(cache.findSeparator(sep) == 0);
            else
                BOOST_CHECK(cache.findSeparator(sep) != 0);
        }
    }
}

BOOST_AUTO_TEST_CASE( cycle_test )
{
    static const std::size_t MAX_SIZE = 10;

    for(std::size_t size = 2; size < MAX_SIZE; ++size)
    {
        Graph g = make_cycle(size);
        treeDAG::SeparatorCache cache(2, &g);
        cache.initialize();

        for(std::size_t i = 0; i < size; ++i)
        {
            for(std::size_t j = i+1; j < size; ++j)
            {
                std::vector<std::size_t> sep;
                sep.push_back(i);
                sep.push_back(j);

                if((j == i+1) || (i == 0 && j == size-1))
                    BOOST_CHECK(cache.findSeparator(sep) == 0);
                else
                    BOOST_CHECK(cache.findSeparator(sep) != 0);
            }
        }
    }

}

max_stars_repo_name: thomasfannes/treeDAG

max_issues_repo_name: thomasfannes/treeDAG

max_forks_repo_name: thomasfannes/treeDAG


text:
//
// Copyright (c) 2015 CNRS
//

#define     BOOST_FUSION_INVOKE_MAX_ARITY 10

// #include "pinocchio/spatial/fwd.hpp"
// #include "pinocchio/spatial/se3.hpp"
// #include "pinocchio/multibody/joint.hpp"
// #include "pinocchio/multibody/model.hpp"

#include <iostream>

#include "pinocchio/tools/timer.hpp"
#include <Eigen/Core>

#include <boost/test/unit_test.hpp>
#include <boost/utility/binary.hpp>

struct TestObj
{
  int i;
  TestObj() : i(0) { std::cout << "Test()" << std::endl; }
  TestObj(int i) : i(i) { std::cout << "Test(int)" << std::endl; }
  TestObj(const TestObj& clone) : i(clone.i) { std::cout << "Test(clone)" << std::endl; }
};

template<typename D>
struct CRTPBase
{
  D& derived() { return static_cast<D&> (*this); }
  const D& derived() const { return static_cast<const D&> (*this); }

  void f() { static_cast<D*>(this)->f(); }
  int g() { return static_cast<D*>(this)->g(); }
  int h(const double & x) { return static_cast<D*>(this)->h(x); }
  int hh(const double & x,const int & y, const Eigen::MatrixXd & z,const TestObj & a) { return static_cast<D*>(this)->hh(x,y,z,a); }
};

struct CRTPDerived : public CRTPBase<CRTPDerived>
{
  void f() { std::cout << "f()" << std::endl; }
  int g() { std::cout << "g()" << std::endl; return 1; }
  int h(const double & x) { std::cout << "h(" << x << ")" << std::endl; return 2; }
  int hh(const double & x,const int & y, const Eigen::MatrixXd & z,const TestObj & )
  { std::cout << "hh(" << x << "," << y << "," << z << ",a)" << std::endl; return 3; }
};

struct CRTPDerived2 : public CRTPBase<CRTPDerived2>
{
  void f() { std::cout << "f()" << std::endl; }
  int g() { std::cout << "g()" << std::endl; return 1; }
  int h(const double & x) { std::cout << "h(" << x << ")" << std::endl; return 2; }
  int hh(const double & x,const int & y, const Eigen::MatrixXd & z,const TestObj & )
  { std::cout << "hh(" << x << "," << y << "," << z << ",a)" << std::endl; return 3; }
};

// template<typedef Launcher>
// struct LauncherBase : public boost::static_visitor<Launcher::ReturnType>
// {
//   typedef typename Launcher::ReturnType ReturnType;

//   template<typename D>
//   ReturnType operator()( const CRTP<D> & crtp )  const
//   {
//     return static_cast<D*>(this)->algo(crtp,
//               static_cast<D*>(this)->args);
//   }

//   static
// };

#include <boost/variant.hpp>
typedef boost::variant<CRTPDerived,CRTPDerived2> CRTPVariant;

#include <boost/fusion/include/sequence.hpp>
#include <boost/fusion/include/make_vector.hpp>
#include <boost/fusion/include/next.hpp>
#include <boost/fusion/include/invoke.hpp>
#include <boost/fusion/view/joint_view.hpp>
#include <boost/fusion/include/joint_view.hpp>
#include <boost/fusion/algorithm.hpp>
#include <boost/fusion/container.hpp>

namespace bf = boost::fusion;

struct Launcher : public boost::static_visitor<int>
{

  typedef bf::vector<const double &,const int &, const Eigen::MatrixXd &,
         const Eigen::MatrixXd &,const Eigen::MatrixXd &,const TestObj &> Args;
  Args args;

  Launcher(Args args) : args(args) {}

  template<typename D>
  int operator() ( CRTPBase<D> & dref )  const
  {
    return bf::invoke(&Launcher::algo<D>,bf::push_front(args,boost::ref(dref)));
  }

  static int run(CRTPVariant & crtp, Args args )
  {
    return boost::apply_visitor( Launcher(args),crtp );
  }

  template<typename D>
  static int algo(CRTPBase<D> & crtp, const double & x,const int & y, const Eigen::MatrixXd & z,
      const Eigen::MatrixXd & ,const Eigen::MatrixXd & ,const TestObj & a)
  {
    return crtp.hh(x,y,z,a);
  }
};

namespace boost {
  namespace fusion {
    template<typename T,typename V>
    typename result_of::push_front<V const, T>::type
    append(T const& t,V const& v) { return push_front(v,t); }

    template<typename T1,typename T2,typename V>
    typename result_of::push_front<typename result_of::push_front<V const, T2>::type const, T1>::type
    append2(T1 const& t1,T2 const& t2,V const& v) { return push_front(push_front(v,t2),t1); }

    // template<typename t1,typename t2,typename v>

    // typename result_of::push_front<Sequence, T>::type

    // res append2(t1 a1,t2 a2,v a3) { return push_front(push_front(a3,a2),a1); }
  }}

BOOST_AUTO_TEST_SUITE ( BOOST_TEST_MODULE )

BOOST_AUTO_TEST_CASE ( test_fusion )
{
  CRTPDerived d;
  //CRTPBase<CRTPDerived> & dref = d;
  CRTPVariant v = d;

  //(CRTPBase<D> & crtp, const double & x,const int & y, const Eigen::MatrixXd & z,const TestObj & a)

  //Args args(1.0,1,Eigen::MatrixXd::Zero(3,3),TestObj(1));
  Launcher::run(v,  Launcher::Args(1.0,1,Eigen::MatrixXd::Zero(3,3),Eigen::MatrixXd::Zero(3,3),
           Eigen::MatrixXd::Zero(3,3),TestObj(1)) );

  int i,j; double k;
  bf::vector<int&> arg = bf::make_vector(boost::ref(j));

  bf::vector<double &,int &> arg1 = bf::append(boost::ref(k),arg);
  bf::vector<int &,double &,int &> arg11 = bf::append(boost::ref(i),arg1);

  bf::vector<int &,double &,int &> arg2 = bf::append2(boost::ref(i),boost::ref(k),arg);
    //bf::push_front(bf::push_front(arg1,boost::ref(k)),boost::ref(j));
}

BOOST_AUTO_TEST_SUITE_END ()

max_stars_repo_name: vishalbelsare/pinocchio

max_issues_repo_name: mulittleyun/pinocchio

max_forks_repo_name: mulittleyun/pinocchio


text:
/*
 //
 // DEKAF(tm): Lighter, Faster, Smarter (tm)
 //
 // Copyright (c) 2018, Ridgeware, Inc.
 //
 // +-------------------------------------------------------------------------+
 // | /\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\|
 // |/+---------------------------------------------------------------------+/|
 // |/|                                                                     |/|
 // |\|  ** THIS NOTICE MUST NOT BE REMOVED FROM THE SOURCE CODE MODULE **  |\|
 // |/|                                                                     |/|
 // |\|   OPEN SOURCE LICENSE                                               |\|
 // |/|                                                                     |/|
 // |\|   Permission is hereby granted, free of charge, to any person       |\|
 // |/|   obtaining a copy of this software and associated                  |/|
 // |\|   documentation files (the "Software"), to deal in the              |\|
 // |/|   Software without restriction, including without limitation        |/|
 // |\|   the rights to use, copy, modify, merge, publish,                  |\|
 // |/|   distribute, sublicense, and/or sell copies of the Software,       |/|
 // |\|   and to permit persons to whom the Software is furnished to        |\|
 // |/|   do so, subject to the following conditions:                       |/|
 // |\|                                                                     |\|
 // |/|   The above copyright notice and this permission notice shall       |/|
 // |\|   be included in all copies or substantial portions of the          |\|
 // |/|   Software.                                                         |/|
 // |\|                                                                     |\|
 // |/|   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY         |/|
 // |\|   KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE        |\|
 // |/|   WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR           |/|
 // |\|   PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS        |\|
 // |/|   OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR          |/|
 // |\|   OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR        |\|
 // |/|   OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE         |/|
 // |\|   SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.            |\|
 // |/|                                                                     |/|
 // |/+---------------------------------------------------------------------+/|
 // |\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ |
 // +-------------------------------------------------------------------------+
 */

#include <boost/iostreams/filter/gzip.hpp>
#include <boost/iostreams/filter/zlib.hpp>
#include <boost/iostreams/filter/bzip2.hpp>

#include "khttpoutputfilter.h"
#include "kchunkedtransfer.h"
#include "kstringstream.h"
#include "kmime.h"

namespace dekaf2 {

//-----------------------------------------------------------------------------
bool KOutHTTPFilter::Parse(const KHTTPHeaders& headers)
//-----------------------------------------------------------------------------
{
	close();

	m_bChunked = headers.Headers.Get(KHTTPHeader::TRANSFER_ENCODING) == "chunked";

	KStringView sCompression = headers.Headers.Get(KHTTPHeader::CONTENT_ENCODING);

	if (sCompression == "gzip" || sCompression == "x-gzip")
	{
		m_Compression = GZIP;
	}
	else if (sCompression == "deflate")
	{
		m_Compression = ZLIB;
	}
	else if (sCompression == "bzip2")
	{
		m_Compression = BZIP2;
	}

	return true;

} // Parse

//-----------------------------------------------------------------------------
bool KOutHTTPFilter::SetupOutputFilter()
//-----------------------------------------------------------------------------
{
	// we lazy-create the input filter chain because we want to give
	// the user the chance to switch off compression AFTER reading
	// the headers

	if (m_bAllowCompression)
	{
		if (m_Compression == GZIP)
		{
			kDebug(2, "using gzip compression")
			m_Filter->push(boost::iostreams::gzip_compressor());
		}
		else if (m_Compression == ZLIB)
		{
			kDebug(2, "using zlib compression")
			m_Filter->push(boost::iostreams::zlib_compressor());
		}
		else if (m_Compression == BZIP2)
		{
			kDebug(2, "using bzip2 compression")
			m_Filter->push(boost::iostreams::bzip2_compressor());
		}
	}
	else
	{
		kDebug(2, "no compression");
	}

	if (m_bChunked)
	{
		kDebug(2, "chunked TX");
	}

	m_iCount = 0;

	// we use the chunked writer also in the unchunked case, but
	// without writing chunks
	KChunkedSink Sink(UnfilteredStream(), m_bChunked, &m_iCount);

	// and finally add our source stream to the filtering_istream
	m_Filter->push(std::move(Sink));

	return true;

} // SetupOutputFilter

//-----------------------------------------------------------------------------
// build the filter if it is not yet created, and return a KOutStream reference to it
KOutStream& KOutHTTPFilter::FilteredStream()
//-----------------------------------------------------------------------------
{
	if (m_Filter->empty())
	{
		SetupOutputFilter();
	}
	return m_FilteredOutStream;
}

//-----------------------------------------------------------------------------
std::streamsize KOutHTTPFilter::Count() const
//-----------------------------------------------------------------------------
{
	if (!m_Filter->empty())
	{
		// we cannot reliably read the count when we compress - no way to flush
		if (m_bAllowCompression && m_Compression == NONE)
		{
			auto chunker = m_Filter->component<KChunkedSink>(m_Filter->size()-1);

			if (chunker)
			{
				// this sync does not work with compression!
				m_Filter->strict_sync();
				return chunker->Count();
			}
			else
			{
				kDebug(1, "cannot get KChunkedSink component from output pipeline");
				return 0;
			}
		}
		else
		{
			kDebug(1, "cannot read count with a compressing pipeline before close()");
			return 0;
		}
	}
	else
	{
		return m_iCount;
	}

} // Count

//-----------------------------------------------------------------------------
bool KOutHTTPFilter::ResetCount()
//-----------------------------------------------------------------------------
{
	if (!m_Filter->empty())
	{
		// we cannot reliably reset the count when we compress - no way to flush
		if (m_bAllowCompression && m_Compression == NONE)
		{
			auto chunker = m_Filter->component<KChunkedSink>(m_Filter->size()-1);

			if (chunker)
			{
				m_Filter->strict_sync();
				chunker->ResetCount();
			}
			else
			{
				kDebug(1, "cannot get KChunkedSink component from output pipeline");
				return false;
			}
		}
		else
		{
			return false;
		}
	}

	m_iCount = 0;
	return true;

} // ResetCount

//-----------------------------------------------------------------------------
size_t KOutHTTPFilter::Write(KInStream& InStream, size_t len)
//-----------------------------------------------------------------------------
{
	auto& Out(FilteredStream());

	if (len == npos)
	{
		// write until eof
		Out.OutStream() << InStream.InStream().rdbuf();
	}
	else
	{
		Out.Write(InStream, len);
	}

	if (Out.Good())
	{
		return len;
	}
	else
	{
		return 0;
	}

} // Write

//-----------------------------------------------------------------------------
size_t KOutHTTPFilter::Write(KStringView sBuffer)
//-----------------------------------------------------------------------------
{
	auto& Out(FilteredStream());

	Out.Write(sBuffer);

	if (Out.Good())
	{
		return sBuffer.size();
	}
	else
	{
		return 0;
	}

} // Write

//-----------------------------------------------------------------------------
size_t KOutHTTPFilter::WriteLine(KStringView sBuffer)
//-----------------------------------------------------------------------------
{
	auto& Out(FilteredStream());

	Out.WriteLine(sBuffer);

	if (Out.Good())
	{
		return sBuffer.size() + Out.GetWriterEndOfLine().size();
	}
	else
	{
		return 0;
	}

} // WriteLine

//-----------------------------------------------------------------------------
void KOutHTTPFilter::close()
//-----------------------------------------------------------------------------
{
	if (!m_Filter->empty())
	{
		m_Filter->reset();

		if (m_OutStream)
		{
			m_OutStream->Flush();
		}

		m_Compression       = NONE;
		m_bChunked          = false;
		m_bAllowCompression = true;
	}

} // close

KOutStringStream KOutHTTPFilter::s_Empty;

} // of namespace dekaf2


text:
/*
 * Copyright 2020 Adobe. All rights reserved.
 * This file is licensed to you under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License. You may obtain a copy
 * of the License at http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under
 * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
 * OF ANY KIND, either express or implied. See the License for the specific language
 * governing permissions and limitations under the License.
 */
#include <Eigen/Core>
#include <lagrange/testing/common.h>

#include <lagrange/common.h>
#include <lagrange/create_mesh.h>
#include <lagrange/experimental/IndexedAttributeManager.h>

namespace {

template <typename T, int DIM>
using TestArray = Eigen::Matrix<T, Eigen::Dynamic, DIM, Eigen::RowMajor>;

template <typename TargetValueDerived, typename TargetIndexDerived>
void check_indexed_attribute(
    lagrange::experimental::IndexedAttributeManager& manager,
    const std::string& name,
    const Eigen::MatrixBase<TargetValueDerived>& target_values,
    const Eigen::MatrixBase<TargetIndexDerived>& target_indices,
    void* values_ptr = nullptr,
    void* indices_ptr = nullptr)
{
    REQUIRE(manager.has(name));

    using ValueDerived = Eigen::Matrix<
        typename TargetValueDerived::Scalar,
        Eigen::Dynamic,
        Eigen::Dynamic,
        TargetValueDerived::IsRowMajor ? Eigen::RowMajor : Eigen::ColMajor>;
    using IndexDerived = Eigen::Matrix<
        typename TargetIndexDerived::Scalar,
        Eigen::Dynamic,
        Eigen::Dynamic,
        TargetIndexDerived::IsRowMajor ? Eigen::RowMajor : Eigen::ColMajor>;
    auto values_view = manager.view_values<ValueDerived>(name);
    auto indices_view = manager.view_indices<IndexDerived>(name);

    REQUIRE(values_view == target_values);
    REQUIRE(indices_view == target_indices);

    if (values_ptr != nullptr) {
        // When data pointers differ, data must be copied into the array.
        REQUIRE(values_view.data() == values_ptr);
    }
    if (indices_ptr != nullptr) {
        // When data pointers differ, data must be copied into the array.
        REQUIRE(indices_view.data() == indices_ptr);
    }
}

} // namespace

TEST_CASE("experimental/IndexedAttributes", "[attribute][indexed]")
{
    using namespace lagrange;

    SECTION("Simple usage")
    {
        experimental::IndexedAttributeManager manager;

        TestArray<int, 3> int_array(3, 3);
        int_array.setZero();

        TestArray<float, 3> float_array(3, 3);
        float_array.setOnes();

        manager.add("int_attr");
        manager.set("int_attr", int_array, int_array);

        REQUIRE(manager.has("int_attr"));

        manager.add("float_attr", float_array, int_array);
        REQUIRE(manager.has("float_attr"));

        int_array.setOnes();
        manager.set("int_attr", int_array, int_array);

        REQUIRE(manager.view_values<TestArray<int, 3>>("int_attr").minCoeff() == 1);
        REQUIRE(manager.view_values<TestArray<int, 3>>("int_attr").maxCoeff() == 1);
        REQUIRE(manager.view_indices<TestArray<int, 3>>("int_attr").minCoeff() == 1);
        REQUIRE(manager.view_indices<TestArray<int, 3>>("int_attr").maxCoeff() == 1);

        float_array.setOnes();
        manager.set("float_attr", float_array, int_array);
        REQUIRE(manager.view_values<TestArray<float, 3>>("float_attr").minCoeff() == 1);
        REQUIRE(manager.view_values<TestArray<float, 3>>("float_attr").maxCoeff() == 1);
        REQUIRE(manager.view_indices<TestArray<int, 3>>("float_attr").minCoeff() == 1);
        REQUIRE(manager.view_indices<TestArray<int, 3>>("float_attr").maxCoeff() == 1);

        SECTION("Update")
        {
            auto arr_int = manager.view_values<TestArray<int, 3>>("int_attr");
            auto arr_float = manager.view_values<TestArray<float, 3>>("float_attr");

            arr_int(0, 0) = 10;
            arr_float(0, 0) = 11;

            REQUIRE(manager.view_values<TestArray<int, 3>>("int_attr")(0, 0) == arr_int(0, 0));
            REQUIRE(
                manager.view_values<TestArray<float, 3>>("float_attr")(0, 0) == arr_float(0, 0));
        }
    }

    SECTION("Check for copies")
    {
        experimental::IndexedAttributeManager manager;

        {
            TestArray<short, 3> values(3, 3);
            values.setIdentity();
            TestArray<uint64_t, 3> indices(3, 3);
            indices << 0, 0, 0, 1, 1, 1, 2, 2, 2;
            manager.add("test", values, indices);
        }

        REQUIRE(manager.has("test"));

        // The return type of view_values is an Eigen::Map, so no need
        // to capture it by reference.
        auto values_1 = manager.view_values<TestArray<short, 3>>("test");
        auto values_2 = manager.view_values<TestArray<short, 3>>("test");
        REQUIRE(values_1.data() == values_2.data());

        // To make a copy of the data, fully specify the result type.
        TestArray<short, 3> values_3 = manager.view_values<TestArray<short, 3>>("test");
        REQUIRE(values_1.data() != values_3.data());

        SECTION("What if I remove the attribute?")
        {
            manager.remove("test");
            REQUIRE(!manager.has("test"));
            // TODO:
            // REQUIRE(values_1(0, 0) == 1);
            // ^ This is a bad idea, because it is accessing invalid memory.
            //   Not sure how to prevent this at compile time or check it at run
            //   time.
        }
    }

    SECTION("Creation")
    {
        experimental::IndexedAttributeManager manager;

        SECTION("Create by copying Eigen matrices")
        {
            TestArray<float, 3> values(3, 3);
            values.setOnes();
            TestArray<int, 3> indices(3, 3);
            indices.setZero();

            manager.add("test", values, indices);
            check_indexed_attribute(manager, "test", values, indices);
            manager.remove("test");
        }

        SECTION("Create by moving Eigen matrices")
        {
            TestArray<float, 3> values(3, 3);
            values.setOnes();
            TestArray<int, 3> indices(3, 3);
            indices.setZero();

            void* values_ptr = values.data();
            void* indices_ptr = indices.data();
            auto values_copy = values;
            auto indices_copy = indices;

            manager.add("test", std::move(values), std::move(indices));
            check_indexed_attribute(
                manager,
                "test",
                values_copy,
                indices_copy,
                values_ptr,
                indices_ptr);
            manager.remove("test");
        }

        SECTION("Create by copying Eigen::Map, which will result in copying")
        {
            std::vector<float> values(9, 0);
            std::vector<int> indices(9, 1);

            Eigen::Map<TestArray<float, 3>> values_map(values.data(), 3, 3);
            Eigen::Map<TestArray<int, 3>> indices_map(indices.data(), 3, 3);

            manager.add("test", values_map, indices_map);
            check_indexed_attribute(manager, "test", values_map, indices_map);
            manager.remove("test");
        }

        SECTION("Create by moving Eigen::Map, which will also result in copy")
        {
            std::vector<float> values(9, 0);
            std::vector<int> indices(9, 1);

            Eigen::Map<TestArray<float, 3>> values_map(values.data(), 3, 3);
            Eigen::Map<TestArray<int, 3>> indices_map(indices.data(), 3, 3);

            TestArray<float, 3> values_copy = values_map;
            TestArray<int, 3> indices_copy = indices_map;

            manager.add("test", std::move(values_map), std::move(indices_map));
            check_indexed_attribute(manager, "test", values_copy, indices_copy);
            manager.remove("test");
        }

        SECTION("Create with Array, no copying")
        {
            TestArray<float, 3> values(3, 3);
            values.setOnes();
            TestArray<int, 3> indices(3, 3);
            indices.setZero();

            auto values_array = to_shared_ptr(experimental::create_array(values));
            auto indices_array = to_shared_ptr(experimental::create_array(indices));

            manager.add("test", values_array, indices_array);
            check_indexed_attribute(
                manager,
                "test",
                values,
                indices,
                values_array->data(),
                indices_array->data());
            manager.remove("test");
        }

        SECTION("Create with wrapped Array, no copying")
        {
            TestArray<float, 3> values(3, 3);
            values.setOnes();
            TestArray<int, 3> indices(3, 3);
            indices.setZero();

            auto values_array = to_shared_ptr(experimental::wrap_with_array(values));
            auto indices_array = to_shared_ptr(experimental::wrap_with_array(indices));

            manager.add("test", values_array, indices_array);
            check_indexed_attribute(
                manager,
                "test",
                values,
                indices,
                values.data(),
                indices.data());
            manager.remove("test");
        }

        SECTION("Mixed type creation")
        {
            TestArray<float, 3> values(3, 3);
            values.setOnes();
            TestArray<int, 3> indices(3, 3);
            indices.setZero();

            SECTION("Moved Eigen::Matrix + copied Eigen::Matrix")
            {
                auto values_copy = values;
                void* values_copy_ptr = values_copy.data();

                manager.add("test", std::move(values_copy), indices);
                check_indexed_attribute(manager, "test", values, indices, values_copy_ptr);
                manager.remove("test");
            }

            SECTION("Array + Eigen::Matrix")
            {
                auto values_array = to_shared_ptr(experimental::create_array(values));

                manager.add("test", values_array, indices);
                check_indexed_attribute(manager, "test", values, indices, values_array->data());
                manager.remove("test");
            }

            SECTION("Array + Eigen::Map")
            {
                auto values_array = to_shared_ptr(experimental::create_array(values));
                Eigen::Map<TestArray<int, 3>> indices_map(indices.data(), 3, 3);

                manager.add("test", values_array, indices_map);
                check_indexed_attribute(manager, "test", values, indices, values_array->data());
                manager.remove("test");
            }

            SECTION("Array + moved Eigen::Matrix")
            {
                auto values_array = to_shared_ptr(experimental::create_array(values));
                auto indices_copy = indices;
                void* indices_copy_ptr = indices_copy.data();

                manager.add("test", values_array, std::move(indices_copy));
                check_indexed_attribute(
                    manager,
                    "test",
                    values,
                    indices,
                    values_array->data(),
                    indices_copy_ptr);
                manager.remove("test");
            }
        }
    }

    SECTION("Import and export")
    {
        experimental::IndexedAttributeManager manager;

        TestArray<float, 3> values(3, 3);
        values.setOnes();
        TestArray<int, 3> indices(3, 3);
        indices.setZero();
        void* values_ptr = values.data();
        void* indices_ptr = indices.data();

        manager.add("test", std::move(values), std::move(indices));

        SECTION("Export")
        {
            TestArray<float, 3> tmp_values;
            TestArray<int, 3> tmp_indices;
            manager.export_data("test", tmp_values, tmp_indices);
            REQUIRE(tmp_values.data() == values_ptr);
            REQUIRE(tmp_indices.data() == indices_ptr);
        }

        SECTION("Export with a different Eigen type will result in copy")
        {
            TestArray<float, Eigen::Dynamic> tmp_values(3, 3);
            TestArray<int, Eigen::Dynamic> tmp_indices(3, 3);
            manager.export_data("test", tmp_values, tmp_indices);
            REQUIRE(tmp_values.data() != values_ptr);
            REQUIRE(tmp_indices.data() != indices_ptr);
        }

        SECTION("Exporting raw array will result in a copy")
        {
            std::vector<float> raw_values(9, 0);
            Eigen::Map<TestArray<float, 3>> tmp_values(raw_values.data(), 3, 3);
            TestArray<int, 3> tmp_indices(3, 3);
            tmp_indices.setIdentity();

            values_ptr = tmp_values.data();
            indices_ptr = tmp_indices.data();

            manager.add("test2", tmp_values, std::move(tmp_indices));

            TestArray<float, 3> out_values;
            TestArray<int, 3> out_indices;
            manager.export_data("test2", out_values, out_indices);

            REQUIRE(out_values.data() != values_ptr); // Values are copied.
            REQUIRE(out_indices.data() == indices_ptr); // Indices are not.
        }

        SECTION("Import")
        {
            TestArray<float, 3> tmp_values(3, 3);
            tmp_values.setIdentity();
            TestArray<int, 3> tmp_indices(4, 3);
            tmp_indices.setConstant(10);

            auto values_copy = tmp_values;
            auto indices_copy = tmp_indices;

            values_ptr = tmp_values.data();
            indices_ptr = tmp_indices.data();

            manager.import_data("test", std::move(tmp_values), std::move(tmp_indices));
            check_indexed_attribute(
                manager,
                "test",
                values_copy,
                indices_copy,
                values_ptr,
                indices_ptr);
        }

        SECTION("Import with a different type will fail")
        {
            TestArray<float, Eigen::Dynamic> tmp_values(3, 3);
            tmp_values.setIdentity();
            TestArray<int, Eigen::Dynamic> tmp_indices(4, 3);
            tmp_indices.setConstant(10);

            values_ptr = tmp_values.data();
            indices_ptr = tmp_indices.data();

            // It is not possible to import if the Eigen type does not exactly
            // match (for now)...  A warning should be issued.
            manager.import_data("test", std::move(tmp_values), std::move(tmp_indices));

            auto attr = manager.get("test");
            REQUIRE(attr != nullptr);
            void* out_values_ptr = attr->get_values()->data();
            void* out_indices_ptr = attr->get_indices()->data();

            REQUIRE(values_ptr != out_values_ptr);
            REQUIRE(indices_ptr != out_indices_ptr);
        }

        SECTION("Export -> update -> import")
        {
            manager.export_data("test", values, indices);
            REQUIRE(values.data() == values_ptr);
            REQUIRE(indices.data() == indices_ptr);

            values.setConstant(10);
            indices.setConstant((int)1e5);
            REQUIRE(values.data() == values_ptr);
            REQUIRE(indices.data() == indices_ptr);

            auto values_copy = values;
            auto indices_copy = indices;

            manager.import_data("test", values, indices);
            check_indexed_attribute(
                manager,
                "test",
                values_copy,
                indices_copy,
                values_ptr,
                indices_ptr);
        }
    }
}


text:
#include "GraphKeyLocks.h"
#include "Common.h"
#include <bcos-framework/libutilities/DataConvertUtility.h>
#include <bcos-framework/libutilities/Error.h>
#include <boost/core/ignore_unused.hpp>
#include <boost/format.hpp>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/depth_first_search.hpp>
#include <boost/graph/detail/adjacency_list.hpp>
#include <boost/graph/edge_list.hpp>
#include <boost/graph/graph_selectors.hpp>
#include <boost/graph/properties.hpp>
#include <boost/graph/visitors.hpp>
#include <boost/throw_exception.hpp>
#include <algorithm>

using namespace bcos::scheduler;

bool GraphKeyLocks::batchAcquireKeyLock(
    std::string_view contract, gsl::span<std::string const> keys, ContextID contextID, Seq seq)
{
    if (!keys.empty())
    {
        for (auto& it : keys)
        {
            if (!acquireKeyLock(contract, it, contextID, seq))
            {
                auto message = (boost::format("Batch acquire lock failed, contract: %s"
                                              ", key: %s, contextID: %ld, seq: %ld") %
                                contract % toHex(it) % contextID % seq)
                                   .str();
                SCHEDULER_LOG(ERROR) << message;
                BOOST_THROW_EXCEPTION(BCOS_ERROR(UnexpectedKeyLockError, message));
                return false;
            }
        }
    }

    return true;
}

bool GraphKeyLocks::acquireKeyLock(
    std::string_view contract, std::string_view key, int64_t contextID, int64_t seq)
{
    auto keyVertex = touchKeyLock(std::make_tuple(contract, key));
    auto contextVertex = touchContext(contextID);

    auto range = boost::out_edges(keyVertex, m_graph);
    for (auto it = range.first; it != range.second; ++it)
    {
        auto vertex = boost::get(VertexPropertyTag(), boost::target(*it, m_graph));
        if (std::get<0>(*vertex) != contextID)
        {
            SCHEDULER_LOG(TRACE) << boost::format(
                                        "Acquire key lock failed, request: [%s, %s, %ld, %ld] "
                                        "exists: [%ld]") %
                                        contract % key % contextID % seq % std::get<0>(*vertex);

            // Key lock holding by another context
            addEdge(contextVertex, keyVertex, seq);
            return false;
        }
    }

    // Remove all request edge
    boost::remove_edge(contextVertex, keyVertex, m_graph);

    // Add an own edge
    addEdge(keyVertex, contextVertex, seq);

    SCHEDULER_LOG(TRACE) << "Acquire key lock success, contract: " << contract << " key: " << key
                         << " contextID: " << contextID << " seq: " << seq;

    return true;
}

std::vector<std::string> GraphKeyLocks::getKeyLocksNotHoldingByContext(
    std::string_view contract, int64_t excludeContextID) const
{
    std::set<std::string> uniqueKeyLocks;

    auto range = boost::edges(m_graph);
    for (auto it = range.first; it != range.second; ++it)
    {
        auto sourceVertex = boost::get(VertexPropertyTag(), boost::source(*it, m_graph));
        auto targetVertex = boost::get(VertexPropertyTag(), boost::target(*it, m_graph));

        if (targetVertex->index() == 0 && std::get<0>(*targetVertex) != excludeContextID &&
            sourceVertex->index() == 1 && std::get<0>(std::get<1>(*sourceVertex)) == contract)
        {
            uniqueKeyLocks.emplace(std::get<1>(std::get<1>(*sourceVertex)));
        }
    }

    std::vector<std::string> keyLocks;
    keyLocks.reserve(uniqueKeyLocks.size());
    for (auto& it : uniqueKeyLocks)
    {
        keyLocks.emplace_back(std::move(it));
    }

    return keyLocks;
}

void GraphKeyLocks::releaseKeyLocks(int64_t contextID, int64_t seq)
{
    SCHEDULER_LOG(TRACE) << "Release key lock, contextID: " << contextID << " seq: " << seq;
    auto vertex = touchContext(contextID);

    auto edgeRemoveFunc = [seq, graph = &m_graph](auto range) mutable -> bool {
        size_t total = 0;
        size_t removed = 0;

        for (auto next = range.first; range.first != range.second; range.first = next)
        {
            ++total;
            ++next;
            auto edgeSeq = boost::get(EdgePropertyTag(), *range.first);
            if (edgeSeq == seq)
            {
                ++removed;
                if (bcos::LogLevel::TRACE >= bcos::c_fileLogLevel)
                {
                    auto source =
                        boost::get(VertexPropertyTag(), boost::source(*range.first, *graph));
                    auto target =
                        boost::get(VertexPropertyTag(), boost::target(*range.first, *graph));
                    if (target->index() == 1)
                    {
                        source = target;
                    }

                    const auto& [contract, key] = std::get<1>(*source);
                    SCHEDULER_LOG(TRACE)
                        << "Releasing key lock, contract: " << contract << " key: " << key;
                }
                boost::remove_edge(*range.first, *graph);
            }
        }

        return total == removed;
    };

    auto clearedIn = edgeRemoveFunc(boost::in_edges(vertex, m_graph));
    auto clearedOut = edgeRemoveFunc(boost::out_edges(vertex, m_graph));

    if (clearedIn && clearedOut)
    {
        // All edge had removed, delete the vertex
        boost::remove_vertex(vertex, m_graph);
        m_vertexes.erase(contextID);
    }
}

bool GraphKeyLocks::detectDeadLock(ContextID contextID)
{
    struct GraphVisitor
    {
        GraphVisitor(bool& backEdge) : m_backEdge(backEdge) {}

        void initialize_vertex(VertexID, const Graph&) {}
        void start_vertex(VertexID, const Graph&) {}
        void discover_vertex(VertexID, const Graph&) {}
        void examine_edge(EdgeID, const Graph&) {}
        void tree_edge(EdgeID, const Graph&) {}
        void forward_or_cross_edge(EdgeID, const Graph&) {}
        void finish_edge(EdgeID, const Graph&) {}
        void finish_vertex(VertexID, const Graph&) {}

        void back_edge(EdgeID edgeID, const Graph&) const
        {
            auto edgeSeq = boost::get(EdgePropertyTag(), edgeID);
            SCHEDULER_LOG(TRACE) << "Detected back edge seq: " << edgeSeq;

            m_backEdge = true;
        }

        bool& m_backEdge;
    };

    auto it = m_vertexes.find(bcos::scheduler::GraphKeyLocks::Vertex(contextID));
    if (it == m_vertexes.end())
    {
        // No vertex, may be removed
        return false;
    }

    if (boost::in_degree(it->second, m_graph) == 0)
    {
        // No in degree, not holding key lock
        return false;
    }

    std::map<VertexID, boost::default_color_type> vertexColors;
    bool hasDeadLock = false;
    boost::depth_first_visit(m_graph, it->second, GraphVisitor(hasDeadLock),
        boost::make_assoc_property_map(vertexColors),
        [&hasDeadLock](VertexID, const Graph&) { return hasDeadLock; });

    return hasDeadLock;
}

GraphKeyLocks::VertexID GraphKeyLocks::touchContext(int64_t contextID)
{
    auto [it, inserted] = m_vertexes.emplace(Vertex(contextID), VertexID());
    if (inserted)
    {
        it->second = boost::add_vertex(&(it->first), m_graph);
    }
    auto contextVertexID = it->second;

    return contextVertexID;
}

GraphKeyLocks::VertexID GraphKeyLocks::touchKeyLock(KeyLockView keyLockView)
{
    auto contractKeyView = keyLockView;
    auto it = m_vertexes.lower_bound(contractKeyView);
    if (it != m_vertexes.end() && it->first == contractKeyView)
    {
        return it->second;
    }

    auto inserted = m_vertexes.emplace_hint(it,
        Vertex(std::make_tuple(
            std::string(std::get<0>(contractKeyView)), std::string(std::get<1>(contractKeyView)))),
        VertexID());
    inserted->second = boost::add_vertex(&(inserted->first), m_graph);
    return inserted->second;
}

void GraphKeyLocks::addEdge(VertexID source, VertexID target, int64_t seq)
{
    bool exists = false;

    auto range = boost::edge_range(source, target, m_graph);
    for (auto it = range.first; it != range.second; ++it)
    {
        auto edgeSeq = boost::get(EdgePropertyTag(), *it);
        if (edgeSeq == seq)
        {
            exists = true;
        }
    }

    if (!exists)
    {
        boost::add_edge(source, target, seq, m_graph);
    }
}

void GraphKeyLocks::removeEdge(VertexID source, VertexID target, int64_t seq)
{
    auto range = boost::edge_range(source, target, m_graph);
    for (auto it = range.first; it != range.second; ++it)
    {
        auto edgeSeq = boost::get(EdgePropertyTag(), *it);
        if (edgeSeq == seq)
        {
            boost::remove_edge(*it, m_graph);
            break;
        }
    }
}


text:
// Copyright (c) 2016 Klemens D. Morgenstern
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#ifndef BOOST_PROCESS_DETAIL_WINDOWS_WAIT_GROUP_HPP_
#define BOOST_PROCESS_DETAIL_WINDOWS_WAIT_GROUP_HPP_

#include <boost/process/detail/config.hpp>
#include <boost/detail/winapi/jobs.hpp>
#include <boost/detail/winapi/wait.hpp>

namespace boost { namespace process { namespace detail { namespace windows {

struct group_handle;

inline void wait(const group_handle &p)
{
    if (::boost::detail::winapi::WaitForSingleObject(p.handle(),
        ::boost::detail::winapi::infinite) == ::boost::detail::winapi::wait_failed)
            throw_last_error("WaitForSingleObject() failed");

}

inline void wait(const group_handle &p, std::error_code &ec)
{
    if (::boost::detail::winapi::WaitForSingleObject(p.handle(),
        ::boost::detail::winapi::infinite) == ::boost::detail::winapi::wait_failed)
            ec = get_last_error();
}

template< class Rep, class Period >
inline bool wait_for(
        const group_handle &p,
        const std::chrono::duration<Rep, Period>& rel_time)
{

    std::chrono::milliseconds ms = std::chrono::duration_cast<std::chrono::milliseconds>(rel_time);

    ::boost::detail::winapi::DWORD_ wait_code;
    wait_code = ::boost::detail::winapi::WaitForSingleObject(p.handle(), ms.count());
    if (wait_code == ::boost::detail::winapi::wait_failed)
        throw_last_error("WaitForSingleObject() failed");
    else if (wait_code == ::boost::detail::winapi::wait_timeout)
        return false; //

    return true;
}

template< class Rep, class Period >
inline bool wait_for(
        const group_handle &p,
        const std::chrono::duration<Rep, Period>& rel_time,
        std::error_code &ec)
{

    std::chrono::milliseconds ms = std::chrono::duration_cast<std::chrono::milliseconds>(rel_time);

    ::boost::detail::winapi::DWORD_ wait_code;
    wait_code = ::boost::detail::winapi::WaitForSingleObject(p.handle(), ms.count());
    if (wait_code == ::boost::detail::winapi::wait_failed)
        ec = get_last_error();

    else if (wait_code == ::boost::detail::winapi::wait_timeout)
        return false; //

    return true;
}

template< class Clock, class Duration >
inline bool wait_until(
        const group_handle &p,
        const std::chrono::time_point<Clock, Duration>& timeout_time)
{
    std::chrono::milliseconds ms =
            std::chrono::duration_cast<std::chrono::milliseconds>(
                    timeout_time - std::chrono::system_clock::now());

    ::boost::detail::winapi::DWORD_ wait_code;
    wait_code = ::boost::detail::winapi::WaitForSingleObject(p.handle(), ms.count());

    if (wait_code == ::boost::detail::winapi::wait_failed)
        throw_last_error("WaitForSingleObject() failed");

    else if (wait_code == ::boost::detail::winapi::wait_timeout)
        return false; //

    return true;
}

template< class Clock, class Duration >
inline bool wait_until(
        const group_handle &p,
        const std::chrono::time_point<Clock, Duration>& timeout_time,
        std::error_code &ec)
{
    std::chrono::milliseconds ms =
            std::chrono::duration_cast<std::chrono::milliseconds>(
                    timeout_time - std::chrono::system_clock::now());

    ::boost::detail::winapi::DWORD_ wait_code;
    wait_code = ::boost::detail::winapi::WaitForSingleObject(p.handle(), ms.count());

    if (wait_code == ::boost::detail::winapi::wait_failed)
        ec = get_last_error();

    else if (wait_code == ::boost::detail::winapi::wait_timeout)
        return false; //

    return true;
;
}

}}}}

#endif /* BOOST_PROCESS_DETAIL_WINDOWS_WAIT_GROUP_HPP_ */