text:
/* Copyright (c) 2015, Julian Straub <jstraub@csail.mit.edu> Licensed
 * under the MIT license.  See the license file LICENSE.
 */

#pragma once

#include <Eigen/Dense>

#include <dpMM/basemeasure.hpp>
#include <dpMM/niwSphereFull.hpp>
#include <mmf/mfPrior.hpp>
#include <mmf/mf.hpp>

template<typename T>
class MfBase : public BaseMeasure<T>
{
public:
  MfBase(const MfPrior<T>& mf0);
  MfBase(const MfPrior<T>& mf0, const MF<T> mf);
  MfBase(const MfBase<T>& mfBase);
  ~MfBase();

  virtual baseMeasureType getBaseMeasureType() const {return(MF_T); }

  virtual BaseMeasure<T>* copy(); // TODO
  virtual MfBase<T>* copyNative(); // TODO

  T logLikelihood(const Matrix<T,Dynamic,1>& x) const;
  T logLikelihood(const Matrix<T,Dynamic,Dynamic>& x, uint32_t i) const
    {return logLikelihood(x.col(i));};
// TODO
// assumes vector [N, sum(x), flatten(sum(outer(x,x)))]
  T logLikelihoodFromSS(const Matrix<T,Dynamic,1>& x) const;

  void posterior(const Matrix<T,Dynamic,Dynamic>& x, const VectorXu& z,
    uint32_t k);
// TODO
//  void posterior(const vector<Matrix<T,Dynamic,Dynamic> >&x, const
//      VectorXu& z, uint32_t k);
// TODO
  void posteriorFromSS(const vector<Matrix<T,Dynamic,1> >&x, const
      VectorXu& z, uint32_t k);
//  void posteriorFromSS(const Matrix<T,Dynamic,1> &x);
//  void sample();

// TODO
  T logPdfUnderPrior() const;
//  T logPdfUnderPriorMarginalized() const;
//  T logPdfUnderPriorMarginalizedMerged(const shared_ptr<MfBase<T> >& other) const;
//
//  T logPdfUnderPriorMarginalized(const Matrix<T,Dynamic,1>& x) {return 0.;};
// TODO
  void print() const;
  virtual uint32_t getDim() const {return 3;};

//  const Matrix<T,Dynamic,Dynamic>& scatter() const {return mf0_.scatter();};
//  const Matrix<T,Dynamic,1>& mean() const {return mf0_.mean();};
//  T count() const {return mf0_.count();};
////  T& count() {return mf0_.count_;};
//  const Matrix<T,Dynamic,1>& getMean() const {return normal_.mu_;};
//
//  const Matrix<T,Dynamic,Dynamic>& Sigma() const {return normal_.Sigma();};
  MfPrior<T> mf0_;
  MF<T> mf_;

private:
};

typedef MfBase<double> MfBased;
typedef MfBase<float> MfBasef;

// ---------------------------------------------------------

template<typename T>
MfBase<T>::MfBase(const MfPrior<T>& mf0)
  :  mf0_(mf0), mf_(mf0.sample())
{
  mf0_.R_ = mf_.R();
};

template<typename T>
MfBase<T>::MfBase(const MfPrior<T>& mf0, const MF<T> mf)
  : mf0_(mf0), mf_(mf)
{};

template<typename T>
MfBase<T>::MfBase(const MfBase<T>& mfB)
  : mf0_(mfB.mf0_), mf_(mfB.mf_)
{};

template<typename T>
MfBase<T>::~MfBase()
{};

template<typename T>
BaseMeasure<T>* MfBase<T>::copy()
{
  MfBase<T>* mfBase = new MfBase<T>(mf0_);
  mfBase->mf_ = mf_;
//  niwSampled->normal_ = normal_;
  return mfBase;
};

template<typename T>
MfBase<T>* MfBase<T>::copyNative()
{
  MfBase<T>* mfBase = new MfBase<T>(mf0_);
  mfBase->mf_ = mf_;
//  niwSampled->normal_ = normal_;
  return mfBase;
};

template<typename T>
T MfBase<T>::logLikelihood(const Matrix<T,Dynamic,1>& x) const
{
//  normal_.print();
  T logLike = mf_.logPdf(x);
//  cout<<x.transpose()<<" -> " <<logLike<<endl;
//  cout<<x.transpose()<<" -> " <<normal_.logPdfSlower(x)<<endl;
  return logLike;
};

template<typename T>
T MfBase<T>::logLikelihoodFromSS(const Matrix<T,Dynamic,1>& x) const
{
  uint32_t D = 3;
  T count = x(0);
  Matrix<T,Dynamic,1> mean = x.middleRows(1,D);
  Matrix<T,Dynamic,Dynamic> scatter = Matrix<T,Dynamic,Dynamic>::Map(&(x.data()[(D+1)]),D-1,D-1);
  // right now this does not support actual scatter!  it supports
  // weighted directional data though.  count is the weight
  assert(scatter(0,0)==0.);
  assert(scatter(1,0)==0.);
  assert(scatter(0,1)==0.);
  assert(scatter(1,1)==0.);
  return count*mf_.logPdf(mean);
};

template<typename T>
void MfBase<T>::posterior(const Matrix<T,Dynamic,Dynamic>& x,
    const VectorXu& z, uint32_t k)
{
  mf_ = mf0_.posteriorSample(x,z,k);
};

//template<typename T>
//void MfBase<T>::posterior(const vector<Matrix<T,Dynamic,Dynamic> >&x,
//	const VectorXu& z, uint32_t k)
//{
//  mf_ = mf0_.posteriorFromSSsample(x,z,k);
//}

template<typename T>
void MfBase<T>::posteriorFromSS(const vector<Matrix<T,Dynamic,1> > &x, const VectorXu& z, uint32_t k)
{
  mf_ = mf0_.posteriorFromSSsample(x,z,k);
  //TODO
//  uint32_t D = normalS_.D_;
//  Matrix<T,Dynamic,1> w(z.size());
//  w.setZero(z.size());
//  uint32_t N = 0;
//  for (int32_t i=0; i<z.size(); ++i)
//    if(z[i] == k)
//    {
//      w[i]=x[i](0); // counts
//      ++N;
//    }
//  if(N > 0)
//  {
//    Matrix<T,Dynamic,Dynamic> q(D,N);
//    uint32_t j=0;
//    for (int32_t i=0; i<z.size(); ++i)
//      if(z[i] == k)
//      {
//        q.col(j++) = x[i].middleRows(1,D);
//      }
//    normalS_.setMean(karcherMeanWeighted<T>(normalS_.getMean(), q, w, 100));
//    //TODO: slight permutation here for mu to allow proper sampling
//    // TODO: wastefull since it computes stuff for normals that are not used in the
//    // later computations
//    Matrix<T,Dynamic,Dynamic> x_mu = S_.Log_p_north(normalS_.getMean(),q);
//    Matrix<T,Dynamic,Dynamic> outer =  Matrix<T,Dynamic,Dynamic>::Zero(D-1,D-1);
//    j=0;
//    for (int32_t i=0; i<z.size(); ++i)
//      if(z[i] == k)
//      {
//        outer += w(i)* x_mu.col(j) * x_mu.col(j).transpose();
//		j++;
//      }
//    normalS_.setSigma(iw0_.posterior(outer, w.sum()).sample());
//
//  }else{
//    normalS_.setMean(S_.sampleUnif(normalS_.pRndGen_));
//    iw0_.resetSufficientStatistics();
//    normalS_.setSigma(iw0_.sample());
//  }
////  sample();
//  //  cout<<"Delta: \n"<<iw0_.posterior(x_mu,z,k).Delta_<<endl;
//  //  cout<<"Sigma: \n"<<normalS_.Sigma()<<endl;
////  cout<<"Sigma Eigs:"<<normalS_.Sigma().eigenvalues()<<endl;
//#ifndef NDEBUG
//  cout<<"NiwSphere<T>::posterior"<<endl
//    <<normalS_.getMean().transpose()<<endl
//    <<normalS_.Sigma()<<endl;
//#endif
//
//  // old
//	normal_ = mf0_.posteriorFromSS(x,z,k).sample();
}

//template<typename T>
//void MfBase<T>::posteriorFromSS(const Matrix<T,Dynamic,1> &x)
//{
//	normal_ = mf0_.posteriorFromSS(x).sample();
//}

template<typename T>
T MfBase<T>::logPdfUnderPrior() const
{
  return mf0_.logPdf(mf_);
};

//template<typename T>
//T MfBase<T>::logPdfUnderPriorMarginalized() const
//{
//  // evaluates log pdf of sufficient statistics stored within mf0_
////  mf0_.print();
//  return mf0_.logPdfMarginalized();
//};
//
//template<typename T>
//T MfBase<T>::logPdfUnderPriorMarginalizedMerged(
//    const shared_ptr<MfBase<T> >& other) const
//{
//  return mf0_.logPdfUnderPriorMarginalizedMerged(other->mf0_);
//};
//
//template<typename T>
//void MfBase<T>::sample()
//{
//  normal_ = mf0_.posterior().sample();
//};

template<typename T>
void MfBase<T>::print() const
{
  mf_.print();
//  mf0_.posterior().print();
//  normal_.print();
};

max_stars_repo_name: jstraub/dpMM

max_issues_repo_name: jstraub/dpMM

max_forks_repo_name: jstraub/dpMM


text:
/*=============================================================================
    Copyright (c) 2001-2011 Joel de Guzman

    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)
==============================================================================*/
#if !defined(FUSION_EQUAL_TO_05052005_1208)
#define FUSION_EQUAL_TO_05052005_1208

#include <boost/fusion/support/config.hpp>
#include <boost/fusion/support/is_iterator.hpp>
#include <boost/fusion/support/tag_of.hpp>
#include <boost/mpl/and.hpp>
#include <boost/type_traits/add_const.hpp>
#include <boost/type_traits/is_same.hpp>
#include <boost/utility/enable_if.hpp>

namespace boost {
namespace fusion {
// Special tags:
struct iterator_facade_tag;      // iterator facade tag
struct boost_array_iterator_tag; // boost::array iterator tag
struct mpl_iterator_tag;         // mpl sequence iterator tag
struct std_pair_iterator_tag;    // std::pair iterator tag

namespace extension {
template <typename Tag> struct equal_to_impl {
  // default implementation
  template <typename I1, typename I2>
  struct apply
      : is_same<typename add_const<I1>::type, typename add_const<I2>::type> {};
};

template <> struct equal_to_impl<iterator_facade_tag> {
  template <typename It1, typename It2, typename Tag1, typename Tag2>
  struct dispatch : mpl::false_ {};

  template <typename It1, typename It2, typename Tag>
  struct dispatch<It1, It2, Tag, Tag> // same tag
      : It1::template equal_to<It1, It2> {};

  template <typename It1, typename It2>
  struct apply
      : dispatch<It1, It2, typename It1::fusion_tag, typename It2::fusion_tag> {
  };
};

template <> struct equal_to_impl<boost_array_iterator_tag>;

template <> struct equal_to_impl<mpl_iterator_tag>;

template <> struct equal_to_impl<std_pair_iterator_tag>;
} // namespace extension

namespace result_of {
template <typename I1, typename I2>
struct equal_to
    : extension::equal_to_impl<
          typename detail::tag_of<I1>::type>::template apply<I1, I2> {};
} // namespace result_of

namespace iterator_operators {
template <typename Iter1, typename Iter2>
BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED inline typename boost::enable_if<
    mpl::and_<is_fusion_iterator<Iter1>, is_fusion_iterator<Iter2>>, bool>::type
operator==(Iter1 const &, Iter2 const &) {
  return result_of::equal_to<Iter1, Iter2>::value;
}

template <typename Iter1, typename Iter2>
BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED inline typename boost::enable_if<
    mpl::and_<is_fusion_iterator<Iter1>, is_fusion_iterator<Iter2>>, bool>::type
operator!=(Iter1 const &, Iter2 const &) {
  return !result_of::equal_to<Iter1, Iter2>::value;
}
} // namespace iterator_operators

using iterator_operators::operator==;
using iterator_operators::operator!=;
} // namespace fusion
} // namespace boost

#endif

ext: hpp

max_stars_repo_name: henrywarhurst/matrix

max_issues_repo_name: henrywarhurst/matrix

max_forks_repo_name: henrywarhurst/matrix


text:
//  Copyright (c) 2007-2013 Hartmut Kaiser
//
//  SPDX-License-Identifier: BSL-1.0
//  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)

#include <hpx/runtime/naming/address.hpp>

#include <hpx/errors.hpp>
#include <hpx/runtime/components/component_type.hpp>
#include <hpx/serialization/serialize.hpp>

#include <boost/io/ios_state.hpp>

#include <iomanip>
#include <iostream>

///////////////////////////////////////////////////////////////////////////////
namespace hpx { namespace naming
{
    template <typename Archive>
    void address::save(Archive& ar, const unsigned int version) const
    {
        ar & locality_ & type_ & address_;
    }

    template <typename Archive>
    void address::load(Archive& ar, const unsigned int version)
    {
        ar & locality_ & type_ & address_;
    }

    template HPX_EXPORT
    void address::save(serialization::output_archive&, const unsigned int) const;

    template HPX_EXPORT
    void address::load(serialization::input_archive&, const unsigned int);

    std::ostream& operator<<(std::ostream& os, address const& addr)
    {
        boost::io::ios_flags_saver ifs(os);
        os << "(" << addr.locality_ << ":"
           << components::get_component_type_name(addr.type_)
           << ":" << std::showbase << std::hex << addr.address_ << ")";
        return os;
    }
}}

ext: cpp

max_stars_repo_name: jnvance/hpx

max_issues_repo_name: jnvance/hpx

max_forks_repo_name: jnvance/hpx


text:
#ifndef RPCZ_APPLICATION_OPTIONS_H
#define RPCZ_APPLICATION_OPTIONS_H

#include <boost/thread.hpp>

namespace zmq {
class context_t;
}  // namespace zmq

namespace rpcz {

// Thread-safe.
class application_options
{
public:
  application_options(void);
  ~application_options(void);

public:
  static void set_zmq_context(zmq::context_t* context);
  static zmq::context_t* get_zmq_context();
  static void set_zmq_io_threads(int n);
  static int get_zmq_io_threads();
  static void set_connection_manager_threads(int n);
  static int get_connection_manager_threads();

 private:
  static boost::mutex mutex_;
  typedef boost::lock_guard<boost::mutex> lock_guard;

 private:
  // Number of connection manager threads. Those threads are used for
  // running user code: handling server requests or running callbacks.
  static int connection_manager_threads_;  // default 1

  // ZeroMQ context to use for our application. If NULL, then application will
  // construct its own ZeroMQ context and own it. If you provide your own
  // ZeroMQ context, application will not take ownership of it. The ZeroMQ
  // context must outlive the rpcz application.
  static zmq::context_t* zmq_context_;  // default NULL

  // Number of ZeroMQ I/O threads, to be passed to zmq_init(). This value is
  // ignored when you provide your own ZeroMQ context.
  static int zmq_io_threads_;  // default 1

};  // class application_options

}  // namespace rpcz

#endif  // RPCZ_APPLICATION_OPTIONS_H

max_issues_repo_name: ericyonng/shiny-engine

max_forks_repo_name: ericyonng/shiny-engine


text:
//
// Created by denn on 06/10/2018.
//

#define BOOST_TEST_MODULE requests

#include "milecsa_jsonrpc.hpp"

#include <optional>
#include <boost/test/included/unit_test.hpp>

std::string node_url = "https://lotus000.testnet.mile.global/v1/api";

struct RequestsEval {

    using Url = milecsa::rpc::Url;

    milecsa::ErrorHandler error_handler = [](milecsa::result code, std::string error){
        BOOST_TEST_MESSAGE("Request Error: " + error);
    };

    milecsa::http::ResponseHandler response_handler = [&](const milecsa::http::status code, const std::string &method, const milecsa::http::response &http){
        std::cerr << "Response["<<code<<"] "<<method<<" error: " << http.result() << std::endl << http << std::endl;
    };

    bool getzeroblock(const std::string &u = node_url) {

        uint256_t start_position_1(0);

        auto client_tt = milecsa::rpc::Client::Connect(u,false, response_handler, error_handler);
        if (!client_tt) {
            BOOST_TEST_MESSAGE(" getzeroblock error ");
            return false;
        }

        milecsa::rpc::response r = client_tt->get_block(start_position_1);

        BOOST_TEST_MESSAGE(" -- ");
        BOOST_TEST_MESSAGE("Zero Block: " + r->dump());

        return true;
    }

    bool test(const std::string &u = node_url) {
        if (auto rpc = milecsa::rpc::Client::Connect(u, true, response_handler, error_handler)) {

            BOOST_TEST_MESSAGE("Ping : " + StringFormat("%l", *rpc->ping()));

            if (auto last_block_id = rpc->get_current_block_id()){

                BOOST_TEST_MESSAGE(" -- ");
                BOOST_TEST_MESSAGE("Id   : " + UInt256ToDecString(*last_block_id));

                BOOST_TEST_MESSAGE(" -- ");
                BOOST_TEST_MESSAGE("Block: " + rpc->get_block(*last_block_id)->dump());

            }
            BOOST_TEST_MESSAGE(" -- ");
            BOOST_TEST_MESSAGE("Info : " + rpc->get_blockchain_info()->dump());

            BOOST_TEST_MESSAGE(" -- ");
            BOOST_TEST_MESSAGE("State: " + rpc->get_blockchain_state()->dump());

            auto pk = "EUjuoTty9oHdF8h7ab4u3KCCci5dduFxvJbqAx5qXUUtk2Wnx";
            BOOST_TEST_MESSAGE(" -- ");
            BOOST_TEST_MESSAGE("Wallet: " + rpc->get_wallet_state(pk)->dump());

            BOOST_TEST_MESSAGE(" -- ");
            BOOST_TEST_MESSAGE("Trxs  : " + rpc->get_wallet_transactions(pk, 5)->dump());

            BOOST_TEST_MESSAGE(" -- ");
            BOOST_TEST_MESSAGE("NW State: " + rpc->get_network_state()->dump());

            BOOST_TEST_MESSAGE(" -- ");
            BOOST_TEST_MESSAGE("NW Nodes: " + rpc->get_nodes()->dump());

            return true;
        }
        return false;
    }
};

BOOST_FIXTURE_TEST_CASE( requests, RequestsEval )
{
    milecsa::rpc::Client::timeout = 20;
    BOOST_CHECK(test());
    BOOST_CHECK(getzeroblock());
}

max_stars_repo_name: mile-core/mile-csa-jsonrpc-client

max_issues_repo_name: mile-core/mile-csa-jsonrpc-client

max_forks_repo_name: mile-core/mile-csa-jsonrpc-client


text:
/*
  Copyright (C) 2021 Xilinx, Inc

  Licensed under the Apache License, Version 2.0 (the "License"). You may
  not use this file except in compliance with the License. A copy of the
  License is located at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  License for the specific language governing permissions and limitations
  under the License.
 */

// ------ I N C L U D E   F I L E S -------------------------------------------
// Local - Include Files
#include "ReportAieShim.h"
#include "core/common/query_requests.h"
#include "core/common/device.h"
#include <boost/optional/optional.hpp>
#include <boost/property_tree/json_parser.hpp>

#define fmt4(x) boost::format("%4s%-22s: " x "\n") % " "
#define fmt8(x) boost::format("%8s%-22s: " x "\n") % " "
#define fmt12(x) boost::format("%12s%-22s: " x "\n") % " "
#define fmt16(x) boost::format("%16s%-22s: " x "\n") % " "

namespace qr = xrt_core::query;

static void
addnodelist(std::string search_str, std::string node_str,boost::property_tree::ptree& input_pt, boost::property_tree::ptree& output_pt)
{
  boost::property_tree::ptree pt_array;
  for (auto& node: input_pt.get_child(search_str)) {
    boost::property_tree::ptree pt;
    std::string val;
    for (auto& value: node.second)
      val +=(val.empty()?"":", ")+ value.second.data();

    pt.put("name", node.first);
    pt.put("value", val);
    pt_array.push_back(std::make_pair("", pt));
  }
  output_pt.add_child(node_str, pt_array);
}

/*
{
    "aie_shim": {
        "0_0": {
            "col": "0",
            "row": "0",
            "dma": {
                "Channel_status": {
                    "MM2S": [
                        "Running"
                    ],
                    "S2MM": [
                        "Stalled_on_lock"
                    ]
                },
                "Mode": {
                    "MM2S": [
                        "A_B"
                    ],
                    "S2MM": [
                        "FIFO",
                        "Packet_Switching"
                    ]
                },
                "Queue_size": {
                    "MM2S": [
                        "2"
                    ],
                    "S2MM": [
                        "3"
                    ]
                },
                "Queue_status": {
                    "MM2S": [
                        "channel0_overflow"
                    ],
                    "S2MM": [
                        "channel0_overflow"
                    ]
                },
                "Current_BD": {
                    "MM2S": [
                        "3"
                    ],
                    "S2MM": [
                        "2"
                    ]
                },
                "Lock_ID": {
                    "MM2S": [
                        "1"
                    ],
                    "S2MM": [
                        "2"
                    ]
                }
            },
            "lock": {
                "lock0": [
                    "Acquired_for_read"
                ],
                "lock1": [
                    "Acquired_for_write"
                ]
            },
            "errors": {
                "Core_module": {
                    "Bus": [
                        "AXI-MM_slave_error"
                    ]
                },
                "Memory_module": {
                    "ECC": [
                        "DM_ECC_error_scrub_2-bit",
                        "DM_ECC_error_2-bit"
                    ]
                },
                "PL_module": {
                    "DMA": [
                        "DMA_S2MM_0_error",
                        "DMA_MM2S_1_error"
                    ]
                }
            },
            "event": {
                "Core_module": [
                    "Perf_Cnt0",
                    "PC_0",
                    "Memory_Stall"
                ],
                "Memory_module": [
                    "Lock_0_Acquired",
                    "DMA_S2MM_0_go_to_idle"
                ],
                "PL_module": [
                    "DMA_S2MM_0_Error",
                    "Lock_0_Acquired"
                ]
            }
        },
        ....
*/
void
populate_aie_shim(const xrt_core::device * device, const std::string& desc, boost::property_tree::ptree& pt)
{
  pt.put("description", desc);
  boost::property_tree::ptree _pt;

  try {
  std::string aie_data = xrt_core::device_query<qr::aie_shim_info>(device);
    std::stringstream ss(aie_data);
    boost::property_tree::read_json(ss, _pt);
  } catch (const std::exception& ex){
    pt.put("error_msg", ex.what());
    return;
  }

  try {
    boost::property_tree::ptree tile_array;
    for (auto& as: _pt.get_child("aie_shim")) {
      boost::property_tree::ptree& oshim = as.second;
      boost::property_tree::ptree ishim;
      int col = oshim.get<uint32_t>("col");
      int row = oshim.get<uint32_t>("row");

      ishim.put("column", col);
      ishim.put("row", row);

      std::string mode;
      boost::property_tree::ptree empty_pt;
      for (auto& node: oshim.get_child("dma.Mode.MM2S", empty_pt)) {
        mode +=(mode.empty()?"":", ")+node.second.data();
      }

      if(!mode.empty())
        ishim.put("dma.mm2s.mode", mode);

      mode.clear();
      for (auto& node: oshim.get_child("dma.Mode.S2MM", empty_pt)) {
        mode +=(mode.empty()?"":", ")+node.second.data();
      }

      if(!mode.empty())
        ishim.put("dma.s2mm.mode", mode);

      boost::property_tree::ptree mm2s_array;
      auto queue_size = oshim.get_child("dma.Queue_size.MM2S").begin();
      auto queue_status = oshim.get_child("dma.Queue_status.MM2S").begin();
      auto current_bd = oshim.get_child("dma.Current_BD.MM2S").begin();
      auto lock_id = oshim.get_child("dma.Lock_ID.MM2S").begin();
      int id = 0;
      for (auto& node : oshim.get_child("dma.Channel_status.MM2S")) {
        boost::property_tree::ptree channel;
        channel.put("id", id);
        channel.put("channel_status", node.second.data());
        channel.put("queue_size", queue_size->second.data());
        channel.put("queue_status", queue_status->second.data());
        channel.put("current_bd", current_bd->second.data());
        channel.put("lock_id", lock_id->second.data());
        queue_size++;
        queue_status++;
        current_bd++;
        lock_id++;
        mm2s_array.push_back(std::make_pair("", channel));
      }
      ishim.add_child("dma.mm2s.channel", mm2s_array);

      boost::property_tree::ptree s2mm_array;
      queue_size = oshim.get_child("dma.Queue_size.S2MM").begin();
      queue_status = oshim.get_child("dma.Queue_status.S2MM").begin();
      current_bd = oshim.get_child("dma.Current_BD.S2MM").begin();
      lock_id = oshim.get_child("dma.Lock_ID.S2MM").begin();
      id = 0;
      for (auto& node : oshim.get_child("dma.Channel_status.S2MM")) {
        boost::property_tree::ptree channel;
        channel.put("id", id);
        channel.put("channel_status", node.second.data());
        channel.put("queue_size", queue_size->second.data());
        channel.put("queue_status", queue_status->second.data());
        channel.put("current_bd", current_bd->second.data());
        channel.put("lock_id", lock_id->second.data());
        queue_size++;
        queue_status++;
        current_bd++;
        lock_id++;
        s2mm_array.push_back(std::make_pair("", channel));
      }
      ishim.add_child("dma.s2mm.channel", s2mm_array);

      addnodelist("lock", "locks", oshim, ishim);
      boost::property_tree::ptree module_array;
      for (auto& node : oshim.get_child("errors", empty_pt)) {
        boost::property_tree::ptree module;
        module.put("module",node.first);
        boost::property_tree::ptree type_array;
        for (auto& type : node.second) {
          boost::property_tree::ptree enode;
          enode.put("name",type.first);
          std::string val;
          for (auto& value: type.second)
            val +=(val.empty()?"":", ")+ value.second.data();
          enode.put("value", val);
          type_array.push_back(std::make_pair("", enode));
        }
        module.add_child("error", type_array);
        module_array.push_back(std::make_pair("", module));
      }
      ishim.add_child("errors", module_array);

      addnodelist("event", "events", oshim, ishim);
      tile_array.push_back(std::make_pair("tile"+std::to_string(col),ishim));
    }
    pt.add_child("tiles",tile_array);
  } catch (const std::exception& ex){
    pt.put("error_msg", (boost::format("%s %s") % ex.what() % "found in the AIE shim"));
  }

}

void
ReportAieShim::getPropertyTreeInternal(const xrt_core::device * _pDevice,
                                   boost::property_tree::ptree &_pt) const
{
  // Defer to the 20202 format.  If we ever need to update JSON data,
  // Then update this method to do so.
  getPropertyTree20202(_pDevice, _pt);
}

void
ReportAieShim::getPropertyTree20202(const xrt_core::device * _pDevice,
                                boost::property_tree::ptree &_pt) const
{
  boost::property_tree::ptree pt;
  populate_aie_shim(_pDevice, "Aie_Shim_Status", pt);
  _pt.add_child("aie_shim_status", pt);
}

void
ReportAieShim::writeReport(const xrt_core::device * _pDevice,
                       const std::vector<std::string> & /*_elementsFilter*/,
                       std::iostream & _output) const
{
  boost::property_tree::ptree _pt;
  boost::property_tree::ptree empty_ptree;
  getPropertyTreeInternal(_pDevice, _pt);

  _output << "Aie\n";
  _output << boost::format("  %-10s\n") % _pt.get<std::string>("aie_shim_status.description");

  try {
    int count = 0;
    for (auto& tile: _pt.get_child("aie_shim_status.tiles")) {
      _output << boost::format("Tile[%2d]\n") % count++;
      _output << fmt4("%d") % "Column" % tile.second.get<int>("column");
      _output << fmt4("%d") % "Row" % tile.second.get<int>("row");
      if(tile.second.find("dma") != tile.second.not_found()) {
        _output << boost::format("    %s:\n") % "DMA";
        _output << boost::format("        %s:\n") % "MM2S";
        _output << fmt12("%s") % "Mode" % tile.second.get<std::string>("dma.mm2s.mode");

        _output << boost::format("            %s:\n") % "Channel";
        for(auto& node : tile.second.get_child("dma.mm2s.channel")) {
          _output << fmt16("%s") % "Id" % node.second.get<std::string>("id");
          _output << fmt16("%s") % "Channel Status" % node.second.get<std::string>("channel_status");
          _output << fmt16("%s") % "Queue Size" % node.second.get<std::string>("queue_size");
          _output << fmt16("%s") % "Queue Status" % node.second.get<std::string>("queue_status");
          _output << fmt16("%s") % "Current BD" % node.second.get<std::string>("current_bd");
          _output << fmt16("%s") % "Lock ID" % node.second.get<std::string>("lock_id");
          _output << std::endl;
        }

        _output << boost::format("        %s:\n") % "S2MM";
        _output << fmt12("%s") % "Mode" % tile.second.get<std::string>("dma.s2mm.mode");

        _output << boost::format("            %s:\n") % "Channel";
        for(auto& node : tile.second.get_child("dma.s2mm.channel")) {
          _output << fmt16("%s") % "Id" % node.second.get<std::string>("id");
          _output << fmt16("%s") % "Channel Status" % node.second.get<std::string>("channel_status");
          _output << fmt16("%s") % "Queue Size" % node.second.get<std::string>("queue_size");
          _output << fmt16("%s") % "Queue Status" % node.second.get<std::string>("queue_status");
          _output << fmt16("%s") % "Current BD" % node.second.get<std::string>("current_bd");
          _output << fmt16("%s") % "Lock ID" % node.second.get<std::string>("lock_id");
          _output << std::endl;
        }
      }

      if(tile.second.find("locks") != tile.second.not_found()) {
        _output << boost::format("    %s:\n") % "Locks";
        for(auto& node : tile.second.get_child("locks",empty_ptree)) {
          _output << fmt8("%s")  % node.second.get<std::string>("name")
                                 % node.second.get<std::string>("value");
        }
        _output << std::endl;
      }

      if(tile.second.find("errors") != tile.second.not_found()) {
        _output << boost::format("    %s:\n") % "Errors";
        for(auto& node : tile.second.get_child("errors",empty_ptree)) {
          _output << boost::format("        %s:\n") % node.second.get<std::string>("module");
          for(auto& enode : node.second.get_child("error",empty_ptree)) {
            _output << fmt12("%s")  % enode.second.get<std::string>("name")
                                    % enode.second.get<std::string>("value");
          }
        }
        _output << std::endl;
      }

      if(tile.second.find("events") != tile.second.not_found()) {
        _output << boost::format("    %s:\n") % "Events";
        for(auto& node : tile.second.get_child("events",empty_ptree)) {
          _output << fmt8("%s")  % node.second.get<std::string>("name")
                                 % node.second.get<std::string>("value");
        }
        _output << std::endl;
      }
    }
  } catch(std::exception const& e) {
    _output <<  e.what() << std::endl;
  }
  _output << std::endl;
}

max_stars_repo_name: Siddhesh-Ghadi/XRT

max_issues_repo_name: Siddhesh-Ghadi/XRT

max_forks_repo_name: Siddhesh-Ghadi/XRT


text:
Executing ssh-askpass to query the password...
Warning: Remote host denied X11 forwarding, perhaps xauth program could not be run on the server side.
// (C) Copyright Jeremy Siek 2001. Permission to copy, use, modify,
// sell and distribute this software is granted provided this
// copyright notice appears in all copies. This software is provided
// "as is" without express or implied warranty, and with no claim as
// to its suitability for any purpose.

#include <boost/config.hpp>

// UNDER CONSTRUCTION

namespace boost {

  namespace detail {

    template <typename SizeType>
    struct intset_iterator_policies : public default_iterator_policies
    {
      intset_iterator_policies(const SizeType* value_ptr)
        : m_value(value_ptr) { }

      SizeType dereference(type<SizeType>, const SizeType& x) {
        return m_value[x];
      }
      SizeType* m_value;
    };

    template <typename SizeType,
              typename Allocator = std::allocator<SizeType> >
    class intset
    {
      typedef intset self;
      typedef intset_iterator_policies<size_type> policies_t;
    public:
      typedef SizeType size_type;

      typedef typename iterator_adaptor<size_type,
        policies_t, size_type, size_type, size_type*,
        std::input_iterator_tag, std::ptrdiff_t> iterator;
      typedef iterator const_iterator;

      intset(size_type n, const Allocator alloc = Allocator)
        : m_index(n + 1, alloc), m_value(n + 1, alloc), m_next(0)
        { }

      bool test(size_type pos) const {
        BOOST_ASSERT_THROW
          (pos < size(), std::out_of_range("boost::intset::test(pos)"));
        if (m_index[pos] < m_next && m_index[x] >= 0)
          if (m_value[index[x]] == x)
            return true;
        return false;
      }

      self& set(size_type pos, int val = true)
      {
        BOOST_ASSERT_THROW
          (pos < size(), std::out_of_range("boost::intset::set(pos,val)"));
        if (!test(pos)) {
          ++m_next;
          m_value[m_next] = pos;
          m_index[pos] = m_next;
        }
        return *this;
      }

      self& reset(size_type pos) {
        BOOST_ASSERT_THROW
          (pos < size(), std::out_of_range("boost::intset::reset(pos)"));
        if (test(pos)) {
          m_value[m_index[pos]] = m_value[m_next];
          m_index[m_value[m_next]] = m_index[x];
          ++m_next;
        }
      }

      iterator begin() const {
        return iterator(0, policies_t(&m_value[0]));
      }
      iterator end() const {
        return iterator(m_next, policies_t(&m_value[0]));
      }

    private:
      std::vector<size_type, Allocator> m_index;
      std::vector<size_type, Allocator> m_value;
      size_type m_next;
    };

  } // namespace detail

} // namespace boost


text:
#include "UnknownCommandHandler.h"

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

UnknownCommandHandler::UnknownCommandHandler(
		core::IDisplayerPtr displayer,
		ICommandRegistererPtr commandRegisterer)
	:_displayer(displayer),
	 _commandRegisterer(commandRegisterer)
{

}

UnknownCommandHandler::~UnknownCommandHandler()
{

}

void UnknownCommandHandler::handle(std::string input)
{
	auto commands = _commandRegisterer->getCommands();

	for (auto iter = commands.begin(); iter != commands.end(); ++iter)
		_displayer->displayLine(*iter);
}

void UnknownCommandHandler::handleResponse(rapidjson::Document& response)
{

}

std::string UnknownCommandHandler::getCommand()
{
	return "#help";
}

std::string UnknownCommandHandler::getResponseCommand()
{
	return "#responseHelp";
}

std::string UnknownCommandHandler::getInfo()
{
	return "#help [displays available commands]";
}


text:
/*
 *   Copyright (c) 2007, Mathieu Champlon
 *   All rights reserved.
 *
 *   Redistribution  and use  in source  and binary  forms, with  or without
 *   modification, are permitted provided  that the following conditions are
 *   met :
 *
 *   . Redistributions  of  source  code  must  retain  the  above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   . Redistributions in  binary form  must reproduce  the above  copyright
 *     notice, this list of conditions  and the following disclaimer in  the
 *     documentation and/or other materials provided with the distribution.
 *
 *   . Neither  the name  of  the  copyright  holders  nor the names  of the
 *     contributors may be used to endorse  or promote products derived from
 *     this software without specific prior written permission.
 *
 *   THIS SOFTWARE  IS  PROVIDED  BY THE  COPYRIGHT HOLDERS  AND CONTRIBUTORS
 *   ``AS IS''  AND ANY  EXPRESS OR  IMPLIED WARRANTIES,  INCLUDING,  BUT NOT
 *   LIMITED TO, THE IMPLIED  WARRANTIES  OF MERCHANTABILITY AND  FITNESS FOR
 *   A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE THE COPYRIGHT
 *   OWNERS OR CONTRIBUTORS  BE LIABLE FOR ANY  DIRECT, INDIRECT, INCIDENTAL,
 *   SPECIAL,  EXEMPLARY,  OR  CONSEQUENTIAL   DAMAGES  (INCLUDING,  BUT  NOT
 *   LIMITED TO,  PROCUREMENT OF SUBSTITUTE  GOODS OR SERVICES;  LOSS OF USE,
 *   DATA, OR PROFITS; OR  BUSINESS INTERRUPTION) HOWEVER CAUSED  AND ON  ANY
 *   THEORY  OF  LIABILITY,  WHETHER IN  CONTRACT,  STRICT LIABILITY, OR TORT
 *   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY  WAY  OUT OF  THE USE
 *   OF THIS SOFTWARE, EVEN  IF  ADVISED OF  THE POSSIBILITY  OF SUCH DAMAGE.
 */

#include "xeuseuleu_test_pch.h"
#include <xeuseuleu/xsl.hpp>
#include <boost/filesystem.hpp>
#include <boost/filesystem/detail/utf8_codecvt_facet.hpp>
#include <fstream>

namespace
{
    const std::string load( const std::string& filename )
    {
        std::ifstream ifs( filename.c_str() );
        if( ! ifs )
            throw std::runtime_error( "File " + filename + " not found" );
        return std::string( std::istreambuf_iterator< char >( ifs ), std::istreambuf_iterator< char >() );
    }
}

// -----------------------------------------------------------------------------
// Name: tranformation_with_a_non_existing_stylesheet_throws
// Created: MCO 2013-03-19
// -----------------------------------------------------------------------------
BOOST_AUTO_TEST_CASE( tranformation_with_a_non_existing_stylesheet_throws )
{
    BOOST_CHECK_THROW( xsl::xftransform( "non-existing.xsl", "file" ), xsl::exception );
}

// -----------------------------------------------------------------------------
// Name: tranformation_creates_a_file
// Created: SLI 2007-09-07
// -----------------------------------------------------------------------------
BOOST_AUTO_TEST_CASE( tranformation_creates_a_file )
{
    const std::string filename = "file";
    {
        xsl::xftransform xf( "stylesheet.xsl", filename );
        xf << xml::start( "root" )
           << xml::end;
    }
    BOOST_REQUIRE_EQUAL(
        "<?xml version=\"1.0\" encoding=\"UTF-8\"?><new-root/>",
        load( filename ) );
    std::remove( filename.c_str() );
}

// -----------------------------------------------------------------------------
// Name: tranformation_uses_a_stylesheet_with_unicode_name
// Created: MCO 2013-03-19
// -----------------------------------------------------------------------------
BOOST_AUTO_TEST_CASE( tranformation_uses_a_stylesheet_with_unicode_name )
{
    std::string stylesheet;
    xml::xifstream( "japanese.xml" )
        >> xml::start( "root" )
            >> xml::attribute( "name", stylesheet );
    stylesheet += ".xsl";
    const boost::filesystem::path path(
        stylesheet.c_str(),
        boost::filesystem::detail::utf8_codecvt_facet() );
    boost::filesystem::copy_file(
        "stylesheet.xsl",
        path,
        boost::filesystem::copy_option::overwrite_if_exists );
    const std::string filename = "file";
    {
        xsl::xftransform xf( stylesheet, filename );
        xf << xml::start( "root" )
           << xml::end;
    }
    BOOST_REQUIRE_EQUAL(
        "<?xml version=\"1.0\" encoding=\"UTF-8\"?><new-root/>",
        load( filename ) );
    boost::filesystem::remove( path );
    std::remove( filename.c_str() );
}

// -----------------------------------------------------------------------------
// Name: tranformation_creates_a_file_with_unicode_name
// Created: MCO 2013-03-19
// -----------------------------------------------------------------------------
BOOST_AUTO_TEST_CASE( tranformation_creates_a_file_with_unicode_name )
{
    std::string filename;
    xml::xifstream( "japanese.xml" )
        >> xml::start( "root" )
            >> xml::attribute( "name", filename );
    const boost::filesystem::path path(
        filename.c_str(),
        boost::filesystem::detail::utf8_codecvt_facet() );
    boost::filesystem::remove( path );
    {
        xsl::xftransform xf( "stylesheet.xsl", filename );
        xf << xml::start( "root" );
    }
    BOOST_CHECK( boost::filesystem::remove( path ) );
}


text:
#pragma once

#include "common.hpp"
#include "sessions.hpp"

#include <boost/asio/io_context.hpp>
#include <boost/asio/ip/address.hpp>
#include <boost/beast/http/message.hpp>
#include <boost/beast/http/string_body.hpp>
#include <boost/beast/websocket.hpp>
#include <boost/url/url_view.hpp>

#include <string>
#include <string_view>

namespace crow
{

struct Request
{
    boost::beast::http::request<boost::beast::http::string_body>& req;
    boost::beast::http::fields& fields;
    std::string_view url{};
    boost::urls::url_view urlView{};
    boost::urls::url_view::params_type urlParams{};
    bool isSecure{false};

    const std::string& body;

    boost::asio::io_context* ioService{};
    boost::asio::ip::address ipAddress{};

    std::shared_ptr<persistent_data::UserSession> session;

    std::string userRole{};
    Request(
        boost::beast::http::request<boost::beast::http::string_body>& reqIn) :
        req(reqIn),
        fields(reqIn.base()), body(reqIn.body())
    {}

    boost::beast::http::verb method() const
    {
        return req.method();
    }

    std::string_view getHeaderValue(std::string_view key) const
    {
        return req[key];
    }

    std::string_view getHeaderValue(boost::beast::http::field key) const
    {
        return req[key];
    }

    std::string_view methodString() const
    {
        return req.method_string();
    }

    std::string_view target() const
    {
        return req.target();
    }

    unsigned version() const
    {
        return req.version();
    }

    bool isUpgrade() const
    {
        return boost::beast::websocket::is_upgrade(req);
    }

    bool keepAlive() const
    {
        return req.keep_alive();
    }
};

} // namespace crow

max_stars_repo_name: pachu-nc/bmcweb

max_issues_repo_name: pachu-nc/bmcweb

max_forks_repo_name: pachu-nc/bmcweb


text:
// All content Copyright (C) 2018 Genomics plc
#define BOOST_TEST_DYN_LINK
#include <boost/test/unit_test.hpp>

#include <iostream>

#include "assembly/node.hpp"
#include "common.hpp"

using wecall::assembly::Node;

BOOST_AUTO_TEST_CASE( testIsolatedNode )
{
    auto node = std::make_shared< Node >( 'A', 'C' );

    BOOST_CHECK_EQUAL( node->lastCharacter(), 'C' );
    BOOST_CHECK( not node->isRegular() );
    BOOST_CHECK( node->isBranch() );
    BOOST_CHECK( node->isTerminal() );
}

BOOST_AUTO_TEST_CASE( testRegularNode )
{
    auto node = std::make_shared< Node >( 'A', 'C' );
    auto inNode = std::make_shared< Node >( 'G', 'T' );
    auto outNode = std::make_shared< Node >( 'T', 'G' );

    node->addInEdge( inNode );
    node->addOutEdge( outNode, 0 );

    BOOST_CHECK( node->isRegular() );
    BOOST_CHECK( not node->isBranch() );
    BOOST_CHECK( not node->isTerminal() );
    BOOST_CHECK_EQUAL( ( *node->begin() ).lastCharacter(), 'G' );
}

max_stars_repo_name: dylex/wecall

max_issues_repo_name: dylex/wecall

max_forks_repo_name: dylex/wecall


text:
// Copyright (C) 2013 by Glyn Matthews
// Copyright 2011 Dean Michael Berris <dberris@google.com>.
// Copyright 2011 Google, Inc.
// 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 NETWORK_HTTP_V2_CLIENT_CONNECTION_ASYNC_RESOLVER_INC
#define NETWORK_HTTP_V2_CLIENT_CONNECTION_ASYNC_RESOLVER_INC

/**
 * \file
 * \brief
 */

#include <functional>
#include <boost/asio/ip/tcp.hpp>

namespace network {
  namespace http {
    inline namespace v2 {
      namespace client_connection {
        /**
         * \class async_resolver network/http/v2/client/connection/async_resolver.hpp
         * \brief Resolves and maintains a cache of hosts.
         */
        class async_resolver {

          async_resolver(const async_resolver &) = delete;
          async_resolver &operator = (const async_resolver &) = delete;

        public:

          /**
           * \brief resolver
           */
          typedef boost::asio::ip::tcp::resolver resolver;

          /**
           * \brief resolver_iterator
           */
          typedef resolver::iterator resolver_iterator;

          /**
           * \typedef resolve_callback
           */
          typedef std::function<void (const boost::system::error_code &,
                                      resolver_iterator)> resolve_callback;

          /**
           * \brief Constructor.
           */
          async_resolver() {

          }

          /**
           * \brief Destructor.
           */
          virtual ~async_resolver() noexcept {

          }

          /**
           * \brief Resolves a host asynchronously.
           * \param host The hostname to resolve.
           * \param port The port number.
           * \param callback A callback handler.
           */
          virtual void async_resolve(const std::string &host, std::uint16_t port,
                                     resolve_callback handler) = 0;

          /**
           * \brief Clears the cache of already resolved endpoints.
           */
          virtual void clear_resolved_cache() = 0;

        };
      } // namespace client_connection
    } // namespace v2
  } // namespace http
} // namespace network

#endif // NETWORK_HTTP_V2_CLIENT_CONNECTION_ASYNC_RESOLVER_INC

max_stars_repo_name: project-zerus/cpp-netlib

max_issues_repo_name: project-zerus/cpp-netlib

max_forks_repo_name: project-zerus/cpp-netlib


text:
#include "profile3d.hpp"
#include <boost/python.hpp>
#include <pyublas/numpy.hpp>
#include "optimization.hpp"
#include "rootfinder.hpp"

namespace gd {
using namespace boost::python;

void py_export_profile_3d() {
	class_< ProfileModel3d, boost::noncopyable >("ProfileModel3d", no_init)
		;
	class_<ProfileModel3d1C, bases<ProfileModel3d>, boost::noncopyable  >("ProfileModel3d1C", init<Profile3d*>())
		.def("density",   (&ProfileModel3d1C::density))
		.def("potential", (&ProfileModel3d1C::potential))
		.def("dphidx", (&ProfileModel3d1C::dphidx))
		.def("dphidy", (&ProfileModel3d1C::dphidy))
		.def("dphidz", (&ProfileModel3d1C::dphidz))
		;
	class_<ProfileModel3d2C, bases<ProfileModel3d>, boost::noncopyable  >("ProfileModel3d2C", init<Profile3d*,Profile3d*>())
		.def("density",   (&ProfileModel3d2C::density))
		.def("potential", (&ProfileModel3d2C::potential))
		.def("dphidx", (&ProfileModel3d2C::dphidx))
		.def("dphidy", (&ProfileModel3d2C::dphidy))
		.def("dphidz", (&ProfileModel3d2C::dphidz))
		;
	class_< Profile3d, boost::noncopyable >("Profile3d", no_init)
		;
	class_< Density3d, boost::noncopyable >("Density3d", no_init)
		;

	class_<NFW3d, bases<Profile3d, Density3d> >("NFW3d", init<double, double, double, double>())
		.def("density",   (&NFW3d::density))
		.def("potential", (&NFW3d::potential))
		.def("dphidx", (&NFW3d::dphidx))
		.def("dphidy", (&NFW3d::dphidy))
		.def("dphidz", (&NFW3d::dphidz))
		.def_readonly("c", &NFW3d::c)
		.def_readonly("mass200", &NFW3d::mass200)
		.def_readonly("r200", &NFW3d::r200)
		.def_readonly("rs", &NFW3d::rs)
		.def_readonly("rho0", &NFW3d::rho0);
	;
	class_<NFW3dTriax, bases<Profile3d, Density3d> >("NFW3dTriax", init<double, double, double, double, double, double, double, double>())
		.def("density",   (&NFW3dTriax::density))
		.def("potential", (&NFW3dTriax::potential))
		.def("dphidx", (&NFW3dTriax::dphidx))
		.def("dphidy", (&NFW3dTriax::dphidy))
		.def("dphidz", (&NFW3dTriax::dphidz))
		.def_readonly("c", &NFW3dTriax::c)
		.def_readonly("mass200", &NFW3dTriax::mass200)
		.def_readonly("r200", &NFW3dTriax::r200)
		.def_readonly("rs", &NFW3dTriax::rs)
		.def_readonly("rho0", &NFW3dTriax::rho0);
	;
	class_<MiyamotoNagai3d, bases<Profile3d, Density3d> >("MiyamotoNagai3d", init<double, double, double, double>())
		.def("density",   (&MiyamotoNagai3d::density))
		.def("potential", (&MiyamotoNagai3d::potential))
		.def("dphidx", (&MiyamotoNagai3d::dphidx))
		.def("dphidy", (&MiyamotoNagai3d::dphidy))
		.def("dphidz", (&MiyamotoNagai3d::dphidz))
		.def_readonly("a", &MiyamotoNagai3d::a)
		.def_readonly("b", &MiyamotoNagai3d::b)
		.def_readonly("mass", &MiyamotoNagai3d::mass)
	;

}

}

max_stars_repo_name: maartenbreddels/mab

max_issues_repo_name: maartenbreddels/mab

max_forks_repo_name: maartenbreddels/mab


text:
#include <exception>
#include <iostream>

#include <boost/python/tuple.hpp>

/*****************************************************************************************/
#include <boost/python/stl_iterator.hpp>
using namespace boost::python;

/* Read a ROS message from a serialized string.
*/
template <typename M>
M ros_from_python(const std::string str_msg)
{
  size_t serial_size = str_msg.size();
  boost::shared_array<uint8_t> buffer(new uint8_t[serial_size]);
  for (size_t i = 0; i < serial_size; ++i)
  {
    buffer[i] = str_msg[i];
  }
  ros::serialization::IStream stream(buffer.get(), serial_size);
  M msg;
  ros::serialization::Serializer<M>::read(stream, msg);
  return msg;
}

/* Write a ROS message into a serialized string.
*/
template <typename M>
std::string ros_to_python(const M& msg)
{
  size_t serial_size = ros::serialization::serializationLength(msg);
  boost::shared_array<uint8_t> buffer(new uint8_t[serial_size]);
  ros::serialization::OStream stream(buffer.get(), serial_size);
  ros::serialization::serialize(stream, msg);
  std::string str_msg;
  str_msg.reserve(serial_size);
  for (size_t i = 0; i < serial_size; ++i)
  {
    str_msg.push_back(buffer[i]);
  }
  return str_msg;
}

template< typename T >
inline
std::vector< T > to_std_vector( const boost::python::list& iterable )
{
  try {
    return std::vector< T >( boost::python::stl_input_iterator< T >( iterable ),
                             boost::python::stl_input_iterator< T >( ) );
  } catch (std::exception ex) {
    std::cerr << ex.what() << std::endl;
    return std::vector<T>();
  }
}

// Extracted from https://gist.github.com/avli/b0bf77449b090b768663.
template<class T>
struct vector_to_python
{
  static PyObject* convert(const std::vector<T>& vec)
  {
    boost::python::list* l = new boost::python::list();
    for(std::size_t i = 0; i < vec.size(); i++)
      (*l).append(vec[i]);

    return l->ptr();
  }
};

/*****************************************************************************************/


text:
// Copyright 2022 Dennis Hezel
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "agrpc/asioGrpc.hpp"
#include "protos/test.grpc.pb.h"
#include "utils/asioUtils.hpp"
#include "utils/grpcClientServerTest.hpp"
#include "utils/grpcContextTest.hpp"

#include <doctest/doctest.h>

#include <cstddef>
#include <optional>
#include <thread>

namespace test_asio_grpc
{
TEST_SUITE_BEGIN(ASIO_GRPC_TEST_CPP_VERSION* doctest::timeout(180.0));

TEST_CASE("GrpcExecutor fulfills Executor TS traits")
{
    using Exec = agrpc::GrpcContext::executor_type;
    CHECK(asio::execution::can_execute_v<std::add_const_t<Exec>, asio::execution::invocable_archetype>);
    CHECK(asio::execution::is_executor_v<Exec>);
    CHECK(asio::can_require_v<Exec, asio::execution::blocking_t::never_t>);
    CHECK(asio::can_prefer_v<Exec, asio::execution::blocking_t::possibly_t>);
    CHECK(asio::can_prefer_v<Exec, asio::execution::relationship_t::fork_t>);
    CHECK(asio::can_prefer_v<Exec, asio::execution::relationship_t::continuation_t>);
    CHECK(asio::can_prefer_v<Exec, asio::execution::outstanding_work_t::tracked_t>);
    CHECK(asio::can_prefer_v<Exec, asio::execution::outstanding_work_t::untracked_t>);
    CHECK(asio::can_prefer_v<Exec, asio::execution::allocator_t<agrpc::detail::pmr::polymorphic_allocator<std::byte>>>);
    CHECK(asio::can_query_v<Exec, asio::execution::blocking_t>);
    CHECK(asio::can_query_v<Exec, asio::execution::relationship_t>);
    CHECK(asio::can_query_v<Exec, asio::execution::outstanding_work_t>);
    CHECK(asio::can_query_v<Exec, asio::execution::mapping_t>);
    CHECK(asio::can_query_v<Exec, asio::execution::allocator_t<void>>);
    CHECK(asio::can_query_v<Exec, asio::execution::context_t>);
    CHECK(std::is_constructible_v<asio::any_io_executor, Exec>);
    agrpc::GrpcContext grpc_context{std::make_unique<grpc::CompletionQueue>()};
    auto executor = grpc_context.get_executor();
    auto possibly_blocking_executor = asio::require(executor, asio::execution::blocking_t::possibly);
    CHECK_EQ(asio::execution::blocking_t::possibly, asio::query(possibly_blocking_executor, asio::execution::blocking));
    CHECK_EQ(asio::execution::blocking_t::never,
             asio::query(asio::require(possibly_blocking_executor, asio::execution::blocking_t::never),
                         asio::execution::blocking));
    auto continuation_executor = asio::prefer(executor, asio::execution::relationship_t::continuation);
    CHECK_EQ(asio::execution::relationship_t::continuation,
             asio::query(continuation_executor, asio::execution::relationship));
    CHECK_EQ(asio::execution::relationship_t::fork,
             asio::query(asio::prefer(continuation_executor, asio::execution::relationship_t::fork),
                         asio::execution::relationship));
    auto tracked_executor = asio::prefer(executor, asio::execution::outstanding_work_t::tracked);
    CHECK_EQ(asio::execution::outstanding_work_t::tracked,
             asio::query(tracked_executor, asio::execution::outstanding_work));
    CHECK_EQ(asio::execution::outstanding_work_t::untracked,
             asio::query(asio::prefer(tracked_executor, asio::execution::outstanding_work_t::untracked),
                         asio::execution::outstanding_work));
}

TEST_CASE("GrpcExecutor is mostly trivial")
{
    CHECK(std::is_trivially_copy_constructible_v<agrpc::GrpcExecutor>);
    CHECK(std::is_trivially_move_constructible_v<agrpc::GrpcExecutor>);
    CHECK(std::is_trivially_destructible_v<agrpc::GrpcExecutor>);
    CHECK(std::is_trivially_copy_assignable_v<agrpc::GrpcExecutor>);
    CHECK(std::is_trivially_move_assignable_v<agrpc::GrpcExecutor>);
    CHECK_EQ(sizeof(void*), sizeof(agrpc::GrpcExecutor));
}

TEST_CASE("GrpcExecutorOptions")
{
    CHECK(agrpc::detail::is_blocking_never(agrpc::detail::GrpcExecutorOptions::BLOCKING_NEVER));
    CHECK_FALSE(agrpc::detail::is_blocking_never(agrpc::detail::GrpcExecutorOptions::OUTSTANDING_WORK_TRACKED));
    CHECK(agrpc::detail::is_blocking_never(
        agrpc::detail::set_blocking_never(agrpc::detail::GrpcExecutorOptions::OUTSTANDING_WORK_TRACKED, true)));
    CHECK_FALSE(agrpc::detail::is_blocking_never(
        agrpc::detail::set_blocking_never(agrpc::detail::GrpcExecutorOptions::BLOCKING_NEVER, false)));

    CHECK(agrpc::detail::is_outstanding_work_tracked(agrpc::detail::GrpcExecutorOptions::OUTSTANDING_WORK_TRACKED));
    CHECK_FALSE(agrpc::detail::is_outstanding_work_tracked(agrpc::detail::GrpcExecutorOptions::BLOCKING_NEVER));
    CHECK(agrpc::detail::is_outstanding_work_tracked(
        agrpc::detail::set_outstanding_work_tracked(agrpc::detail::GrpcExecutorOptions::BLOCKING_NEVER, true)));
    CHECK_FALSE(agrpc::detail::is_outstanding_work_tracked(agrpc::detail::set_outstanding_work_tracked(
        agrpc::detail::GrpcExecutorOptions::OUTSTANDING_WORK_TRACKED, false)));

    CHECK(agrpc::detail::is_relationship_continuation(agrpc::detail::GrpcExecutorOptions::RELATIONSHIP_CONTINUATION));
    CHECK_FALSE(
        agrpc::detail::is_relationship_continuation(agrpc::detail::GrpcExecutorOptions::OUTSTANDING_WORK_TRACKED));
    CHECK(agrpc::detail::is_relationship_continuation(
        agrpc::detail::set_relationship_continuation(agrpc::detail::GrpcExecutorOptions::BLOCKING_NEVER, true)));
    CHECK_FALSE(agrpc::detail::is_relationship_continuation(agrpc::detail::set_relationship_continuation(
        agrpc::detail::GrpcExecutorOptions::RELATIONSHIP_CONTINUATION, false)));
}

TEST_CASE("Work tracking GrpcExecutor constructor and assignment")
{
    agrpc::GrpcContext grpc_context{std::make_unique<grpc::CompletionQueue>()};
    agrpc::GrpcContext other_context{std::make_unique<grpc::CompletionQueue>()};

    auto other_ex = asio::prefer(grpc_context.get_executor(), asio::execution::blocking_t::possibly);
    auto ex = asio::require(grpc_context.get_executor(), asio::execution::outstanding_work_t::tracked,
                            asio::execution::allocator(agrpc::detail::pmr::polymorphic_allocator<std::byte>()));
    auto ex2a = asio::require(ex, asio::execution::allocator);
    CHECK_EQ(std::allocator<void>{}, asio::query(ex2a, asio::execution::allocator));
    CHECK_NE(other_ex, ex2a);
    CHECK_NE(grpc_context.get_executor(), ex2a);
    CHECK_NE(other_context.get_executor(), ex2a);

    const auto ex1{ex};
    auto ex2{ex};
    auto ex3{std::move(ex)};
    CHECK_EQ(ex3, ex2);
    ex2 = ex1;
    CHECK_EQ(ex2, ex1);
    ex2 = std::move(ex3);
    ex2 = std::move(ex2);
    CHECK_EQ(ex2, ex1);
    ex3 = std::move(ex2);
    CHECK_EQ(ex3, ex1);
    ex2 = std::as_const(ex3);
    ex2 = std::as_const(ex2);
    CHECK_EQ(ex2, ex1);
}

TEST_CASE_FIXTURE(test::GrpcContextTest, "GrpcContext::reset")
{
    bool ok{false};
    CHECK_FALSE(grpc_context.is_stopped());
    asio::post(grpc_context,
               [&]
               {
                   ok = true;
                   CHECK_FALSE(grpc_context.is_stopped());
               });
    grpc_context.run();
    CHECK(grpc_context.is_stopped());
    CHECK(ok);
    asio::post(grpc_context,
               [&]
               {
                   ok = false;
               });
    grpc_context.run();
    CHECK(ok);
    grpc_context.reset();
    asio::post(grpc_context,
               [&]
               {
                   ok = false;
               });
    grpc_context.run();
    CHECK_FALSE(ok);
}

TEST_CASE_FIXTURE(test::GrpcContextTest, "GrpcContext::stop does not complete pending operations")
{
    bool ok{false};
    asio::post(grpc_context,
               [&]
               {
                   grpc_context.stop();
                   asio::post(grpc_context,
                              [&]
                              {
                                  ok = true;
                              });
               });
    grpc_context.run();
    CHECK_FALSE(ok);
}

TEST_CASE("GrpcContext::stop while waiting for Alarm will not invoke the Alarm's completion handler")
{
    bool is_stop_from_same_thread{true};
    SUBCASE("stop from same thread") {}
    SUBCASE("stop from other thread") { is_stop_from_same_thread = false; }
    bool ok{false};
    {
        std::thread thread;
        agrpc::GrpcContext grpc_context{std::make_unique<grpc::CompletionQueue>()};
        auto guard = asio::make_work_guard(grpc_context);
        grpc::Alarm alarm;
        asio::post(grpc_context,
                   [&]
                   {
                       agrpc::wait(alarm, test::five_seconds_from_now(),
                                   asio::bind_executor(grpc_context,
                                                       [&](bool)
                                                       {
                                                           ok = true;
                                                       }));
                       if (is_stop_from_same_thread)
                       {
                           grpc_context.stop();
                           guard.reset();
                       }
                       else
                       {
                           thread = std::thread(
                               [&]
                               {
                                   grpc_context.stop();
                                   guard.reset();
                               });
                       }
                   });
        grpc_context.run();
        CHECK_FALSE(ok);
        if (!is_stop_from_same_thread)
        {
            thread.join();
        }
    }
    CHECK_FALSE(ok);
}

TEST_CASE_FIXTURE(test::GrpcContextTest, "asio::spawn an Alarm and yield its wait")
{
    bool ok{false};
    std::chrono::system_clock::time_point start;
    asio::spawn(asio::bind_executor(get_executor(), [] {}),
                [&](auto&& yield)
                {
                    grpc::Alarm alarm;
                    start = std::chrono::system_clock::now();
                    ok = agrpc::wait(alarm, test::hundred_milliseconds_from_now(), yield);
                });
    grpc_context.run();
    CHECK_LE(std::chrono::milliseconds(100), std::chrono::system_clock::now() - start);
    CHECK(ok);
}

TEST_CASE_FIXTURE(test::GrpcContextTest, "asio::post an Alarm and check time")
{
    bool ok{false};
    std::chrono::system_clock::time_point start;
    grpc::Alarm alarm;
    asio::post(grpc_context,
               [&]()
               {
                   start = std::chrono::system_clock::now();
                   agrpc::wait(alarm, test::hundred_milliseconds_from_now(),
                               asio::bind_executor(grpc_context,
                                                   [&](bool)
                                                   {
                                                       ok = true;
                                                   }));
               });
    grpc_context.run();
    CHECK_LE(std::chrono::milliseconds(100), std::chrono::system_clock::now() - start);
    CHECK(ok);
}

TEST_CASE_FIXTURE(test::GrpcContextTest, "experimental::deferred with Alarm")
{
    bool ok1{false};
    bool ok2{false};
    grpc::Alarm alarm;
    auto deferred_op =
        agrpc::wait(alarm, test::ten_milliseconds_from_now(),
                    asio::experimental::deferred(
                        [&](bool wait_ok)
                        {
                            ok1 = wait_ok;
                            return agrpc::wait(alarm, test::ten_milliseconds_from_now(), asio::experimental::deferred);
                        }));
    std::move(deferred_op)(asio::bind_executor(grpc_context,
                                               [&](bool wait_ok)
                                               {
                                                   ok2 = wait_ok;
                                               }));
    grpc_context.run();
    CHECK(ok1);
    CHECK(ok2);
}

TEST_CASE_FIXTURE(test::GrpcContextTest, "asio::post a asio::steady_timer")
{
    std::optional<test::ErrorCode> error_code;
    asio::steady_timer timer{get_executor()};
    asio::post(get_executor(),
               [&]
               {
                   timer.expires_after(std::chrono::milliseconds(10));
                   timer.async_wait(
                       [&](const test::ErrorCode& ec)
                       {
                           error_code.emplace(ec);
                       });
               });
    grpc_context.run();
    CHECK_EQ(test::ErrorCode{}, error_code);
}

TEST_CASE_FIXTURE(test::GrpcContextTest, "asio::spawn with yield_context")
{
    bool ok{false};
    asio::spawn(get_executor(),
                [&](asio::yield_context yield)
                {
                    grpc::Alarm alarm;
                    ok = agrpc::wait(alarm, test::ten_milliseconds_from_now(), yield);
                });
    grpc_context.run();
    CHECK(ok);
}

TEST_CASE_FIXTURE(test::GrpcContextTest, "post from multiple threads")
{
    static constexpr auto THREAD_COUNT = 32;
    std::atomic_int counter{};
    asio::thread_pool pool{THREAD_COUNT};
    auto guard = asio::make_work_guard(grpc_context);
    for (size_t i = 0; i < THREAD_COUNT; ++i)
    {
        asio::post(pool,
                   [&]
                   {
                       asio::post(grpc_context,
                                  [&]
                                  {
                                      if (++counter == THREAD_COUNT)
                                      {
                                          guard.reset();
                                      }
                                  });
                   });
    }
    asio::post(pool,
               [&]
               {
                   grpc_context.run();
               });
    pool.join();
    CHECK_EQ(THREAD_COUNT, counter);
}

TEST_CASE_FIXTURE(test::GrpcContextTest, "post/execute with allocator")
{
    SUBCASE("asio::post")
    {
        asio::post(grpc_context,
                   test::HandlerWithAssociatedAllocator{
                       [] {}, agrpc::detail::pmr::polymorphic_allocator<std::byte>(&resource)});
    }
    SUBCASE("asio::execute before grpc_context.run()")
    {
        get_pmr_executor().execute([] {});
    }
    SUBCASE("asio::execute after grpc_context.run() from same thread")
    {
        asio::post(grpc_context,
                   [&, exec = get_pmr_executor()]
                   {
                       exec.execute([] {});
                   });
    }
    SUBCASE("agrpc::wait")
    {
        asio::execution::execute(get_executor(),
                                 [&, executor = get_pmr_executor()]() mutable
                                 {
                                     auto alarm = std::make_shared<grpc::Alarm>();
                                     auto& alarm_ref = *alarm;
                                     agrpc::wait(alarm_ref, test::ten_milliseconds_from_now(),
                                                 asio::bind_executor(std::move(executor),
                                                                     [a = std::move(alarm)](bool ok)
                                                                     {
                                                                         CHECK(ok);
                                                                     }));
                                 });
    }
    grpc_context.run();
    CHECK(allocator_has_been_used());
}

TEST_CASE_FIXTURE(test::GrpcContextTest, "dispatch with allocator")
{
    asio::post(grpc_context,
               [&]
               {
                   asio::dispatch(get_pmr_executor(), [] {});
               });
    grpc_context.run();
    CHECK(std::all_of(buffer.begin(), buffer.end(),
                      [](auto&& value)
                      {
                          return value == std::byte{};
                      }));
}

TEST_CASE_FIXTURE(test::GrpcContextTest, "execute with throwing allocator")
{
    const auto executor =
        asio::require(get_executor(), asio::execution::allocator(agrpc::detail::pmr::polymorphic_allocator<std::byte>(
                                          agrpc::detail::pmr::null_memory_resource())));
    CHECK_THROWS(asio::execution::execute(executor, [] {}));
}

struct Exception : std::exception
{
};

TEST_CASE_FIXTURE(test::GrpcContextTest, "asio::post with throwing completion handler")
{
    asio::post(get_executor(), asio::bind_executor(get_executor(),
                                                   []
                                                   {
                                                       throw Exception{};
                                                   }));
    CHECK_THROWS_AS(grpc_context.run(), Exception);
}

template <class Function>
struct Coro : asio::coroutine
{
    using executor_type =
        asio::require_result<agrpc::GrpcContext::executor_type, asio::execution::outstanding_work_t::tracked_t>::type;

    executor_type executor;
    Function function;

    Coro(agrpc::GrpcContext& grpc_context, Function&& f)
        : executor(asio::require(grpc_context.get_executor(), asio::execution::outstanding_work_t::tracked)),
          function(std::forward<Function>(f))
    {
    }

    void operator()(bool ok) { function(ok, this); }

    executor_type get_executor() const noexcept { return executor; }
};

#ifdef AGRPC_STANDALONE_ASIO
#include <asio/yield.hpp>
#elif defined(AGRPC_BOOST_ASIO)
#include <boost/asio/yield.hpp>
#endif

TEST_CASE_FIXTURE(test::GrpcContextTest, "asio::coroutine with Alarm")
{
    struct Coro : asio::coroutine
    {
        using executor_type = agrpc::GrpcContext::executor_type;

        grpc::Alarm& alarm;
        std::chrono::system_clock::time_point deadline;
        agrpc::GrpcContext& grpc_context;
        bool& ok;

        Coro(grpc::Alarm& alarm, std::chrono::system_clock::time_point deadline, agrpc::GrpcContext& grpc_context,
             bool& ok)
            : alarm(alarm), deadline(deadline), grpc_context(grpc_context), ok(ok)
        {
        }

        void operator()(bool wait_ok)
        {
            reenter(*this)
            {
                yield agrpc::wait(alarm, deadline, *this);
                ok = wait_ok;
            }
        }

        executor_type get_executor() const noexcept { return grpc_context.get_executor(); }
    };
    bool ok{false};
    grpc::Alarm alarm;
    Coro{alarm, test::ten_milliseconds_from_now(), grpc_context, ok}(false);
    grpc_context.run();
    CHECK(ok);
}

TEST_CASE("agrpc::request and agrpc::wait are noexcept for use_sender")
{
    using UseSender = decltype(agrpc::use_sender(std::declval<agrpc::GrpcContext&>()));
    CHECK_FALSE(noexcept(agrpc::request(std::declval<decltype(&test::v1::Test::Stub::AsyncServerStreaming)>(),
                                        std::declval<test::v1::Test::Stub&>(), std::declval<grpc::ClientContext&>(),
                                        std::declval<test::v1::Request&>(),
                                        std::declval<std::unique_ptr<grpc::ClientAsyncReader<test::v1::Response>>&>(),
                                        std::declval<asio::yield_context>())));
    CHECK(noexcept(agrpc::request(
        std::declval<decltype(&test::v1::Test::Stub::AsyncServerStreaming)>(), std::declval<test::v1::Test::Stub&>(),
        std::declval<grpc::ClientContext&>(), std::declval<test::v1::Request&>(),
        std::declval<std::unique_ptr<grpc::ClientAsyncReader<test::v1::Response>>&>(), std::declval<UseSender>())));
    CHECK_FALSE(
        noexcept(agrpc::wait(std::declval<grpc::Alarm&>(), std::declval<std::chrono::system_clock::time_point>(),
                             std::declval<asio::yield_context>())));
    CHECK(noexcept(agrpc::wait(std::declval<grpc::Alarm&>(), std::declval<std::chrono::system_clock::time_point>(),
                               std::declval<UseSender>())));
}

TEST_CASE_FIXTURE(test::GrpcClientServerTest, "unary stackless coroutine")
{
    grpc::ServerAsyncResponseWriter<test::v1::Response> writer{&server_context};
    test::v1::Request server_request;
    test::v1::Response server_response;
    auto server_loop = [&](bool ok, auto* coro) mutable
    {
        reenter(*coro)
        {
            yield agrpc::request(&test::v1::Test::AsyncService::RequestUnary, service, server_context, server_request,
                                 writer, *coro);
            CHECK(ok);
            CHECK_EQ(42, server_request.integer());
            server_response.set_integer(21);
            yield agrpc::finish(writer, server_response, grpc::Status::OK, *coro);
            CHECK(ok);
        }
    };
    std::thread server_thread(
        [&, server_coro = Coro{grpc_context, std::move(server_loop)}]() mutable
        {
            server_coro(true);
        });

    test::v1::Request client_request;
    client_request.set_integer(42);
    test::v1::Response client_response;
    grpc::Status status;
    std::unique_ptr<grpc::ClientAsyncResponseReader<test::v1::Response>> reader;
    auto client_loop = [&](bool ok, auto* coro) mutable
    {
        reenter(*coro)
        {
            reader = stub->AsyncUnary(&client_context, client_request, agrpc::get_completion_queue(*coro));
            yield agrpc::finish(*reader, client_response, status, *coro);
            CHECK(ok);
            CHECK(status.ok());
            CHECK_EQ(21, client_response.integer());
        }
    };
    std::thread client_thread(
        [&, client_coro = Coro{grpc_context, std::move(client_loop)}]() mutable
        {
            client_coro(true);
        });

    grpc_context.run();
    server_thread.join();
    client_thread.join();
}

#ifdef AGRPC_STANDALONE_ASIO
#include <asio/unyield.hpp>
#elif defined(AGRPC_BOOST_ASIO)
#include <boost/asio/unyield.hpp>
#endif

TEST_CASE_FIXTURE(test::GrpcClientServerTest, "yield_context server streaming")
{
    bool use_write_and_finish{false};
    SUBCASE("server write_and_finish") { use_write_and_finish = true; }
    bool use_client_convenience{false};
    SUBCASE("client use convenience") { use_client_convenience = true; }
    asio::spawn(get_executor(),
                [&](asio::yield_context yield)
                {
                    test::v1::Request request;
                    grpc::ServerAsyncWriter<test::v1::Response> writer{&server_context};
                    CHECK(agrpc::request(&test::v1::Test::AsyncService::RequestServerStreaming, service, server_context,
                                         request, writer, yield));
                    CHECK(agrpc::send_initial_metadata(writer, yield));
                    CHECK_EQ(42, request.integer());
                    test::v1::Response response;
                    response.set_integer(21);
                    CHECK(agrpc::write(writer, response, grpc::WriteOptions{}, yield));
                    if (use_write_and_finish)
                    {
                        CHECK(agrpc::write_and_finish(writer, response, {}, grpc::Status::OK, yield));
                    }
                    else
                    {
                        CHECK(agrpc::write(writer, response, yield));
                        CHECK(agrpc::finish(writer, grpc::Status::OK, yield));
                    }
                });
    asio::spawn(get_executor(),
                [&](asio::yield_context yield)
                {
                    test::v1::Request request;
                    request.set_integer(42);
                    auto [reader, ok] = [&]
                    {
                        if (use_client_convenience)
                        {
                            return agrpc::request(&test::v1::Test::Stub::AsyncServerStreaming, *stub, client_context,
                                                  request, yield);
                        }
                        std::unique_ptr<grpc::ClientAsyncReader<test::v1::Response>> reader;
                        bool ok = agrpc::request(&test::v1::Test::Stub::AsyncServerStreaming, *stub, client_context,
                                                 request, reader, yield);
                        return std::pair{std::move(reader), ok};
                    }();
                    CHECK(ok);
                    CHECK(agrpc::read_initial_metadata(*reader, yield));
                    test::v1::Response response;
                    CHECK(agrpc::read(*reader, response, yield));
                    CHECK(agrpc::read(*reader, response, yield));
                    grpc::Status status;
                    CHECK(agrpc::finish(*reader, status, yield));
                    CHECK(status.ok());
                    CHECK_EQ(21, response.integer());
                });
    grpc_context.run();
}

TEST_CASE_FIXTURE(test::GrpcClientServerTest, "yield_context client streaming")
{
    bool use_client_convenience{false};
    SUBCASE("client use convenience") { use_client_convenience = true; }
    bool use_finish_with_error{false};
    SUBCASE("server finish_with_error") { use_finish_with_error = true; }
    asio::spawn(get_executor(),
                [&](asio::yield_context yield)
                {
                    grpc::ServerAsyncReader<test::v1::Response, test::v1::Request> reader{&server_context};
                    CHECK(agrpc::request(&test::v1::Test::AsyncService::RequestClientStreaming, service, server_context,
                                         reader, yield));
                    CHECK(agrpc::send_initial_metadata(reader, yield));
                    test::v1::Request request;
                    CHECK(agrpc::read(reader, request, yield));
                    CHECK_EQ(42, request.integer());
                    test::v1::Response response;
                    response.set_integer(21);
                    if (use_finish_with_error)
                    {
                        CHECK(agrpc::finish_with_error(reader, grpc::Status::CANCELLED, yield));
                    }
                    else
                    {
                        CHECK(agrpc::finish(reader, response, grpc::Status::OK, yield));
                    }
                });
    asio::spawn(get_executor(),
                [&](asio::yield_context yield)
                {
                    test::v1::Response response;
                    auto [writer, ok] = [&]
                    {
                        if (use_client_convenience)
                        {
                            return agrpc::request(&test::v1::Test::Stub::AsyncClientStreaming, *stub, client_context,
                                                  response, yield);
                        }
                        std::unique_ptr<grpc::ClientAsyncWriter<test::v1::Request>> writer;
                        bool ok = agrpc::request(&test::v1::Test::Stub::AsyncClientStreaming, *stub, client_context,
                                                 writer, response, yield);
                        return std::pair{std::move(writer), ok};
                    }();
                    CHECK(ok);
                    CHECK(agrpc::read_initial_metadata(*writer, yield));
                    test::v1::Request request;
                    request.set_integer(42);
                    CHECK(agrpc::write(*writer, request, yield));
                    CHECK(agrpc::write(*writer, request, grpc::WriteOptions{}, yield));
                    CHECK(agrpc::writes_done(*writer, yield));
                    grpc::Status status;
                    CHECK(agrpc::finish(*writer, status, yield));
                    if (use_finish_with_error)
                    {
                        CHECK_EQ(grpc::StatusCode::CANCELLED, status.error_code());
                    }
                    else
                    {
                        CHECK(status.ok());
                        CHECK_EQ(21, response.integer());
                    }
                });
    grpc_context.run();
}

TEST_CASE_FIXTURE(test::GrpcClientServerTest, "yield_context unary")
{
    bool use_finish_with_error{false};
    SUBCASE("server finish_with_error") { use_finish_with_error = true; }
    SUBCASE("server finish with OK") {}
    asio::spawn(get_executor(),
                [&](asio::yield_context yield)
                {
                    test::v1::Request request;
                    grpc::ServerAsyncResponseWriter<test::v1::Response> writer{&server_context};
                    CHECK(agrpc::request(&test::v1::Test::AsyncService::RequestUnary, service, server_context, request,
                                         writer, yield));
                    CHECK(agrpc::send_initial_metadata(writer, yield));
                    CHECK_EQ(42, request.integer());
                    test::v1::Response response;
                    response.set_integer(21);
                    if (use_finish_with_error)
                    {
                        CHECK(agrpc::finish_with_error(writer, grpc::Status::CANCELLED, yield));
                    }
                    else
                    {
                        CHECK(agrpc::finish(writer, response, grpc::Status::OK, yield));
                    }
                });
    asio::spawn(get_executor(),
                [&](asio::yield_context yield)
                {
                    test::v1::Request request;
                    request.set_integer(42);
                    auto reader =
                        stub->AsyncUnary(&client_context, request, agrpc::get_completion_queue(get_executor()));
                    CHECK(agrpc::read_initial_metadata(*reader, yield));
                    test::v1::Response response;
                    grpc::Status status;
                    CHECK(agrpc::finish(*reader, response, status, yield));
                    if (use_finish_with_error)
                    {
                        CHECK_EQ(grpc::StatusCode::CANCELLED, status.error_code());
                    }
                    else
                    {
                        CHECK(status.ok());
                        CHECK_EQ(21, response.integer());
                    }
                });
    grpc_context.run();
}

TEST_CASE_FIXTURE(test::GrpcClientServerTest, "yield_context bidirectional streaming")
{
    bool use_write_and_finish{false};
    SUBCASE("server write_and_finish") { use_write_and_finish = true; }
    bool use_client_convenience{false};
    SUBCASE("client use convenience") { use_client_convenience = true; }
    asio::spawn(get_executor(),
                [&](asio::yield_context yield)
                {
                    grpc::ServerAsyncReaderWriter<test::v1::Response, test::v1::Request> reader_writer{&server_context};
                    CHECK(agrpc::request(&test::v1::Test::AsyncService::RequestBidirectionalStreaming, service,
                                         server_context, reader_writer, yield));
                    CHECK(agrpc::send_initial_metadata(reader_writer, yield));
                    test::v1::Request request;
                    CHECK(agrpc::read(reader_writer, request, yield));
                    CHECK(agrpc::read(reader_writer, request, yield));
                    CHECK_EQ(42, request.integer());
                    test::v1::Response response;
                    response.set_integer(21);
                    CHECK(agrpc::write(reader_writer, response, grpc::WriteOptions{}, yield));
                    if (use_write_and_finish)
                    {
                        CHECK(agrpc::write_and_finish(reader_writer, response, {}, grpc::Status::OK, yield));
                    }
                    else
                    {
                        CHECK(agrpc::write(reader_writer, response, yield));
                        CHECK(agrpc::finish(reader_writer, grpc::Status::OK, yield));
                    }
                });
    asio::spawn(
        get_executor(),
        [&](asio::yield_context yield)
        {
            auto [reader_writer, ok] = [&]
            {
                if (use_client_convenience)
                {
                    return agrpc::request(&test::v1::Test::Stub::AsyncBidirectionalStreaming, *stub, client_context,
                                          yield);
                }
                std::unique_ptr<grpc::ClientAsyncReaderWriter<test::v1::Request, test::v1::Response>> reader_writer;
                bool ok = agrpc::request(&test::v1::Test::Stub::AsyncBidirectionalStreaming, *stub, client_context,
                                         reader_writer, yield);
                return std::pair{std::move(reader_writer), ok};
            }();
            CHECK(ok);
            CHECK(agrpc::read_initial_metadata(*reader_writer, yield));
            test::v1::Request request;
            request.set_integer(42);
            CHECK(agrpc::write(*reader_writer, request, yield));
            CHECK(agrpc::write(*reader_writer, request, grpc::WriteOptions{}, yield));
            CHECK(agrpc::writes_done(*reader_writer, yield));
            test::v1::Response response;
            CHECK(agrpc::read(*reader_writer, response, yield));
            CHECK(agrpc::read(*reader_writer, response, yield));
            grpc::Status status;
            CHECK(agrpc::finish(*reader_writer, status, yield));
            CHECK(status.ok());
            CHECK_EQ(21, response.integer());
        });
    grpc_context.run();
}

struct GrpcRepeatedlyRequestTest : test::GrpcClientServerTest
{
    template <class RPC, class Service, class ServerFunction, class ClientFunction, class Allocator>
    auto test(RPC rpc, Service& service, ServerFunction server_function, ClientFunction client_function,
              Allocator allocator)
    {
        agrpc::repeatedly_request(
            rpc, service,
            test::RpcSpawner{asio::bind_executor(this->get_executor(), std::move(server_function)), allocator});
        asio::spawn(get_executor(), std::move(client_function));
    }
};

TEST_CASE_FIXTURE(GrpcRepeatedlyRequestTest, "yield_context repeatedly_request unary")
{
    bool is_shutdown{false};
    auto request_count{0};
    this->test(
        &test::v1::Test::AsyncService::RequestUnary, service,
        [&](grpc::ServerContext&, test::v1::Request& request,
            grpc::ServerAsyncResponseWriter<test::v1::Response>& writer, bool, asio::yield_context yield)
        {
            CHECK_EQ(42, request.integer());
            test::v1::Response response;
            response.set_integer(21);
            ++request_count;
            if (request_count > 3)
            {
                is_shutdown = true;
            }
            CHECK(agrpc::finish(writer, response, grpc::Status::OK, yield));
        },
        [&](asio::yield_context yield)
        {
            while (!is_shutdown)
            {
                test::v1::Request request;
                request.set_integer(42);
                grpc::ClientContext new_client_context;
                auto reader =
                    stub->AsyncUnary(&new_client_context, request, agrpc::get_completion_queue(get_executor()));
                test::v1::Response response;
                grpc::Status status;
                CHECK(agrpc::finish(*reader, response, status, yield));
                CHECK(status.ok());
                CHECK_EQ(21, response.integer());
            }
            grpc_context.stop();
        },
        get_allocator());
    grpc_context.run();
    CHECK_EQ(4, request_count);
    CHECK(allocator_has_been_used());
}

TEST_CASE_FIXTURE(GrpcRepeatedlyRequestTest, "yield_context repeatedly_request client streaming")
{
    bool is_shutdown{false};
    auto request_count{0};
    this->test(
        &test::v1::Test::AsyncService::RequestClientStreaming, service,
        [&](grpc::ServerContext&, grpc::ServerAsyncReader<test::v1::Response, test::v1::Request>& reader, bool,
            asio::yield_context yield)
        {
            test::v1::Request request;
            CHECK(agrpc::read(reader, request, yield));
            CHECK_EQ(42, request.integer());
            test::v1::Response response;
            response.set_integer(21);
            ++request_count;
            if (request_count > 3)
            {
                is_shutdown = true;
            }
            CHECK(agrpc::finish(reader, response, grpc::Status::OK, yield));
        },
        [&](asio::yield_context yield)
        {
            while (!is_shutdown)
            {
                test::v1::Response response;
                grpc::ClientContext new_client_context;
                auto [writer, ok] = agrpc::request(&test::v1::Test::Stub::AsyncClientStreaming, *stub,
                                                   new_client_context, response, yield);
                CHECK(ok);
                test::v1::Request request;
                request.set_integer(42);
                CHECK(agrpc::write(*writer, request, yield));
                CHECK(agrpc::writes_done(*writer, yield));
                grpc::Status status;
                CHECK(agrpc::finish(*writer, status, yield));
                CHECK(status.ok());
                CHECK_EQ(21, response.integer());
            }
            grpc_context.stop();
        },
        get_allocator());
    grpc_context.run();
    CHECK_EQ(4, request_count);
    CHECK(allocator_has_been_used());
}

TEST_CASE_FIXTURE(GrpcRepeatedlyRequestTest, "RepeatedlyRequestContext member functions for multi-arg requests")
{
    agrpc::repeatedly_request(
        &test::v1::Test::AsyncService::RequestUnary, service,
        asio::bind_executor(
            get_executor(),
            [&](auto&& rpc_context, bool)
            {
                auto&& request = rpc_context.request();
                CHECK(std::is_same_v<test::v1::Request&, decltype(request)>);
                auto&& responder = rpc_context.responder();
                CHECK(std::is_same_v<grpc::ServerAsyncResponseWriter<test::v1::Response>&, decltype(responder)>);
                auto&& context = rpc_context.server_context();
                CHECK(std::is_same_v<grpc::ServerContext&, decltype(context)>);
                test::v1::Response response;
                agrpc::finish(responder, response, grpc::Status::OK,
                              asio::bind_executor(get_executor(), [c = std::move(rpc_context)](bool) {}));
            }));
    asio::spawn(get_executor(),
                [&](asio::yield_context yield)
                {
                    test::v1::Request request;
                    auto reader =
                        stub->AsyncUnary(&client_context, request, agrpc::get_completion_queue(get_executor()));
                    test::v1::Response response;
                    grpc::Status status;
                    agrpc::finish(*reader, response, status, yield);
                    grpc_context.stop();
                });
    grpc_context.run();
}

TEST_CASE_FIXTURE(GrpcRepeatedlyRequestTest, "RepeatedlyRequestContext member functions for single-arg requests")
{
    agrpc::repeatedly_request(
        &test::v1::Test::AsyncService::RequestClientStreaming, service,
        asio::bind_executor(get_executor(),
                            [&](auto&& rpc_context, bool)
                            {
                                auto&& responder = rpc_context.responder();
                                CHECK(std::is_same_v<grpc::ServerAsyncReader<test::v1::Response, test::v1::Request>&,
                                                     decltype(responder)>);
                                auto&& context = rpc_context.server_context();
                                CHECK(std::is_same_v<grpc::ServerContext&, decltype(context)>);
                                test::v1::Response response;
                                agrpc::finish(
                                    responder, response, grpc::Status::OK,
                                    asio::bind_executor(get_executor(), [c = std::move(rpc_context)](bool) {}));
                            }));
    asio::spawn(get_executor(),
                [&](asio::yield_context yield)
                {
                    test::v1::Response response;
                    auto [writer, ok] = agrpc::request(&test::v1::Test::Stub::AsyncClientStreaming, *stub,
                                                       client_context, response, yield);
                    agrpc::writes_done(*writer, yield);
                    grpc::Status status;
                    agrpc::finish(*writer, status, yield);
                    grpc_context.stop();
                });
    grpc_context.run();
}

TEST_CASE_FIXTURE(test::GrpcClientServerTest, "RPC step after grpc_context stop")
{
    std::optional<bool> ok;
    asio::spawn(get_executor(),
                [&](asio::yield_context yield)
                {
                    grpc_context.stop();
                    test::v1::Request request;
                    grpc::ServerAsyncResponseWriter<test::v1::Response> writer{&server_context};
                    ok = agrpc::request(&test::v1::Test::AsyncService::RequestUnary, service, server_context, request,
                                        writer, yield);
                });
    grpc_context.run();
    CHECK_FALSE(ok);
}

TEST_CASE_FIXTURE(test::GrpcContextTest, "asio::post an Alarm and use variadic-arg callback for its wait")
{
    bool ok{false};
    grpc::Alarm alarm;
    asio::post(get_executor(),
               [&]
               {
                   agrpc::wait(alarm, test::ten_milliseconds_from_now(),
                               asio::bind_executor(get_executor(),
                                                   [&](auto&&... args)
                                                   {
                                                       ok = bool{args...};
                                                   }));
               });
    grpc_context.run();
    CHECK(ok);
}

#ifdef AGRPC_ASIO_HAS_CANCELLATION_SLOT
TEST_CASE_FIXTURE(test::GrpcContextTest, "cancel grpc::Alarm with cancellation_type::total")
{
    bool ok{true};
    asio::cancellation_signal signal{};
    grpc::Alarm alarm;
    agrpc::wait(alarm, test::five_seconds_from_now(),
                asio::bind_cancellation_slot(signal.slot(), asio::bind_executor(get_executor(),
                                                                                [&](bool alarm_ok)
                                                                                {
                                                                                ok = alarm_ok;
                                                                                })));
    asio::post(get_executor(),
               [&]
               {
                   signal.emit(asio::cancellation_type::total);
               });
    SUBCASE("cancel once") {}
    SUBCASE("cancel twice has no effect")
    {
        asio::post(get_executor(),
                   [&]
                   {
                       signal.emit(asio::cancellation_type::total);
                   });
    }
    grpc_context.run();
    CHECK_FALSE(ok);
}

TEST_CASE_FIXTURE(test::GrpcContextTest, "cancel grpc::Alarm with cancellation_type::none")
{
    bool ok{false};
    asio::cancellation_signal signal{};
    grpc::Alarm alarm;
    asio::post(get_executor(),
               [&]
               {
                   agrpc::wait(alarm, test::hundred_milliseconds_from_now(),
                               asio::bind_cancellation_slot(signal.slot(), asio::bind_executor(get_executor(),
                                                                                [&](bool alarm_ok)
                                                                                {
                                                                                ok = alarm_ok;
                                                                                })));
                   asio::post(get_executor(),
                              [&]
                              {
                                  signal.emit(asio::cancellation_type::none);
                              });
               });
    grpc_context.run();
    CHECK(ok);
}

TEST_CASE_FIXTURE(test::GrpcContextTest, "cancel grpc::Alarm with parallel_group")
{
    std::array<std::size_t, 2> completion_order;
    std::optional<test::ErrorCode> error_code;
    bool ok{true};
    grpc::Alarm alarm;
    asio::steady_timer timer{get_executor()};
    timer.expires_after(std::chrono::milliseconds(100));
    asio::experimental::make_parallel_group(timer.async_wait(asio::experimental::deferred),
                                            [&](auto token)
                                            {
                                                return agrpc::wait(alarm, test::five_seconds_from_now(),
                                                                   asio::bind_executor(get_executor(), token));
                                            })
        .async_wait(asio::experimental::wait_for_one(),
                    [&](std::array<std::size_t, 2> actual_completion_order, test::ErrorCode timer_ec, bool wait_ok)
                    {
                        completion_order = actual_completion_order;
                        error_code.emplace(timer_ec);
                        ok = wait_ok;
                    });
    grpc_context.run();
    CHECK_EQ(0, completion_order[0]);
    CHECK_EQ(1, completion_order[1]);
    CHECK_EQ(test::ErrorCode{}, error_code);
    CHECK_FALSE(ok);
}
#endif

TEST_SUITE_END();
}  // namespace test_asio_grpc

max_stars_repo_name: Tradias/asio-grpc

max_issues_repo_name: Tradias/asio-grpc

max_forks_repo_name: Tradias/asio-grpc