text:
#include <Eigen/Core>

#include <numpy_eigen/boost_python_headers.hpp>
Eigen::Matrix<int, 2, 3> test_int_2_3(const Eigen::Matrix<int, 2, 3>& M) { return M; }
void export_int_2_3() { boost::python::def("test_int_2_3", test_int_2_3); }

max_stars_repo_name: chengfzy/kalibr

max_issues_repo_name: chengfzy/kalibr

max_forks_repo_name: chengfzy/kalibr


text:
#ifndef VENTURA_READ_FROM_ANONYMOUS_PIPE_HPP
#define VENTURA_READ_FROM_ANONYMOUS_PIPE_HPP

#include <silicium/sink/buffering_sink.hpp>
#include <silicium/sink/append.hpp>
#include <boost/thread/future.hpp>
#include <boost/asio/io_service.hpp>
#include <boost/asio/posix/stream_descriptor.hpp>
#include <silicium/make_unique.hpp>
#include <silicium/optional.hpp>
#include <silicium/to_shared.hpp>

namespace ventura
{
#define VENTURA_HAS_EXPERIMENTAL_READ_FROM_ANONYMOUS_PIPE SILICIUM_HAS_BUFFERING_SINK

#if VENTURA_HAS_EXPERIMENTAL_READ_FROM_ANONYMOUS_PIPE && defined(_WIN32)
    namespace win32
    {
        template <class ByteSink>
        void copy_whole_pipe(HANDLE pipe_in, ByteSink &&sink_out, boost::shared_future<void> stop_polling)
        {
            auto buffered_out = make_buffering_sink(std::forward<ByteSink>(sink_out));
            for (;;)
            {
                auto buffer = buffered_out.make_append_space((std::numeric_limits<DWORD>::max)());
                DWORD read_bytes = 0;
                DWORD available = 0;
                DWORD left = 0;
                BOOL const peeked = PeekNamedPipe(pipe_in, buffer.begin(), static_cast<DWORD>(buffer.size()),
                                                  &read_bytes, &available, &left);
                if (!peeked)
                {
                    auto error = ::GetLastError();
                    if (error == ERROR_BROKEN_PIPE)
                    {
                        buffered_out.make_append_space(read_bytes);
                        buffered_out.flush_append_space();
                        break;
                    }
                    throw boost::system::system_error(error, boost::system::native_ecat);
                }
                if (available == 0)
                {
                    switch (stop_polling.wait_for(boost::chrono::milliseconds(300)))
                    {
                    case std::future_status::ready:
                        return;

                    case std::future_status::deferred:
                    case std::future_status::timeout:
                        break;
                    }
                    continue;
                }
                if (ReadFile(pipe_in, buffer.begin(), available, &read_bytes, nullptr))
                {
                    assert(available == read_bytes);
                    buffered_out.make_append_space(read_bytes);
                    buffered_out.flush_append_space();
                }
                else
                {
                    Si::throw_last_error();
                }
            }
            buffered_out.flush();
        }
    }
#endif
    namespace experimental
    {
#if VENTURA_HAS_EXPERIMENTAL_READ_FROM_ANONYMOUS_PIPE

#ifndef _WIN32
        struct pipe_reading_state
        {
            boost::asio::posix::stream_descriptor reader;
            std::array<char, 4096> buffer;

            explicit pipe_reading_state(boost::asio::io_service &io, Si::file_handle file)
                : reader(io, file.release())
            {
            }
        };

        template <class CharSink>
        void read_all(std::shared_ptr<pipe_reading_state> state, CharSink &destination)
        {
            state->reader.async_read_some(
                boost::asio::buffer(state->buffer), [state, &destination](boost::system::error_code ec, size_t bytes)
                {
                    if (!!ec)
                    {
                        return;
                    }
                    Si::append(destination,
                               Si::make_iterator_range(state->buffer.begin(), state->buffer.begin() + bytes));
                    read_all(state, destination);
                });
        }
#endif

        // TODO: find a more generic API for reading from a pipe portably
        template <class CharSink>
        boost::unique_future<void> read_from_anonymous_pipe(boost::asio::io_service &io, CharSink &destination,
                                                            Si::file_handle file,
                                                            boost::shared_future<void> stop_polling)
        {
#ifdef _WIN32
            return boost::async(boost::launch::async, [&io, file = std::move(file), stop_polling, &destination ]()
                                {
                                    boost::asio::io_service::work work(io);
                                    win32::copy_whole_pipe(file.handle, destination, stop_polling);
                                });
#else
            // TODO: implement for Windows
            (void)stop_polling;
            auto state = std::make_shared<pipe_reading_state>(io, std::move(file));
            read_all(state, destination);
            return boost::make_ready_future();
#endif
        }
#endif
    }
}

#endif

ext: hpp

max_stars_repo_name: TyRoXx/ventura

max_issues_repo_name: TyRoXx/ventura

max_forks_repo_name: TyRoXx/ventura


text: #include <boost/serialization/scoped_ptr.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
// Copyright (C) 2016 Gideon May (gideon@borges.xyz)
//
// Permission to copy, use, sell and distribute this software is granted
// provided this copyright notice appears in all copies.
// Permission to modify the code and to distribute modified code is granted
// provided this copyright notice appears in all copies, and a notice
// that the code was modified is included with the copyright notice.
//
// This software is provided "as is" without express or implied warranty,
// and with no claim as to its suitability for any purpose.

#include <boost/python.hpp>

#include <string>
#include <iostream>

#include <osg/Timer>
using namespace boost::python;

class Timer : public osg::Timer {
  private:
    int dummy_;
};

Timer& instance()
{
    // FIXME !!! XXX Danger Will Robinson, a static cast due to compiler error
    // in Apple gcc 3.3
    Timer * timer = (Timer*) const_cast<osg::Timer*>(osg::Timer::instance());
    return * timer;
}

namespace PyOSG {
void init_Timer()
{
    class_<Timer>("Timer",
        "A high resolution, low latency time stamper.")
        .def("tick", &Timer::tick)
        .def("delta_s", &Timer::delta_s)
        .def("delta_m", &Timer::delta_m)
        .def("delta_u", &Timer::delta_u)
        .def("delta_n", &Timer::delta_n)
        .def("getSecondsPerTick", &Timer::getSecondsPerTick)
        .def("instance",
                &instance,
                return_value_policy<copy_non_const_reference>()
                )
        .staticmethod("instance")
        ;
}
}

ext: cpp

max_stars_repo_name: gideonmay/PyOSG

max_issues_repo_name: gideonmay/PyOSG

max_forks_repo_name: gideonmay/PyOSG


text:
#include <boost/python.hpp>
#include <boost/python/list.hpp>
#include <boost/python/extract.hpp>
#include <string>
#include <sstream>
#include <vector>
#include <iostream>
class World
{
public:
    void set(std::string msg) { mMsg = msg; }
    void many(boost::python::list msgs) {
        long l = len(msgs);
        std::stringstream ss;
        for (long i = 0; i<l; ++i) {
            if (i>0) ss << ", ";
            std::string s = boost::python::extract<std::string>(msgs[i]);
            ss << s;
        }
        mMsg = ss.str();
    }
    std::string greet() { return mMsg; }
    void set_strain(boost::python::list strain_list)
    {
        int a = len(strain_list);
        for (int i =0; i < a;i++)
        {
            strain_list_.push_back(boost::python::extract<double>(strain_list[i]));
        }
    }
    void show_strain()
    {
        int a = strain_list_.size();
        for (int i=0;i<a;i++) std::cout <<strain_list_.at(i)<<"\n";

    }
private:
    std::string mMsg;
    std::vector<double> strain_list_;
};

// using namespace boost::python;

BOOST_PYTHON_MODULE(classes)
{
    boost::python::class_<World>("World")
        .def("greet", &World::greet)
        .def("set", &World::set)
        .def("many", &World::many)
        .def("set_strain",&World::set_strain)
        .def("show_strain",&World::show_strain)
    ;
};

max_stars_repo_name: WeijianLIANG/boost-python-examples

max_issues_repo_name: WeijianLIANG/boost-python-examples

max_forks_repo_name: WeijianLIANG/boost-python-examples


text:
/**
 * @CopyRight:
 * FISCO-BCOS is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * FISCO-BCOS is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with FISCO-BCOS.  If not, see <http://www.gnu.org/licenses/>
 * (c) 2016-2018 fisco-dev contributors.
 *
 * @brief: Empty test framework of FISCO-BCOS. Define BOOST_TEST_MODULE
 *
 * @file main.cpp
 * @author: yujiechen, jimmyshi
 * @date 2018-08-24
 */
#define BOOST_TEST_MODULE FISCO_BCOS_Tests
#define BOOST_TEST_NO_MAIN

#include "libdevcrypto/CryptoInterface.h"
#include <boost/test/included/unit_test.hpp>
#include <boost/test/unit_test.hpp>

int main(int argc, const char* argv[])
{
    auto fakeInit = [](int, char**) -> boost::unit_test::test_suite* { return nullptr; };
    int result = boost::unit_test::unit_test_main(fakeInit, argc, const_cast<char**>(argv));
    return result;
}

max_stars_repo_name: imtypist/FISCO-BCOS

max_issues_repo_name: imtypist/FISCO-BCOS

max_forks_repo_name: imtypist/FISCO-BCOS


text:
#include "mirtk/Common.h"
#include "mirtk/M2SConnectivity.h"
#include "mirtk/PointSetUtils.h"

#include <vtkMassProperties.h>
#include <vtkWindowedSincPolyDataFilter.h>
#include <vtkFastMarchingGeodesicDistance.h>
#include <vtkIdList.h>
#include <vtkDoubleArray.h>
#include <vtkPointData.h>
#include <vtkCellArray.h>

#include <boost/range/irange.hpp>

namespace mirtk {
// =============================================================================
// Construction/Destruction
// =============================================================================

M2SConnectivity::M2SConnectivity()
{
  _Input = vtkSmartPointer<vtkPolyData>::New();
  _Normalize = false;
  _ScaleFactor = -1.0;
  _Threshold = -1.0;
  _K = -1;

  _ForwardDirection = true;
  _BackwardDirection = true;
  _IdentityEdges = false;
}

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

M2SConnectivity::M2SConnectivity(const M2SConnectivity &other)
{
  *this = other;
}

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

M2SConnectivity &M2SConnectivity::operator =(const M2SConnectivity &other)
{
  if (this != &other) {
    M2SConnectivity::operator =(other);
    CopyAttributes(other);
  }
  return *this;
}

M2SConnectivity::~M2SConnectivity(){}

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

void M2SConnectivity::CopyAttributes(const M2SConnectivity &other){
  cout << "TODO copy attributes" << endl;
}

void progress(float p){
  int barWidth = 70;

  cout << "[";
  int pos = barWidth * p;
  for (int i = 0; i < barWidth; ++i) {
      if (i < pos) std::cout << "=";
      else if (i == pos) std::cout << ">";
      else std::cout << " ";
  }
  std::cout << "] " << int(p * 100.0) << " %\r";
  std::cout.flush();

}

bool idPairCompare(const std::pair<int, int>& firstElem, const std::pair<int, int>& secondElem) {

  if (firstElem.first < secondElem.first){
    return true;
  }

  if (firstElem.first > secondElem.first){
    return false;
  }

  return firstElem.second < secondElem.second;
}

bool compareIdsLessThan(const Edge &l, const Edge &r){
  return l.ptId1 < r.ptId1 || ( l.ptId1 == r.ptId1 &&  l.ptId2 < r.ptId2);
};

bool compareIdsGreaterThan (const Edge &l, const Edge &r){
  return l.ptId1 > r.ptId1 || ( l.ptId1 == r.ptId1 &&  l.ptId2 > r.ptId2);
};

bool compareIdsEquivalent (const Edge &l, const Edge &r){
  return l.ptId1 == r.ptId1 && l.ptId2 == r.ptId2;
};

bool compareIdsNotEquivalent (const Edge &l, const Edge &r){
  return l.ptId1 != r.ptId1 || l.ptId2 != r.ptId2;
};

void uniqueSortedEdges(Array<Edge> & edges){
  int numEdges = edges.size();

  sort(edges.begin(), edges.end(), compareIdsLessThan);

  Array<Edge> uniqueEdges;

  int count = 0;
  double meanLength = 0.0;
  int lastEdgeId = numEdges -1;

  for (int edgeId=0; edgeId<numEdges; edgeId++){
    Edge edge = edges[edgeId];
    count++;

    Edge nextEdge;
    if (edgeId < lastEdgeId){
      nextEdge = edges[edgeId+1];
    }

    if (compareIdsNotEquivalent(edge, nextEdge) || edgeId == lastEdgeId){
      meanLength += edge.length;
      meanLength /= (double)count;
      edge.length = meanLength;
      uniqueEdges.push_back(edge);

      count = 0;
      meanLength = 0.0;
    }
    else{
      meanLength += edge.length;
    }
  }

  edges = uniqueEdges;
}

void M2SConnectivity::ComputeGeodesics(){

  int numPts = _Input->GetNumberOfPoints();

  string arrayName = "FMMDist";
  vtkSmartPointer< vtkFastMarchingGeodesicDistance > fmm =
      vtkSmartPointer< vtkFastMarchingGeodesicDistance >::New();

  vtkSmartPointer< vtkIdList > seed =
      vtkSmartPointer< vtkIdList >::New();

  int numSeeds = _SeedPtIds.size();
  if (numSeeds == 0){
    _SeedPtIds = Array<int>(numPts);
    std::iota (_SeedPtIds.begin(), _SeedPtIds.end(), 0);
    numSeeds = numPts;
  }

  int numOtherPts = _OtherPtIds.size();
  if (numOtherPts == 0){
    _OtherPtIds = Array<int>(numPts);
    std::iota (_OtherPtIds.begin(), _OtherPtIds.end(), 0);
    numOtherPts = numPts;
  }

  fmm->SetInputData(_Input);
  fmm->SetFieldDataName(arrayName.c_str());
  seed->SetNumberOfIds(1);
  fmm->SetSeeds(seed);
  fmm->SetDistanceStopCriterion(_Threshold);

  if (_K > 0){
    int k = _K;
    if (!_IdentityEdges)
      k++;
    fmm->SetNumberOfVisitedPointsStopCriterion(k);
  }

  int onePercentOfSeeds = numSeeds/100;
  onePercentOfSeeds++;

  cout << "computing geodesics" << endl;

  bool symmetric = _ForwardDirection && _BackwardDirection;

  for (int i=0; i<numSeeds; i++){
    int seedPtId = _SeedPtIds[i];
    //cout << ptId << endl;
    if (i % onePercentOfSeeds == 0){
      double p = double(i) / double(numSeeds);
      progress(p);
    }

    seed->SetId(0, seedPtId);
    seed->Modified();
    fmm->Update();

    vtkDoubleArray * array = (vtkDoubleArray *)
        fmm->GetOutput()->GetPointData()->GetArray(arrayName.c_str());

    //note otherPtId < ptId, as int otherPtId=ptId+1 below

    int numEdge = 0;
    for (int j=0; j<numOtherPts; j++){

      int otherPtId = _OtherPtIds[j];

      if ((!_IdentityEdges) && seedPtId == otherPtId)
        continue;

      double d = array->GetTuple1(otherPtId);
      if (d >= 0.0 && (_Threshold <= 0.0 || d < _Threshold)){

        int ptId1 = seedPtId;
        int ptId2 = otherPtId;

        if (symmetric && otherPtId < seedPtId){
          std::swap(ptId1, ptId2);
        }

        Edge e;
        e.ptId1 = ptId1;
        e.ptId2 = ptId2;
        e.length = d;
        e.weight1 = _ForwardDirection;
        e.weight2 = _BackwardDirection;
        _Edges.push_back(e);
      }
    }

  }

  if (symmetric){ uniqueSortedEdges(_Edges); }

}

/*
void M2SConnectivity::InitializeEdges(){

  //get edges

  //map original id to subset id
  //map submesh id to original id -> ptidhierarchy

  _Edges.clear();

  cout << "Initialising edges" << endl;
  Array< Pair<int, int> > edgePairs;

  int numPts = _Input->GetNumberOfPoints();

  GenericSparseMatrix<double>::Entries entries;

  for (int ptId1 = 0; ptId1< numPts; ptId1++){

    if ( ptId1 >= numPts){
      cout << "InitializeEdges::point id ptId1 " << ptId1 << " is greater than number of points! " << numPts << endl;
      exit(1);
    }

    _Geodesics.GetCol(ptId1, entries);

    int numAdjs = entries.size();

    for (int k=0; k<numAdjs; k++){
      int ptId2 = entries[k].first;

      if ( ptId2 >= numPts){
        cout << "InitializeEdges::point id ptId2 is greater than number of points!" << endl;
        exit(1);
      }

      if (ptId1 < ptId2){
        double d = _Geodesics.Get(ptId2,ptId1);

        if (d <= 0){
          cout << "M2SConnectivity::InitialiseEdges : invalid geodesic value "
              << d << endl;
          exit(1);
        }
        edgePairs.push_back(MakePair(ptId1, ptId2));
      }

      else{
        cout << "M2SConnectivity::InitialiseEdges : invalid id pair "
            << "<" << ptId1 << "," << ptId2 << ">" << endl;
      }
    }
  }
  //add mesh links if required
  if (_EdgeLinksOn){

    _Input->GetPolys()->InitTraversal();
    vtkSmartPointer<vtkIdList> idList = vtkSmartPointer<vtkIdList>::New();

    while(_Input->GetPolys()->GetNextCell(idList)) {
      int numIds = idList->GetNumberOfIds();

      for (int i=0; i<numIds ;i++){
        int ptId1 = idList->GetId(i);

        for (int j=0; j<numIds ;j++){
          int ptId2 = idList->GetId(j);

          if (ptId1 < ptId2){
            edgePairs.push_back(MakePair(ptId1,ptId2));
          }
        }
      }
    }
  }
  //get only unique pairs
  uniqueSortedPairs(edgePairs);

  _Edges.Initialize(edgePairs, numPts);
}
*/
void M2SConnectivity::ScaleEdgeDistances(){

  //radius of sphere with same surface area gives normalisation to unit sphere

  if (_ScaleFactor < 0){
    vtkSmartPointer<vtkMassProperties> mp =
        vtkSmartPointer<vtkMassProperties>::New();
    mp->SetInputData(_Input);
    mp->Update();
    double area = mp->GetSurfaceArea();
    _ScaleFactor = sqrt(area / (4 * pi));
  }

  for (auto &edge:_Edges){
    edge.length /= _ScaleFactor;
  }

}

/*
void M2SConnectivity::InitializeEdgeDistances(){
  //extract vector of geodesics
  EdgeIterator ei(_Edges);
  ei.InitTraversal();
  vtkIdType pid1, pid2;

  _Distances.clear();
 //double maxd = 0;
  while ( ei.GetNextEdge(pid1, pid2) != -1 ){
    double d = _Geodesics.Get(pid1,pid2);

    if (d == 0){
      d = _Geodesics.Get(pid2,pid1);
    }

    if (d == 0){//not in geodesics must be mesh edge compute length

      //cout << "WARNING - distance not in geodesics" << endl;

      double p1 [3], p2 [3];

      _Input->GetPoint(pid1,p1);
      _Input->GetPoint(pid2,p2);
      //cout << "edge link found computing distance" << endl;
      d = sqrt(pow(p1[0]-p2[0],2)
                  + pow(p1[1]-p2[1],2) + pow(p1[2]-p2[2],2));

      //if (d > maxd) maxd = d;
    }
    _Distances.push_back(d);
  }
  //cout << "maxd " << maxd << endl;
  ScaleEdgeDistances();
}
*/

/*
void M2SConnectivity::ComputeEdgeLinks(){

  int numTargetPts = _TargetMesh->GetNumberOfPoints();

  EdgeTable edgeTable(_TargetMesh);
  EdgeIterator ei(edgeTable);

  Array<double> weights;

  for (int ptId=0; ptId<numTargetPts; ptId++){
    int numAdjs = edgeTable.NumberOfAdjacentPoints(ptId);
    double w = 1.0 / (double)numAdjs;
    weights.push_back(w);
  }

  ei.InitTraversal();
  int ptId1, ptId2;
  while ( ei.GetNextEdge(ptId1, ptId2) != -1 ){

    Pair idPair = MakePair(ptId1, ptId2);
    bool seen = _VisitedEdges.find(idPair) != _VisitedEdges.end();
    if (seen)
      continue;

    _VisitedEdges.insert(idPair);

    double p1 [3], p2 [3];
    _TargetMesh->GetPoint(ptId1,p1);
    _TargetMesh->GetPoint(ptId2,p2);
    //cout << "edge link found computing distance" << endl;
    double d = sqrt(pow(p1[0]-p2[0],2)
                + pow(p1[1]-p2[1],2) + pow(p1[2]-p2[2],2));

    Edge e;
    e.ptId1 = ptId1;
    e.ptId2 = ptId2;
    e.length = d;
    e.weight1 = weights[ptId1];
    e.weight2 = weights[ptId2];

    _Edges.push_back(e);
  }
}

*/
/*
void M2SConnectivity::GetEdges(Array<int> seedPtIds, Array<Edge> otherPtIds, int max, double maxDist = -1.0){

  int maxId = 0;

  for (auto e:_Edges){
    if (e.ptId1 > maxId){ maxId = e.ptId1; }
    if (e.ptId2 > maxId){ maxId = e.ptId2; }
  }

  Array<bool> seedPtMask;
  if (seedPtIds.empty()){
    seedPtMask = Array<bool>(maxId+1, true);
  }
  else{
    seedPtMask = Array<bool>(maxId+1, false);
    for (auto id:seedPtIds){
      seedPtMask[id] = true;
    }
  }

  Array<bool> otherPtMask;
  if (otherPtIds.empty()){
    otherPtMask = Array<bool>(maxId+1, true);
  }
  else{
    otherPtMask = Array<bool>(maxId+1, false);
    for (auto id:otherPtIds){
      otherPtMask[id] = true;
    }
  }

}
*/

void M2SConnectivity::Update(){
  ComputeGeodesics();
  if (_Normalize)
    ScaleEdgeDistances();

}

} // mirtk namespace

ext: cc

max_stars_repo_name: jcupitt/SphericalMesh

max_issues_repo_name: jcupitt/SphericalMesh

max_forks_repo_name: jcupitt/SphericalMesh


text: #include <boost/geometry/strategies/cartesian/buffer_point_square.hpp>


text:
#include <boost/test/unit_test.hpp>

#include <giecs/bits.hpp>
#include <giecs/memory/context.hpp>
#include <giecs/memory/accessor.hpp>
#include <giecs/memory/accessors/linear.hpp>

BOOST_AUTO_TEST_SUITE(context);

using namespace giecs;

BOOST_AUTO_TEST_CASE(accessor)
{
    typedef Bits<6> byte;
    typedef Bits<24> word;

    auto c1 = memory::Context<4, word>();

    struct Index
    {
        int x,y;
        Index()
            :x(0),y(0)
        {}

        Index(int x)
            : Index(x, 0)
        {
        }

        Index(int x_, int y_)
            : x(x_), y(y_)
        {
            this->y += this->x / 4;
            this->x %= 4;
        }

        Index operator+(Index const& i) const
        {
            return Index(this->x+i.x, this->y+i.y);
        }

        bool operator<(Index const& i) const
        {
            return ((int)*this  < (int)i);
        }

        Index& operator++()
        {
            *this = Index(this->x+1, this->y);
            return *this;
        }

        operator int() const
        {
            return (this->x + this->y*4);
        }
    };

    struct Array
    {
        byte* ptr;

        Array(void const* ptr_)
            :ptr((byte*)ptr_)
        {}

        byte& operator[] (Index const& i) const
        {
            return this->ptr[(int)i];
        }

        byte& operator* () const
        {
            return *this->ptr;
        }

        Array& operator++()
        {
            this->ptr++;
            return *this;
        }
    };

    auto acc = memory::accessors::Linear<4, word, Index, byte, Array, Index>(c1);

    Index len = Index(0,4);

    int a = 0;
    for(Index i = Index(); i < len; ++i)
    {
        ++a;
        acc[i] = a;
    }

    a = 0;
    for(Index i = Index(); i < len; ++i)
    {
        ++a;
        byte b = acc[i];
        BOOST_CHECK( b == a );
    }
}

BOOST_AUTO_TEST_CASE(synchronization)
{
    auto c1 = memory::Context<8, uint8_t>();

    auto acc1 = memory::accessors::Linear<8, uint8_t, int, uint8_t>(c1);
    auto acc2 = memory::accessors::Linear<8, uint8_t, int, uint16_t>(c1);

    static int const n = 4;

    uint8_t v8 = 0;
    for(int i = 0; i < 2*n; i++)
    {
        ++v8;
        acc1[i] = v8;
    }

    v8 = 0;
    for(int i = 0; i < n; i++)
    {
        uint16_t v16 = 0;

        ++v8;
        uint8_t r8 = acc1[i*2];
        BOOST_CHECK(r8 == v8);
        v16 = v8;

        printf("%x ", v8);

        ++v8;
        r8 = acc1[i*2+1];
        BOOST_CHECK(r8 == v8);
        v16 |= v8 << 8;

        uint16_t r16 = acc2[i];
        printf("%x -> %x == %x\n", v8, v16, r16);
        BOOST_CHECK(r16 == v16);
    }
}

BOOST_AUTO_TEST_SUITE_END();

max_stars_repo_name: michaelsippel/cautious-potato

max_issues_repo_name: michaelsippel/cautious-potato

max_forks_repo_name: michaelsippel/cautious-potato


text:
////////////////////////////////////////////////////////////////////////////////////////////////////
// pop_back.hpp
// Proto callables Fusion pop_back
//
//  Copyright 2010 Eric Niebler. Distributed under the Boost
//  Software License, Version 1.0. (See accompanying file
//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#ifndef BOOST_PROTO_V5_FUNCTIONAL_FUSION_POP_BACK_HPP_INCLUDED
#define BOOST_PROTO_V5_FUNCTIONAL_FUSION_POP_BACK_HPP_INCLUDED

#include <type_traits>
#include <boost/fusion/include/begin.hpp>
#include <boost/fusion/include/end.hpp>
#include <boost/fusion/include/prior.hpp>
#include <boost/fusion/include/pop_back.hpp>
#include <boost/proto/v5/proto_fwd.hpp>

namespace boost
{
    namespace proto
    {
        inline namespace v5
        {
            namespace functional
            {
                namespace fusion
                {
                    /// \brief A PolymorphicFunctionObject type that invokes the
                    /// \c fusion::pop_back() action on its argument.
                    ///
                    /// A PolymorphicFunctionObject type that invokes the
                    /// \c fusion::pop_back() action on its argument.
                    struct pop_back
                    {
                        template<typename Seq>
                        auto operator ()(Seq &&seq) const
                        BOOST_PROTO_AUTO_RETURN(
                            typename boost::fusion::result_of::pop_back<
                                typename ::std::remove_reference<Seq>::type
                            >::type(
                                boost::fusion::begin(static_cast<Seq &&>(seq))
                              , boost::fusion::prior(boost::fusion::end(static_cast<Seq &&>(seq)))
                            )
                        )
                    };
                }
            }
        }
    }
}

#endif


text:
// @@@LICENSE
//
//      Copyright (c) 2010-2013 LG Electronics, Inc.
//
// 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.
//
// LICENSE@@@

#include "commands/SyncFolderListCommand.h"
#include "client/ImapSession.h"
#include "data/ImapAccount.h"
#include "data/FolderAdapter.h"
#include "data/ImapAccountAdapter.h"
#include "data/ImapFolderAdapter.h"
#include "data/DatabaseInterface.h"
#include "data/DatabaseAdapter.h"
#include <map>
#include "ImapPrivate.h"
#include "sync/SpecialFolderPicker.h"
#include "activity/ActivityBuilder.h"
#include "activity/ImapActivityFactory.h"
#include "data/EmailSchema.h"
#include "commands/DeleteFoldersCommand.h"
#include "protocol/ListResponseParser.h"
#include "protocol/NamespaceResponseParser.h"
#include "client/Capabilities.h"
#include <boost/algorithm/string/predicate.hpp>

using namespace std;

SyncFolderListCommand::SyncFolderListCommand(ImapSession& session)
: ImapSessionCommand(session),
  m_accountModified(false),
  m_namespaceResponseSlot(this, &SyncFolderListCommand::NamespaceResponse),
  m_getFoldersSlot(this, &SyncFolderListCommand::GetLocalFoldersResponse),
  m_listResponseSlot(this, &SyncFolderListCommand::ListResponse),
  m_reserveFolderIdsSlot(this, &SyncFolderListCommand::ReserveNewFolderIdsResponse),
  m_createFoldersSlot(this, &SyncFolderListCommand::CreateNewFoldersResponse),
  m_deleteFoldersSlot(this, &SyncFolderListCommand::DeleteFoldersDone),
  m_updateAccountSlot(this, &SyncFolderListCommand::UpdateAccountResponse),
  m_setupWatchDraftsActivitySlot(this, &SyncFolderListCommand::SetupWatchDraftsActivityResponse)
{
}

SyncFolderListCommand::~SyncFolderListCommand()
{
}

void SyncFolderListCommand::RunImpl()
{
	// Get root folder prefix from account preferences
	m_namespacePrefix = m_session.GetAccount()->GetNamespaceRoot();

	// If there's no prefix, and the server supports NAMESPACE, run the NAMEPSACE command
	if(m_namespacePrefix.empty() && m_session.GetCapabilities().HasCapability(Capabilities::NAMESPACE)) {
		SendNamespaceCommand();
	} else {
		GetLocalFolders();
	}
}

void SyncFolderListCommand::SendNamespaceCommand()
{
	CommandTraceFunction();

	m_namespaceResponseParser.reset(new NamespaceResponseParser(m_session, m_namespaceResponseSlot));
	m_session.SendRequest("NAMESPACE", m_namespaceResponseParser);
}

MojErr SyncFolderListCommand::NamespaceResponse()
{
	CommandTraceFunction();

	try {
		m_namespaceResponseParser->CheckStatus();

		m_namespacePrefix = m_namespaceResponseParser->GetNamespacePrefix();

		GetLocalFolders();
	} CATCH_AS_FAILURE

	return MojErrNone;
}

void SyncFolderListCommand::GetLocalFolders()
{
	CommandTraceFunction();

	assert( m_session.GetAccount().get() != NULL );
	const MojObject& accountId = m_session.GetAccount()->GetId();
	assert( !accountId.undefined() && !accountId.null() );

	m_session.GetDatabaseInterface().GetFolders(m_getFoldersSlot, accountId, m_folderPage);
}

MojErr SyncFolderListCommand::GetLocalFoldersResponse(MojObject& response, MojErr err)
{
	CommandTraceFunction();

	try {
		ErrorToException(err);

		MojObject accountId = m_session.GetAccount()->GetId();

		MojObject results;
		err = response.getRequired("results", results);
		ErrorToException(err);

		MojObject::ArrayIterator it;
		err = results.arrayBegin(it);
		ErrorToException(err);

		// Read list of local folders
		for (; it != results.arrayEnd(); ++it) {
			MojObject& folderObj = *it;
			ImapFolderPtr folder = boost::make_shared<ImapFolder>();

			ImapFolderAdapter::ParseDatabaseObject(folderObj, *folder);
			folder->SetAccountId(accountId);

			m_localFolders.push_back(folder);
		}

		if(DatabaseAdapter::GetNextPage(response, m_folderPage)) {
			// Get more folders
			GetLocalFolders();
		} else {
			// Next step: get list of emails from server
			SendListCommand();
		}
	} CATCH_AS_FAILURE

	return MojErrNone;
}

void SyncFolderListCommand::SendListCommand()
{
	CommandTraceFunction();

	m_listResponseParser.reset( new ListResponseParser(m_session, m_listResponseSlot) );

	bool useXlist = m_session.GetCapabilities().HasCapability(Capabilities::XLIST);

	stringstream ss;
	ss << (useXlist ? "XLIST " : "LIST ") << QuoteString(m_namespacePrefix) << " *";

	m_session.SendRequest(ss.str(), m_listResponseParser);
}

MojErr SyncFolderListCommand::ListResponse()
{
	CommandTraceFunction();

	try {
		m_listResponseParser->CheckStatus();

		MojLogInfo(m_log, "folders on server: %d", m_listResponseParser->GetFolders().size());

		ReconcileFolderList();

	} CATCH_AS_FAILURE

	return MojErrNone;
}

void SyncFolderListCommand::ReconcileFolderList()
{
	CommandTraceFunction();

	m_folderListDiff.GenerateDiff(m_localFolders, m_listResponseParser->GetFolders());

	if(m_folderListDiff.GetDeletedFolders().size() > 0) {
		// Delete new folders first
		DeleteFolders();
	} else if(m_folderListDiff.GetNewFolders().size() > 0) {
		// Create new folders first
		ReserveNewFolderIds();
	} else {
		// Just update the account
		UpdateAccount();
	}
}

void SyncFolderListCommand::PickSpecialFolders()
{
	const boost::shared_ptr<ImapAccount>& account = m_session.GetAccount();

	assert( account.get() != NULL );

	// Update special folders
	m_accountModified = false;
	SpecialFolderPicker folderPicker(m_folderListDiff.GetFolders());

	// Update Inbox
	if(!folderPicker.FolderIdExists(account->GetInboxFolderId())) {
		ImapFolderPtr inbox = folderPicker.MatchInbox();

		if(inbox.get()) {
			MojLogInfo(m_log, "setting inboxFolderId to folderId %s", AsJsonString(inbox->GetId()).c_str());

			account->SetInboxFolderId(inbox->GetId());
			m_accountModified = true;
		}
	}

	if(!folderPicker.FolderIdExists(account->GetArchiveFolderId())) {
		ImapFolderPtr archive = folderPicker.MatchArchive();

		if(archive.get()) {
			MojLogInfo(m_log, "setting archiveFolderId to folderId %s", AsJsonString(archive->GetId()).c_str());

			account->SetArchiveFolderId(archive->GetId());
			m_accountModified = true;
		} else {
			MojLogInfo(m_log, "setting archiveFolderId to null");

			account->SetArchiveFolderId(MojObject::Null);
			m_accountModified = true;
		}
	}

	if(!folderPicker.FolderIdExists(account->GetDraftsFolderId())) {
		ImapFolderPtr drafts = folderPicker.MatchDrafts();

		if(drafts.get()) {
			MojLogInfo(m_log, "setting draftsFolderId to folderId %s", AsJsonString(drafts->GetId()).c_str());

			account->SetDraftsFolderId(drafts->GetId());
			m_accountModified = true;
		} else {
			MojLogInfo(m_log, "setting draftsFolderId to null");

			account->SetDraftsFolderId(MojObject::Null);
			m_accountModified = true;
		}
	}

	if(!folderPicker.FolderIdExists(account->GetSentFolderId())) {
		ImapFolderPtr sent = folderPicker.MatchSent();

		if(sent.get()) {
			MojLogInfo(m_log, "setting sentFolderId to folderId %s", AsJsonString(sent->GetId()).c_str());

			account->SetSentFolderId(sent->GetId());
			m_accountModified = true;
		} else {
			MojLogInfo(m_log, "setting sentFolderId to null");

			account->SetSentFolderId(MojObject::Null);
			m_accountModified = true;
		}
	}

	if(!folderPicker.FolderIdExists(account->GetSpamFolderId())) {
		ImapFolderPtr spam = folderPicker.MatchSpam();

		if(spam.get()) {
			MojLogInfo(m_log, "setting spamFolderId to folderId %s", AsJsonString(spam->GetId()).c_str());

			account->SetSpamFolderId(spam->GetId());
			m_accountModified = true;
		} else {
			MojLogInfo(m_log, "setting spamFolderId to null");

			account->SetSpamFolderId(MojObject::Null);
			m_accountModified = true;
		}
	}

	if(!folderPicker.FolderIdExists(account->GetTrashFolderId())) {
		ImapFolderPtr trash = folderPicker.MatchTrash();

		if(trash.get()) {
			MojLogInfo(m_log, "setting trashFolderId to folderId %s", AsJsonString(trash->GetId()).c_str());

			account->SetTrashFolderId(trash->GetId());
			m_accountModified = true;
		} else {
			MojLogInfo(m_log, "setting trashFolderId to null");

			account->SetTrashFolderId(MojObject::Null);
			m_accountModified = true;
		}
	}
}

void SyncFolderListCommand::DeleteFolders()
{
	CommandTraceFunction();

	MojErr err;
	MojObject::ObjectVec deletedIds;

	MojLogInfo(m_log, "deleting %d folders", m_folderListDiff.GetDeletedFolders().size());
	// Get list of folder ids to delete
	BOOST_FOREACH(const ImapFolderPtr& folder, m_folderListDiff.GetDeletedFolders()) {
		if(boost::iequals(folder->GetFolderName(), ImapFolder::INBOX_FOLDER_NAME)) {
			MojLogError(m_log, "attempted to delete inbox!");
		} else {
			// Delete folder as long as it's not the inbox
			err = deletedIds.push(folder->GetId());
			ErrorToException(err);
		}
	}

	// DeleteFoldersCommands deletes all the specified folders, folders' emails, and watches.
	m_deleteFoldersCommand.reset(new DeleteFoldersCommand(*(m_session.GetClient()), deletedIds));
	m_deleteFoldersCommand->Run(m_deleteFoldersSlot);
}

MojErr SyncFolderListCommand::DeleteFoldersDone()
{
	CommandTraceFunction();

	try {
		m_deleteFoldersCommand->GetResult()->CheckException();

		if(m_folderListDiff.GetNewFolders().size()) {
			// Create new folders second
			ReserveNewFolderIds();
		} else {
			// No new folders; skip to updating account
			UpdateAccount();
		}
	} CATCH_AS_FAILURE

	return MojErrNone;
}

void SyncFolderListCommand::ReserveNewFolderIds()
{
	CommandTraceFunction();

	m_reserveFolderIdsSlot.cancel();
	m_session.GetDatabaseInterface().ReserveIds(m_reserveFolderIdsSlot, DatabaseAdapter::RESERVE_BATCH_SIZE);
}

MojErr SyncFolderListCommand::ReserveNewFolderIdsResponse(MojObject& response, MojErr err)
{
	CommandTraceFunction();

	try {
		ErrorToException(err);

		const vector<ImapFolderPtr>& newFolders = m_folderListDiff.GetNewFolders();

		MojObject ids;
		err = response.getRequired("ids", ids);

		// Add ids
		BOOST_FOREACH(const MojObject& id, DatabaseAdapter::GetArrayIterators(ids)) {
			m_reservedIds.push_back(id);
		}

		if(m_reservedIds.size() < newFolders.size()) {
			if(ids.size() == 0)
				throw MailException("not enough ids reserved", __FILE__, __LINE__);

			ReserveNewFolderIds();
		} else {
			AssignFolderIds();
		}
	} CATCH_AS_FAILURE

	return MojErrNone;
}

void SyncFolderListCommand::AssignFolderIds()
{
	CommandTraceFunction();

	const vector<ImapFolderPtr>& newFolders = m_folderListDiff.GetNewFolders();

	// Assign ids to each new folder
	for(unsigned int i = 0; i < newFolders.size(); i++) {
		MojObject id = m_reservedIds.at(i);

		newFolders.at(i)->SetId(id);
	}

	CreateNewFolders();
}

// Associate folders with the right parent folders
// For each new folder, strip off the last component of the folder name.
// Look through new and existing folders for names that match.
void SyncFolderListCommand::MatchParents()
{
	const vector<ImapFolderPtr>& folders = m_folderListDiff.GetFolders();
	map<string, MojObject> suitableParents;

	vector<ImapFolderPtr>::const_iterator it;

	BOOST_FOREACH(const ImapFolderPtr& folder, folders) {
		// add to map
		assert( !folder->GetId().undefined() );
		suitableParents[folder->GetFolderName()] = folder->GetId();
	}

	// Match up parents
	BOOST_FOREACH(const ImapFolderPtr& folder, folders) {
		const string &folderName = folder->GetFolderName();
		size_t end = folderName.find_last_of(folder->GetDelimiter());

		if(end != string::npos) {
			std::string parentName = folderName.substr(0, end);

			// Fixup parent name to match our all-caps INBOX
			if(boost::istarts_with(parentName, ImapFolder::INBOX_FOLDER_NAME)) {
				parentName.replace(0, string(ImapFolder::INBOX_FOLDER_NAME).length(), ImapFolder::INBOX_FOLDER_NAME);
			}

			map<string, MojObject>::iterator parentIt = suitableParents.find(parentName);

			if(parentIt != suitableParents.end()) {
				MojObject parentId = parentIt->second;
				folder->SetParentId(parentId);
			}
		}
	}
}

void SyncFolderListCommand::CreateNewFolders()
{
	CommandTraceFunction();

	const vector<ImapFolderPtr>& newFolders = m_folderListDiff.GetNewFolders();
	MojLogInfo(m_log, "creating %d new folders", newFolders.size());

	MojObject::ObjectVec newFolderObjs;

	assert( m_session.GetAccount() != NULL );
	MojObject accountId = m_session.GetAccount()->GetId();

	// Pick special folders; note that ids have already been assigned at this point
	PickSpecialFolders();

	// Set parentId for new folders
	MatchParents();

	// Add folders (serialized into MojObjects) to array
	BOOST_FOREACH(const ImapFolderPtr& folder, newFolders) {
		MojObject folderObj;

		// Set account id first
		folder->SetAccountId(accountId);

		if(boost::iequals(folder->GetFolderName(), ImapFolder::INBOX_FOLDER_NAME)) {
			MojLogWarning(m_log, "attempted to re-add inbox folder '%s'; disallowing", folder->GetFolderName().c_str());
			continue;
		}

		// Set favorite flag on inbox
		if(m_session.GetAccount()->GetInboxFolderId() == folder->GetId()) {
			folder->SetFavorite(true);
		}

		ImapFolderAdapter::SerializeToDatabaseObject(*folder.get(), folderObj);
		newFolderObjs.push(folderObj);
	}

	m_session.GetDatabaseInterface().CreateFolders(m_createFoldersSlot, newFolderObjs);
}

MojErr SyncFolderListCommand::CreateNewFoldersResponse(MojObject& response, MojErr err)
{
	CommandTraceFunction();

	try {
		ErrorToException(err);

		UpdateAccount();
	} catch(const std::exception& e) {
		Failure(e);
	} catch(...) {
		// FIXME
	}
	return MojErrNone;
}

void SyncFolderListCommand::UpdateAccount()
{
	CommandTraceFunction();

	const boost::shared_ptr<ImapAccount>& account = m_session.GetAccount();
	assert( account.get() != NULL );

	// TODO: check for dangling folder ids?

	if(m_accountModified) {
		m_session.GetDatabaseInterface().UpdateAccountSpecialFolders(m_updateAccountSlot, *account);
	} else {
		Done();
	}
}

MojErr SyncFolderListCommand::UpdateAccountResponse(MojObject& response, MojErr err)
{
	CommandTraceFunction();

	try {
		ErrorToException(err);
		SetupWatchDraftsActivity();
	} catch(const std::exception& e) {
		Failure(e);
	} catch(...) {
		// FIXME
	}

	return MojErrNone;
}

void SyncFolderListCommand::SetupWatchDraftsActivity()
{
	MojObject accountId = m_session.GetAccount()->GetAccountId();
	MojObject folderId = m_session.GetAccount()->GetDraftsFolderId();

	ImapActivityFactory factory;
	ActivityBuilder actBuilder;

	factory.BuildDraftsWatch(actBuilder, accountId, folderId, 0);

	// create new activity (replacing any existing activity, if necessary)
	MojObject payload;
	MojErr err = payload.put("activity", actBuilder.GetActivityObject());
	ErrorToException(err);
	err = payload.put("start", true);
	ErrorToException(err);
	err = payload.put("replace", true);
	ErrorToException(err);

	m_session.GetClient()->SendRequest(m_setupWatchDraftsActivitySlot, "com.palm.activitymanager","create", payload);

}

MojErr SyncFolderListCommand::SetupWatchDraftsActivityResponse(MojObject& response, MojErr err)
{
	CommandTraceFunction();

	try {
		ErrorToException(err);
		Done();
	} catch (const std::exception& e) {
		Failure(e);
	}

	return MojErrNone;
}

void SyncFolderListCommand::Done()
{
	CommandTraceFunction();
	m_session.FolderListSynced();
	Complete();
}

max_stars_repo_name: webOS-ports/mojomail

max_issues_repo_name: openwebos/app-services

max_forks_repo_name: openwebos/app-services


text:
#ifndef NTRIPSOCKET_H
#define NTRIPSOCKET_H

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

using std::string;
using std::vector;
using std::chrono::system_clock;
using std::chrono::time_point;

#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/iostreams/device/array.hpp>
#include <boost/algorithm/string/trim.hpp>
#include <boost/system/error_code.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/log/expressions.hpp>
#include <boost/log/trivial.hpp>
#include <boost/asio/buffer.hpp>
#include <boost/filesystem.hpp>
#include <boost/thread.hpp>
#include <boost/format.hpp>
#include <boost/regex.hpp>
#include <boost/asio.hpp>
#include <boost/asio/ssl.hpp>

#include "ntripTrace.hpp"

/* Interface to be used for NTRIP version 2, streams for downloading messages.
* The NtripSteam was ugraded by Alex and now connects and download ansyncronously
* in the background on a boost service with it's own thread created in the constuctor.
* The message chunking of NTRIP version 2 has been implemented and receivedDataBuffer
* is filled with valid RCTM messages in the background without the chunked encoding data.
* During testing there is some data downloading that is invalid, being not complient with
* the chunked protocol. This data is not transfered to receivedDataBuffer.
* As in the previous implementation getData() is called once per epoch of the main loop
* and the completed and checked RTCM messages are placed in receivedData in a thread safe
* way. A destructor was added to correctly close socket when the program exits.
* Addition ansyncronous code was added to connect reconnect and establish a data stream.
* An example for the boost library documenation was used;
* https://www.boost.org/doc/libs/1_40_0/doc/html/boost_asio/example/http/client/async_client.cpp
*/
namespace B_asio    = boost::asio;
namespace ip		= B_asio::ip;
namespace ssl		= B_asio::ssl;
using tcp			= ip::tcp;
using error_code	= boost::system::error_code;
using ssl_socket	= ssl::stream<tcp::socket>;

using namespace boost::system;

#define ERROR_OUTPUT_RECONNECT_AND_RETURN 																					\
{																															\
	onErrorStatistics(err, __FUNCTION__);																					\
	BOOST_LOG_TRIVIAL(error) << "Error: " << err.message() << " in " << __FUNCTION__ << " for " << url.sanitised() << "\n";	\
																															\
	if (err != boost::asio::error::operation_aborted)																		\
		delayed_reconnect();        																						\
																															\
	return;																													\
}

struct Base64
{
	static string encode(string in)
	{
		return encode(in.c_str(), in.length());
	}

	static string encode(const char * in, std::size_t len)
	{
		string out;
		const char constexpr tab[] =
		{
			"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
			"abcdefghijklmnopqrstuvwxyz"
			"0123456789+/"
		};

		for (auto n = len / 3; n--; )
		{
			out += tab[ (in[0] & 0xfc) >> 2];
			out += tab[((in[0] & 0x03) << 4) + ((in[1] & 0xf0) >> 4)];
			out += tab[((in[2] & 0xc0) >> 6) + ((in[1] & 0x0f) << 2)];
			out += tab[  in[2] & 0x3f];
			in += 3;
		}

		switch (len % 3)
		{
			case 2:
				out += tab[ (in[0] & 0xfc) >> 2];
				out += tab[((in[0] & 0x03) << 4) + ((in[1] & 0xf0) >> 4)];
				out += tab[                         (in[1] & 0x0f) << 2];
				out += '=';
				break;

			case 1:
				out += tab[ (in[0] & 0xfc) >> 2];
				out += tab[((in[0] & 0x03) << 4)];
				out += '=';
				out += '=';
				break;

			case 0:
				break;
		}

		return out;
	}
};

struct URL
{
	string  url;
	string  protocol;
	string  user;
	string  pass;
	string  host;
	string  port_str;
	int     port;
	string  path;

	static URL parse(string url)
	{

//      boost::regex re (R"(^((https?)://)?((\w):(\w)@)?([^\s:=/]+)(:(\d+)?)/(.*$))", boost::regex::extended);
		boost::regex re (R"((https?)://(([^:@]+):([^@]+)@)?([^:@]+)(:(\d+))?(/.*)$)", boost::regex::extended);

		boost::smatch matches;

		if (!boost::regex_match(url, matches, re))
		{
			BOOST_LOG_TRIVIAL(debug) << "Invalid URL [" << url << "]";
			return URL();
		}

		BOOST_LOG_TRIVIAL(debug)
		<< "Valid URL ["    << url << "]";

		BOOST_LOG_TRIVIAL(debug)
		<< "protocol=["     << matches[1]

		<< "] username=["   << matches[3]
		<< "] password=["   << matches[4]
		<< "] host=["       << matches[5]
		<< "] port=["       << matches[7]
		<< "] path=["       << matches[8] << "]";

		URL out;

		out.url = url;

		string protocol	= matches[1];

		out.user		= matches[3];
		out.pass		= matches[4];
		out.host		= matches[5];
		out.port_str	= matches[7];
		out.path		= matches[8];

		out.protocol    = protocol.     empty() ? "http"    : protocol;
		if (out.port_str.empty())
		{
			if (out.protocol == "https")    out.port_str = "443";
			else                            out.port_str = "2101";
		}
		out.port        = std::stoi(out.port_str);

		return out;
	}

	string sanitised()
	{
		return protocol + ":" + "//" + host + (port > 0 ? (":" + std::to_string(port)) : "") + path;
	}
};

struct NtripSocket : NetworkStatistics
{
protected:
	std::shared_ptr<tcp::socket>	_socket;
	tcp::socket*					socket_ptr;
	std::shared_ptr<ssl_socket>		_sslsocket;
	std::shared_ptr<tcp::resolver>	_resolver;

	string request_string;
	string response_string;

	boost::asio::deadline_timer		timer;

	boost::asio::streambuf			request;
	boost::asio::streambuf			downloadBuf;

public:
	URL		url;

	int		disconnectionCount	= 0;
	bool	isConnected			= false;
// 	boost::posix_time::ptime         startTime;			//todo aaron, use NetworkStatistics for this instead
// 	boost::posix_time::ptime         connectedTime;
// 	boost::posix_time::ptime         disconnectedTime;
// 	boost::posix_time::time_duration connectedDuration;
// 	boost::posix_time::time_duration disconnectedDuration;
//
// 	boost::posix_time::time_duration epochConnectedDuration;
// 	boost::posix_time::time_duration epochDisconnectedDuration;

	bool			finishedReadingStream	= false;
	unsigned int	chunked_message_length	= 0;
	int				numberErroredChunks		= 0;
	bool			logHttpSentReceived		= false;

	unsigned int content_length = 0;

	NtripSocket(const string& url_str) :
		timer(io_service),
		ssl_context(ssl::context::sslv23_client)
	{
// 		startTime = boost::posix_time::from_time_t(system_clock::to_time_t(system_clock::now()));
		url			= URL::parse(url_str);
		streamName	= url.path;
	}

	void setUrl(const string& url_str)
	{
		url			= URL::parse(url_str);
		streamName	= url.path;
	}

	void connect();
	void disconnect();

	void start_read(bool chunked);

protected:
	void delayed_reconnect();

private:
	// These functions manage the connection using the boost service and
	// asyncronous function calls.
	void resolve_handler			(const boost::system::error_code& err, tcp::resolver::iterator endpoint_iterator);
	void connect_handler			(const boost::system::error_code& err, tcp::resolver::iterator endpoint_iterator);
	void sslhandshake_handler		(const boost::system::error_code& err);
	void write_request_handler		(const boost::system::error_code& err);
	void request_response_handler	(const boost::system::error_code& err);
	void reconnect_timer_handler	(const boost::system::error_code& err);

	void read_handler_content		(const boost::system::error_code& err);
	void read_handler_chunked		(const boost::system::error_code& err);

public:
	void logChunkError();
	void printChunkHex(vector<char> chunk);

	//content from a stream has been received - process it in virtual functions from other classes
	virtual bool dataChunkDownloaded(
		vector<char> dataChunk)
	{
		return false;
	}

	//content from a one-shot request has been received - process it in virtual functions from other classes
	virtual void readContentDownloaded(
		vector<char> content)
	{

	}

	virtual void connected()
	{

	}

	virtual void messageChunkLog(
		string message)
	{

	}

	virtual void networkLog(
		string message)
	{

	}

	virtual void connectionError(
		const boost::system::error_code& err,
		string operation)
	{

	}

	virtual void serverResponse(
		unsigned int status_code,
		string http_version)
	{

	}

	B_asio::ssl::context ssl_context;

	static B_asio::io_service io_service;
	static void runService()
	{
		B_asio::io_service::work work(io_service);
		io_service.run();
	}

	static void startClients()
	{
		std::thread(NtripSocket::runService).detach();
	}
};

#endif

max_stars_repo_name: GnssTao/ginan


text:
#include <treeDAG/decomposer.hpp>
#include <boost/lexical_cast.hpp>
#include <iostream>
#include <fstream>
#include <boost/timer/timer.hpp>

typedef treeDAG::SeparatorConfig::Graph Graph;

Graph create_cyle(std::size_t size)
{
    Graph g(size);
    for(std::size_t i = 0; i < size; ++i)
    {
        std::size_t src = i;
        std::size_t dst = (i+1)%size;
        boost::add_edge(src, dst, g);
    }

    return g;
}

Graph create_path(std::size_t size)
{
    Graph g(size);
    for(std::size_t i = 1; i < size; ++i)
        boost::add_edge(i-1, i, g);

    return g;
}

Graph create_test_graph()
{
    Graph g(7);
    boost::add_edge(0, 1, g);
    boost::add_edge(2, 1, g);
    boost::add_edge(5, 1, g);
    boost::add_edge(2, 3, g);
    boost::add_edge(5, 3, g);
    boost::add_edge(3, 4, g);
    boost::add_edge(3, 6, g);
    boost::add_edge(0, 4, g);
    boost::add_edge(0, 6, g);

    return g;
}

Graph create_test_graph2()
{
    Graph g(7);
    boost::add_edge(0, 1, g);
    boost::add_edge(1, 2, g);
    boost::add_edge(2, 3, g);
    boost::add_edge(3, 0, g);
    boost::add_edge(3, 4, g);
    boost::add_edge(4, 5, g);
    boost::add_edge(5, 6, g);
    boost::add_edge(6, 4, g);

    return g;
}

Graph create_test_graph3()
{
    Graph g(8);
    boost::add_edge(0, 1, g);
    boost::add_edge(1, 2, g);
    boost::add_edge(2, 3, g);
    boost::add_edge(3, 0, g);
    boost::add_edge(2, 4, g);
    boost::add_edge(4, 5, g);
    boost::add_edge(5, 6, g);
    boost::add_edge(6, 7, g);
    boost::add_edge(7, 5, g);

    return g;
}

int main(int argc, char ** argv)
{
    if(argc != 2)
    {
        std::cerr << "usage: " << argv[0] << " cycle_size" << std::endl;
        return -1;
    }

    std::size_t sz = boost::lexical_cast<std::size_t>(argv[1]);
//    Graph g = create_cyle(sz);
//    Graph g = create_test_graph3();
    Graph g = create_path(sz);

    std::stringstream times;

    for(std::size_t i = 0; i < 1; ++i)
    {
        boost::timer::cpu_timer t;
        t.start();

        treeDAG::Decomposer decomposer(&g, 2);
        decomposer.initialize();

        std::vector<unsigned char> roots;
        roots.push_back(0);
        roots.push_back(1);

        decomposer.process(roots.begin(), roots.end());
        t.stop();

        std::cout << sz << ";" << decomposer.decompositionDAG().numberOfNodes() << ";" << decomposer.decompositionDAG().numberOfBranches() << ";" << t.elapsed().wall << std::endl;

        std::stringstream filename;
        filename << "test_" << sz << ".dot";

        std::ofstream ofs;
        ofs.open(filename.str().c_str());

        decomposer.writeDot(ofs);
    }
}

max_stars_repo_name: thomasfannes/treeDAG

max_issues_repo_name: thomasfannes/treeDAG

max_forks_repo_name: thomasfannes/treeDAG


text:
#ifndef ASLAM_BACKEND_LINEAR_SYSTEM_SOLVER_HPP
#define ASLAM_BACKEND_LINEAR_SYSTEM_SOLVER_HPP

#include <vector>
#include <Eigen/Core>
#include <boost/function.hpp>
#include <sm/assert_macros.hpp>

namespace aslam {
  namespace backend {

    class DesignVariable;
    class ErrorTerm;
    class Matrix;

    namespace callback {
      class Manager;
    }

    class LinearSystemSolver {
    public:
      SM_DEFINE_EXCEPTION(Exception, std::runtime_error);

      LinearSystemSolver();

      virtual ~LinearSystemSolver();

      /// \brief Evaluate the error using nThreads.
      double evaluateError(size_t nThreads, bool useMEstimator, callback::Manager * callback = nullptr);

      /// \brief initialized the matrix structure for the problem with these error terms and errors.
      void initMatrixStructure(const std::vector<DesignVariable*>& dvs, const std::vector<ErrorTerm*>& errors, bool useDiagonalConditioner);

      /// \brief build the system of equations.
      virtual void buildSystem(size_t nThreads, bool useMEstimator) = 0;

      /// \brief Set the diagonal matrix conditioner.
      ///        NOTE: The square of these values will be added to the diagonal of the Hessian matrix
      virtual void setConditioner(const Eigen::VectorXd& diag);

      /// \brief Set a constant diagonal conditioner.
      ///        NOTE: The square of this value will be added to the diagonal of the Hessian matrix
      virtual void setConstantConditioner(double diag);

      /// \brief solve the system storing the solution in outDx and returning true on success.
      virtual bool solveSystem(Eigen::VectorXd& outDx) = 0;

      virtual std::string name() const = 0;

      /// \brief return the right-hand side of the equation system.
      virtual const Eigen::VectorXd& rhs() const;

      /// \brief return the Jacobian matrix if available. Null if not available.
      virtual const Matrix* Jacobian() const {
        return NULL;
      }

      /// \brief return the Hessian matrix if avaliable. Null if not available.
      virtual const Matrix* Hessian() const {
        return NULL;
      }

      /// \brief return the full error vector
      virtual const Eigen::VectorXd& e() const;

      /// \brief the number of rows in the Jacobian matrix
      size_t JRows() const;

      /// \brief the number of columns in the Jacobian matrix
      size_t JCols() const;

      // helper function for dog leg implementation / steepest descent solution
      virtual double rhsJtJrhs() = 0;

      /// \brief If enabled the system builder must not throw on constant error terms (:= not depending on any active design variable)
      bool isAcceptConstantErrorTerms() const {
        return _acceptConstantErrorTerms;
      }
      void setAcceptConstantErrorTerms(bool acceptConstantErrorTerms);
    protected:
      /// \brief initialized the matrix structure for the problem with these error terms and errors.
      virtual void initMatrixStructureImplementation(const std::vector<DesignVariable*>& dvs, const std::vector<ErrorTerm*>& errors, bool useDiagonalConditioner) = 0;

      /// \brief Set the row base and column base of the design variables (to tweak the ordering)
      ///        The default implementation doesn't do anything.
      virtual void setOrdering(const std::vector<DesignVariable*>& /* dvs */, const std::vector<ErrorTerm*>& /* errors */ ) { }

      /// \brief a function for one thread to evaluate a set of error terms.
      void evaluateErrors(size_t threadId, size_t startIdx, size_t endIdx, bool useMEstimator);

      /// \brief a function to split a multi-threaded job across all error term indices.
      void setupThreadedJob(boost::function<void(size_t, size_t, size_t, bool)> job, size_t nThreads, bool useMEstimator);

      /// \brief Event hook to handle new value for the acceptConstantErrorTerms property
      virtual void handleNewAcceptConstantErrorTerms();

      /// \brief the vector of error terms.
      std::vector<ErrorTerm*> _errorTerms;

      /// \brief The squared error values calculated locally for a single thread.
      std::vector<double> _threadLocalErrors;

      /// \brief the error vector;
      Eigen::VectorXd _e;

      /// \brief the linear system rhs.
      Eigen::VectorXd _rhs;

      /// \brief Should we use a diagonal conditioner
      bool _useDiagonalConditioner;

      /// \brief If enabled the system builder must not complain about constant error terms (:= not depending on any active design variable)
      bool _acceptConstantErrorTerms;

      /// \brief The diagonal conditioner
      Eigen::VectorXd _diagonalConditioner;

      /// \brief The number of rows in the Jacobian matrix
      size_t _JRows;

      /// \brief The number of columns in the Jacobian matrix
      size_t _JCols;
    };

  } // namespace backend
} // namespace aslam

#endif /* ASLAM_BACKEND_QR_SOLUTION_HPP */


text:
/**
 * Copyright (C) 2018-2022 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.
 */

#include "SectionMCS.h"

#include "XclBinUtilities.h"
#include <boost/algorithm/string.hpp>
#include <boost/format.hpp>
#include <boost/functional/factory.hpp>

// Disable windows compiler warnings
#ifdef _WIN32
  #pragma warning( disable : 4100)      // 4100 - Unreferenced formal parameter
#endif

namespace XUtil = XclBinUtilities;

// Static Variables / Classes
SectionMCS::init SectionMCS::initializer;

SectionMCS::init::init()
{
  auto sectionInfo = std::make_unique<SectionInfo>(MCS, "MCS", boost::factory<SectionMCS*>());
  sectionInfo->supportsSubSections = true;
  sectionInfo->subSections.push_back(getSubSectionName(MCS_PRIMARY));
  sectionInfo->subSections.push_back(getSubSectionName(MCS_SECONDARY));

  sectionInfo->supportedAddFormats.push_back(FormatType::raw);

  sectionInfo->supportedDumpFormats.push_back(FormatType::raw);

  addSectionType(std::move(sectionInfo));
}

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

using SubSectionTableCollection = std::vector<std::pair<std::string, MCS_TYPE>>;
static const SubSectionTableCollection&
getSubSectionTable()
{
  static const SubSectionTableCollection subSectionTable = {
    { "UNKNOWN", MCS_UNKNOWN },
    { "PRIMARY", MCS_PRIMARY },
    { "SECONDARY", MCS_SECONDARY }
  };

  return subSectionTable;
}

MCS_TYPE
SectionMCS::getSubSectionEnum(const std::string& sSubSectionName)
{
  auto subSectionTable = getSubSectionTable();
  auto iter = std::find_if(subSectionTable.begin(), subSectionTable.end(), [&](const auto& entry) {return boost::iequals(entry.first, sSubSectionName);});

  if (iter == subSectionTable.end())
    return MCS_UNKNOWN;

  return iter->second;
}

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

const std::string&
SectionMCS::getSubSectionName(MCS_TYPE eSubSection)
{
  auto subSectionTable = getSubSectionTable();
  auto iter = std::find_if(subSectionTable.begin(), subSectionTable.end(), [&](const auto& entry) {return entry.second == eSubSection;});

  if (iter == subSectionTable.end())
    return getSubSectionName(MCS_UNKNOWN);
  return iter->first;
}

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

void
SectionMCS::marshalToJSON(char* _pDataSegment,
                          unsigned int _segmentSize,
                          boost::property_tree::ptree& _ptree) const
{
  XUtil::TRACE("");
  XUtil::TRACE("Extracting: MCS");

  // Do we have enough room to overlay the header structure
  if (_segmentSize < sizeof(mcs)) {
    auto errMsg = boost::format("ERROR: Segment size (%d) is smaller than the size of the mcs structure (%d)") % _segmentSize % sizeof(mcs);
    throw std::runtime_error(errMsg.str());
  }

  mcs* pHdr = (mcs*)_pDataSegment;

  boost::property_tree::ptree pt_mcs;

  XUtil::TRACE(boost::format("m_count: %d") % (uint32_t)pHdr->m_count);
  XUtil::TRACE_BUF("mcs", reinterpret_cast<const char*>(pHdr), ((uint64_t)&(pHdr->m_chunk[0]) - (uint64_t)pHdr));

  // Do we have something to extract.  Note: This should never happen.
  if (pHdr->m_count == 0) {
    XUtil::TRACE("m_count is zero, nothing to extract");
    return;
  }

  pt_mcs.put("count", (boost::format("%d") % (unsigned int)pHdr->m_count).str());

  // Check to make sure that the array did not exceed its bounds
  uint64_t arraySize = ((uint64_t)&(pHdr->m_chunk[0]) - (uint64_t)pHdr) + (sizeof(mcs_chunk) * pHdr->m_count);

  if (arraySize > _segmentSize) {
    auto errMsg = boost::format("ERROR: m_chunk array size (0x%lx) exceeds segment size (0x%lx).") % arraySize % _segmentSize;
    throw std::runtime_error(errMsg.str());
  }

  // Examine and extract the data
  for (int index = 0; index < pHdr->m_count; ++index) {
    boost::property_tree::ptree pt_mcs_chunk;
    XUtil::TRACE(boost::format("[%d]: m_type: %s, m_offset: 0x%lx, m_size: 0x%lx")
                 % index
                 % getSubSectionName((MCS_TYPE)pHdr->m_chunk[index].m_type)
                 % pHdr->m_chunk[index].m_offset
                 % pHdr->m_chunk[index].m_size);

    XUtil::TRACE_BUF("m_chunk", reinterpret_cast<const char*>(&(pHdr->m_chunk[index])), sizeof(mcs_chunk));

    // Do some error checking
    char* ptrImageBase = _pDataSegment + pHdr->m_chunk[index].m_offset;

    // Check to make sure that the MCS image is partially looking good
    if ((uint64_t)ptrImageBase > ((uint64_t)_pDataSegment) + _segmentSize) {
      auto errMsg = boost::format("ERROR: MCS image %d start offset exceeds MCS segment size.") % index;
      throw std::runtime_error(errMsg.str());
    }

    if (((uint64_t)ptrImageBase) + pHdr->m_chunk[index].m_size > ((uint64_t)_pDataSegment) + _segmentSize) {
      auto errMsg = boost::format("ERROR: MCS image %d size exceeds the MCS segment size.") % index;
      throw std::runtime_error(errMsg.str());
    }

    pt_mcs_chunk.put("m_type", getSubSectionName((MCS_TYPE)pHdr->m_chunk[index].m_type).c_str());
    pt_mcs_chunk.put("m_offset", (boost::format("0x%ld") % pHdr->m_chunk[index].m_offset).str());
    pt_mcs_chunk.put("m_size", (boost::format("0x%ld") % pHdr->m_chunk[index].m_size).str());
  }

  // TODO: Add support to write out this data
}

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

void
SectionMCS::getSubPayload(char* _pDataSection,
                          unsigned int _sectionSize,
                          std::ostringstream& _buf,
                          const std::string& _sSubSectionName,
                          Section::FormatType _eFormatType) const
{
  // Make sure we support the subsystem
  if (Section::supportsSubSectionName(m_eKind, _sSubSectionName) == false) {
    auto errMsg = boost::format("ERROR: For section '%s' the subsystem '%s' is not supported.") % getSectionKindAsString() % _sSubSectionName;
    throw std::runtime_error(errMsg.str());
  }

  // Make sure we support the format type
  if (_eFormatType != FormatType::raw) {
    auto errMsg = boost::format("ERROR: For section '%s' the format type (%d) is not supported.") % getSectionKindAsString() % (unsigned int)_eFormatType;
    throw std::runtime_error(errMsg.str());
  }

  // Get the payload
  std::vector<mcsBufferPair> mcsBuffers;

  if (m_pBuffer != nullptr) {
    extractBuffers(m_pBuffer, m_bufferSize, mcsBuffers);
  }

  MCS_TYPE eMCSType = getSubSectionEnum(_sSubSectionName);

  for (auto mcsBuffer : mcsBuffers) {
    if (mcsBuffer.first == eMCSType) {
      const std::string& sBuffer = mcsBuffer.second->str();
      _buf.write(sBuffer.c_str(), sBuffer.size());
    }
  }
}

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

void
SectionMCS::extractBuffers(const char* _pDataSection,
                           unsigned int _sectionSize,
                           std::vector<mcsBufferPair>& _mcsBuffers) const
{
  XUtil::TRACE("Extracting: MCS buffers");

  // Do we have enough room to overlay the header structure
  if (_sectionSize < sizeof(mcs)) {
    auto errMsg = boost::format("ERROR: Section size (%d) is smaller than the size of the mcs structure (%d)") % _sectionSize % sizeof(mcs);
    throw std::runtime_error(errMsg.str());
  }

  mcs* pHdr = (mcs*)_pDataSection;

  XUtil::TRACE(boost::format("m_count: %d") % (uint32_t)pHdr->m_count);
  XUtil::TRACE_BUF("mcs", reinterpret_cast<const char*>(pHdr), ((uint64_t)&(pHdr->m_chunk[0]) - (uint64_t)pHdr));

  // Do we have something to extract.  Note: This should never happen.
  if (pHdr->m_count == 0) {
    XUtil::TRACE("m_count is zero, nothing to extract");
    return;
  }

  // Check to make sure that the array did not exceed its bounds
  uint64_t arraySize = ((uint64_t)&(pHdr->m_chunk[0]) - (uint64_t)pHdr) + (sizeof(mcs_chunk) * pHdr->m_count);

  if (arraySize > _sectionSize) {
    auto errMsg = boost::format("ERROR: m_chunk array size (0x%lx) exceeds segment size (0x%lx).") % arraySize % _sectionSize;
    throw std::runtime_error(errMsg.str());
  }

  // Examine and extract the data
  for (int index = 0; index < pHdr->m_count; ++index) {
    XUtil::TRACE(boost::format("[%d]: m_type: %s, m_offset: 0x%lx, m_size: 0x%lx")
                 % index
                 % getSubSectionName((MCS_TYPE)pHdr->m_chunk[index].m_type)
                 % pHdr->m_chunk[index].m_offset
                 % pHdr->m_chunk[index].m_size);

    XUtil::TRACE_BUF("m_chunk", reinterpret_cast<const char*>(&(pHdr->m_chunk[index])), sizeof(mcs_chunk));

    const char* ptrImageBase = _pDataSection + pHdr->m_chunk[index].m_offset;

    // Check to make sure that the MCS image is partially looking good
    if ((uint64_t)ptrImageBase > ((uint64_t)_pDataSection) + _sectionSize) {
      auto errMsg = boost::format("ERROR: MCS image %d start offset exceeds MCS segment size.") % index;
      throw std::runtime_error(errMsg.str());
    }

    if (((uint64_t)ptrImageBase) + pHdr->m_chunk[index].m_size > ((uint64_t)_pDataSection) + _sectionSize) {
      auto errMsg = boost::format("ERROR: MCS image %d size exceeds the MCS segment size.") % index;
      throw std::runtime_error(errMsg.str());
    }

    std::ostringstream* pBuffer = new std::ostringstream;
    pBuffer->write(ptrImageBase, pHdr->m_chunk[index].m_size);

    _mcsBuffers.emplace_back((MCS_TYPE)pHdr->m_chunk[index].m_type, pBuffer);
  }
}

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

void
SectionMCS::buildBuffer(const std::vector<mcsBufferPair>& _mcsBuffers,
                        std::ostringstream& _buffer) const
{
  XUtil::TRACE("Building: MCS buffers");

  // Must have something to work with
  int count = (int)_mcsBuffers.size();
  if (count == 0)
    return;

  mcs mcsHdr = mcs{};
  mcsHdr.m_count = (int8_t)count;

  XUtil::TRACE(boost::format("m_count: %d") % (int)mcsHdr.m_count);

  // Write out the entire structure except for the mcs structure
  XUtil::TRACE_BUF("mcs - minus mcs_chunk", reinterpret_cast<const char*>(&mcsHdr), (sizeof(mcs) - sizeof(mcs_chunk)));
  _buffer.write(reinterpret_cast<const char*>(&mcsHdr), (sizeof(mcs) - sizeof(mcs_chunk)));

  // Calculate The mcs_chunks data
  std::vector<mcs_chunk> mcsChunks;
  {
    uint64_t currentOffset = ((sizeof(mcs) - sizeof(mcs_chunk)) +
                              (sizeof(mcs_chunk) * count));

    for (auto mcsEntry : _mcsBuffers) {
      mcs_chunk mcsChunk = mcs_chunk{};
      mcsChunk.m_type = (uint8_t)mcsEntry.first;   // Record the MCS type

      mcsEntry.second->seekp(0, std::ios_base::end);
      mcsChunk.m_size = mcsEntry.second->tellp();
      mcsChunk.m_offset = currentOffset;
      currentOffset += mcsChunk.m_size;

      mcsChunks.push_back(mcsChunk);
    }
  }

  // Finish building the buffer
  // First the array
  {
    int index = 0;
    for (auto mcsChunk : mcsChunks) {
      XUtil::TRACE(boost::format("[%d]: m_type: %d, m_offset: 0x%lx, m_size: 0x%lx")
                   % index++
                   % mcsChunk.m_type
                   % mcsChunk.m_offset
                   % mcsChunk.m_size);
      XUtil::TRACE_BUF("mcs_chunk", reinterpret_cast<const char*>(&mcsChunk), sizeof(mcs_chunk));
      _buffer.write(reinterpret_cast<const char*>(&mcsChunk), sizeof(mcs_chunk));
    }
  }

  // Second the data
  {
    for (auto mcsEntry : _mcsBuffers) {
      const std::string& stringBuffer = mcsEntry.second->str();
      _buffer.write(stringBuffer.c_str(), stringBuffer.size());
    }
  }
}

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

void
SectionMCS::readSubPayload(const char* _pOrigDataSection,
                           unsigned int _origSectionSize,
                           std::istream& _istream,
                           const std::string& _sSubSection,
                           Section::FormatType _eFormatType,
                           std::ostringstream& _buffer) const
{
  // Determine subsection name
  MCS_TYPE eMCSType = getSubSectionEnum(_sSubSection);

  if (eMCSType == MCS_UNKNOWN) {
    auto errMsg = boost::format("ERROR: Not support subsection '%s' for section '%s',") % _sSubSection % getSectionKindAsString();
    throw std::runtime_error(errMsg.str());
  }

  // Validate format type
  if (_eFormatType != Section::FormatType::raw) {
    auto errMsg = boost::format("ERROR: Section '%s' only supports 'RAW' subsections.") % getSectionKindAsString();
    throw std::runtime_error(errMsg.str());
  }

  // Get any previous sections
  std::vector<mcsBufferPair> mcsBuffers;

  if (_pOrigDataSection != nullptr) {
    extractBuffers(_pOrigDataSection, _origSectionSize, mcsBuffers);
  }

  // Check to see if subsection already exists
  for (auto mcsEntry : mcsBuffers) {
    if (mcsEntry.first == eMCSType) {
      auto errMsg = boost::format("ERROR: Subsection '%s' already exists for section '%s',") % _sSubSection % getSectionKindAsString();
      throw std::runtime_error(errMsg.str());
    }
  }

  // Things are good, now get this new buffer
  {
    _istream.seekg(0, _istream.end);
    std::streamsize mcsSize = _istream.tellg();

    // -- Read contents into memory buffer --
    std::unique_ptr<unsigned char> memBuffer(new unsigned char[mcsSize]);
    _istream.clear();
    _istream.seekg(0, _istream.beg);
    _istream.read((char*)memBuffer.get(), mcsSize);

    std::ostringstream* buffer = new std::ostringstream;
    buffer->write(reinterpret_cast<const char*>(memBuffer.get()), mcsSize);
    mcsBuffers.emplace_back(eMCSType, buffer);
  }

  // Now create a new buffer stream
  buildBuffer(mcsBuffers, _buffer);

  // Clean up the memory
  for (auto mcsEntry : mcsBuffers) {
    delete mcsEntry.second;
    mcsEntry.second = nullptr;
  }
}

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

bool
SectionMCS::subSectionExists(const std::string& _sSubSectionName) const
{
  // Get a list of the sections
  std::vector<mcsBufferPair> mcsBuffers;
  if (m_pBuffer != nullptr) {
    extractBuffers(m_pBuffer, m_bufferSize, mcsBuffers);
  }

  // Search for the given section
  MCS_TYPE eMCSType = getSubSectionEnum(_sSubSectionName);
  for (auto mcsBuffer : mcsBuffers) {
    if (mcsBuffer.first == eMCSType) {
      return true;
    }
  }

  // If we get here, then the section of interest doesn't exist
  return false;
}

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

void
SectionMCS::writeSubPayload(const std::string& _sSubSectionName,
                            FormatType _eFormatType,
                            std::fstream&  _oStream) const
{
  // Validate format type
  if (_eFormatType != Section::FormatType::raw) {
    auto errMsg = boost::format("ERROR: Section '%s' only supports 'RAW' subsections.") % getSectionKindAsString();
    throw std::runtime_error(errMsg.str());
  }

  // Obtain the collection of MCS buffers
  std::vector<mcsBufferPair> mcsBuffers;
  if (m_pBuffer != nullptr) {
    extractBuffers(m_pBuffer, m_bufferSize, mcsBuffers);
  }

  // Search for the collection of interest
  MCS_TYPE eMCSType = getSubSectionEnum(_sSubSectionName);
  for (auto mcsBuffer : mcsBuffers) {
    if (mcsBuffer.first == eMCSType) {
      const std::string& buffer = mcsBuffer.second->str();
      _oStream.write(buffer.c_str(), buffer.size());
      return;
    }
  }

  // No collection entry
  auto errMsg = boost::format("ERROR: Subsection '%s' of section '%s' does not exist") % _sSubSectionName % getSectionKindAsString();
  throw std::runtime_error(errMsg.str());
}

ext: cxx

max_stars_repo_name: bryanloz-xilinx/XRT

max_issues_repo_name: bryanloz-xilinx/XRT

max_forks_repo_name: bryanloz-xilinx/XRT


text:
//          Copyright Carl Philipp Reh 2009 - 2016.
// 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 <fcppt/make_cref.hpp>
#include <fcppt/make_ref.hpp>
#include <fcppt/reference_comparison.hpp>
#include <fcppt/reference_output.hpp>
#include <fcppt/optional/comparison.hpp>
#include <fcppt/optional/output.hpp>
#include <fcppt/optional/reference.hpp>
#include <fcppt/preprocessor/disable_gcc_warning.hpp>
#include <fcppt/preprocessor/pop_warning.hpp>
#include <fcppt/preprocessor/push_warning.hpp>
#include <fcppt/variant/to_optional_ref.hpp>
#include <fcppt/variant/variadic.hpp>
#include <fcppt/config/external_begin.hpp>
#include <boost/test/unit_test.hpp>
#include <fcppt/config/external_end.hpp>

FCPPT_PP_PUSH_WARNING
FCPPT_PP_DISABLE_GCC_WARNING(-Weffc++)

BOOST_AUTO_TEST_CASE(
	variant_to_optional_ref
)
{
FCPPT_PP_POP_WARNING

	typedef
	fcppt::variant::variadic<
		int,
		std::string
	>
	variant;

	{
		variant var(
			42
		);

		BOOST_CHECK_EQUAL(
			fcppt::variant::to_optional_ref<
				int
			>(
				var
			),
			fcppt::optional::reference<
				int
			>(
				fcppt::make_ref(
					var.get_unsafe<
						int
					>()
				)
			)
		);

		BOOST_CHECK_EQUAL(
			fcppt::variant::to_optional_ref<
				std::string
			>(
				var
			),
			fcppt::optional::reference<
				std::string
			>()
		);
	}

	{
		variant const var(
			42
		);

		BOOST_CHECK_EQUAL(
			fcppt::variant::to_optional_ref<
				int const
			>(
				var
			),
			fcppt::optional::reference<
				int const
			>(
				fcppt::make_cref(
					var.get_unsafe<
						int
					>()
				)
			)
		);

		BOOST_CHECK_EQUAL(
			fcppt::variant::to_optional_ref<
				std::string const
			>(
				var
			),
			fcppt::optional::reference<
				std::string const
			>()
		);
	}
}

max_stars_repo_name: vinzenz/fcppt

max_issues_repo_name: vinzenz/fcppt

max_forks_repo_name: vinzenz/fcppt


text:
#include <iostream>
#include <boost/cstdint.hpp>
#include <CGAL/assertions.h>

int main()
{
  std::cout << "Verifying the sizes of boost::[u]int{8,16,32,64}_t"
            << std::endl;

  CGAL_static_assertion(sizeof(boost::int8_t)  == 1);
  CGAL_static_assertion(sizeof(boost::int16_t) == 2);
  CGAL_static_assertion(sizeof(boost::int32_t) == 4);
#ifndef BOOST_NO_INT64_T
  CGAL_static_assertion(sizeof(boost::int64_t) == 8);
#endif

  CGAL_static_assertion(sizeof(boost::uint8_t)  == 1);
  CGAL_static_assertion(sizeof(boost::uint16_t) == 2);
  CGAL_static_assertion(sizeof(boost::uint32_t) == 4);
#ifndef BOOST_NO_INT64_T
  CGAL_static_assertion(sizeof(boost::uint64_t) == 8);
#endif

  return 0;
}

max_stars_repo_name: hlzz/dotfiles

max_issues_repo_name: hlzz/dotfiles

max_forks_repo_name: hlzz/dotfiles


text:
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- vim:set ts=4 sw=4 sts=4 noet: */
#include "runtime/channel.h"

#include <cassert>
#include <cerrno>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <map>
#include <memory>
#include <set>
#include <unordered_set>
#include <vector>

#include <boost/uuid/uuid_io.hpp>

#include "bc/index.h"
#include "czmq.h"
#include "zmq.h"

namespace flint {
namespace runtime {

namespace {

const size_t kBufferSize = 64;
const size_t kPrefixSize = 48;

int Process(void *data, int argc, char **argv, char **names)
{
	(void)names;
	assert(argc == 2);
	auto *cv = static_cast<std::vector<std::string> *>(data);
	size_t len = std::strlen(argv[1]);
	assert(16+len <= kPrefixSize);
	char prefix[kPrefixSize];
	std::memset(prefix, 0, kPrefixSize);
	std::memcpy(prefix, argv[0], 16);
	std::memcpy(prefix+16, argv[1], len);
	cv->emplace_back(std::string(prefix, kPrefixSize));
	return 0;
}

}

class ChannelImpl {
public:
	explicit ChannelImpl(const std::vector<std::string> &cv);

	~ChannelImpl();

	bool Connect(const char *host, const std::map<key::Data, size_t> &output);

	bool Lookup(int index, double t, double *d);

	void Send(const double *data);

private:
	std::vector<void *> sv_;
	std::vector<std::map<double, double> > v_;
	std::map<std::string, int> m_;
	std::map<std::string, size_t> output_;
	void *ctx_;
	void *sock_;
	char buf_[kBufferSize];
};

ChannelImpl::ChannelImpl(const std::vector<std::string> &v)
	: sv_(v.size())
	, v_(v.size())
	, ctx_(nullptr)
	, sock_(nullptr)
{
	for (size_t i=0;i<v.size();i++)
		sv_[i] = nullptr;
	int i = 0;
	for (const auto &s : v)
		m_.emplace(s, i++);
}

ChannelImpl::~ChannelImpl()
{
	for (void *sock : sv_)
		if (sock)
			zmq_close(sock);
	if (sock_)
		zmq_close(sock_);
	if (ctx_) {
		zmq_ctx_shutdown(ctx_);
		zmq_ctx_term(ctx_);
	}
}

bool ChannelImpl::Connect(const char *host, const std::map<key::Data, size_t> &output)
{
	const size_t kLength = 128;

	bool result = false;
	// get available address
	char address[64];
	auto *iflist = ziflist_new();
	assert(iflist);
	const char *name = ziflist_first(iflist);
	if (!name) {
		std::cerr << "failed to get interface name" << std::endl;
		ziflist_destroy(&iflist);
		return false;
	}
	std::sprintf(address, "%s", ziflist_address(iflist));
	ziflist_destroy(&iflist);

	ctx_ = zmq_ctx_new();
	assert(ctx_);

	sock_ = zmq_socket(ctx_, ZMQ_PUB);
	assert(sock_);
	char output_endpoint[kLength];
	std::sprintf(output_endpoint, "tcp://%s:*", address);
	int r = zmq_bind(sock_, output_endpoint);
	if (r != 0) {
		std::cerr << "failed to bind socket: "
				  << zmq_strerror(errno)
				  << std::endl;
		return false;
	}
	size_t len = kLength;
	r = zmq_getsockopt(sock_, ZMQ_LAST_ENDPOINT, &output_endpoint, &len);
	if (r != 0) {
		std::cerr << "failed to get last endpoint: "
				  << zmq_strerror(errno)
				  << std::endl;
		return false;
	}

	zactor_t *peer = zactor_new(zgossip, output_endpoint); // FIXME
	assert(peer);
	char endpoint[kLength];
	std::sprintf(endpoint, "tcp://%s:20010", host);
	zstr_sendx(peer, "CONNECT", endpoint, nullptr);
	// register output
	for (const auto &p : output) {
		const auto &kd = p.first;
		output_.emplace(kd.GetPrefixString(), p.second);
		char key[256];
		std::sprintf(key, "%s:%s", boost::uuids::to_string(kd.uuid).c_str(), kd.name.c_str());
		zstr_sendx(peer, "PUBLISH", key, output_endpoint, nullptr);
	}

	zpoller_t *poller = zpoller_new(peer, nullptr);
	assert(poller);
	// poll until all of input become registered
	while (!m_.empty()) {
		void *which = zpoller_wait(poller, -1); // no timeout
		if (!which)
			goto bail;
		assert(which == peer);
		char *command, *key, *value;
		zstr_recvx(peer, &command, &key, &value, nullptr);
		if (std::strcmp(command, "DELIVER") == 0) {
			std::cerr << "key: " << key << std::endl;
			key::Data kd;
			if (!key::Data::FromString(key, &kd)) {
				zstr_free(&command);
				zstr_free(&key);
				zstr_free(&value);
				goto bail;
			}
			auto it = m_.find(kd.GetPrefixString());
			if (it != m_.end()) {
				void *sock = zmq_socket(ctx_, ZMQ_SUB);
				assert(sock);
				r = zmq_setsockopt(sock, ZMQ_SUBSCRIBE, it->first.c_str(), kPrefixSize);
				assert(r == 0);
				r = zmq_connect(sock, value);
				if (r != 0) {
					std::cerr << "failed to connect socket: "
							  << zmq_strerror(errno)
							  << std::endl;
					return false;
				}
				sv_[it->second] = sock;
				m_.erase(it);
			}
		}
		zstr_free(&command);
		zstr_free(&key);
		zstr_free(&value);
	}

	// TODO: initial values
	for (auto &m : v_)
		m.emplace(0, 0);
	result = true;
 bail:
	zpoller_destroy(&poller);
	zactor_destroy(&peer);
	return result;
}

bool ChannelImpl::Lookup(int index, double t, double *d)
{
	auto &m = v_[index];
	std::pair<std::map<double, double>::iterator, std::map<double, double>::iterator> r;
	r = m.equal_range(t);
	if (r.first != r.second) { // found the exact data
		*d = r.first->second;
		return true;
	}
	if (r.first == m.begin()) { // smaller than every existing data
		*d = 0; // FIXME
		return true;
	}
	if (r.first == m.end()) { // larger than every existing data
		double t_r, v_r;
		while ( zmq_recv(sv_[index], buf_, kBufferSize, 0) >= 0 ) {
			std::memcpy(&t_r, buf_+kPrefixSize, sizeof(t_r));
			std::memcpy(&v_r, buf_+kPrefixSize+sizeof(t_r), sizeof(v_r));
			v_[index].emplace(t_r, v_r);
			std::cerr << "remote: " << std::string(buf_+16, kPrefixSize-16)
					  << ": " << t_r
					  << ": " << v_r
					  << std::endl;
			if (t_r >= t) {
				*d = v_r;
				return true;
			}
		}
		std::cerr << "failed to receive data: "
				  << zmq_strerror(errno) << std::endl;
		return false;
	}
	auto it = r.first;
	--it;
	*d = it->second; // FIXME
	return true;
}

void ChannelImpl::Send(const double *data)
{
	for (const auto &p : output_) {
		const auto &prefix = p.first;
		std::memset(buf_, 0, kBufferSize);
		std::memcpy(buf_, prefix.c_str(), kPrefixSize);
		std::memcpy(buf_+kPrefixSize, &data[kIndexTime], sizeof(double));
		std::memcpy(buf_+kPrefixSize+sizeof(double), &data[p.second], sizeof(double));
		if (zmq_send(sock_, buf_, kBufferSize, 0) < 0)
			std::cerr << "failed to send data: "
					  << zmq_strerror(errno)
					  << std::endl;
	}
}

Channel::Channel(const std::vector<std::string> &cv)
	: impl_(new ChannelImpl(cv))
{}

Channel::~Channel() = default;

bool Channel::Connect(const char *host, const std::map<key::Data, size_t> &output)
{
	return impl_->Connect(host, output);
}

bool Channel::Lookup(int index, double t, double *d)
{
	return impl_->Lookup(index, t, d);
}

void Channel::Send(const double *data)
{
	impl_->Send(data);
}

bool LoadChannel(sqlite3 *db,
				 std::unique_ptr<Channel> &channel)
{
	std::vector<std::string> v;
	char *em;
	int e = sqlite3_exec(db, "SELECT uuid, name FROM channels",
						 &Process, &v, &em);
	if (e != SQLITE_OK) {
		std::cerr << "failed to select channels: " << e << ": " << em << std::endl;
		sqlite3_free(em);
		return false;
	}
	if (v.empty()) {
		channel.reset();
		return true;
	}
	channel.reset(new Channel(v));
	return true;
}

}
}

max_stars_repo_name: Abhisheknishant/Flint

max_issues_repo_name: Abhisheknishant/Flint

max_forks_repo_name: Abhisheknishant/Flint


text:
// Copyright  (C)  2007  Ruben Smits <ruben dot smits at mech dot kuleuven dot be>

// Version: 1.0
// Author: Ruben Smits <ruben dot smits at mech dot kuleuven dot be>
// Maintainer: Ruben Smits <ruben dot smits at mech dot kuleuven dot be>
// URL: http://www.orocos.org/kdl

// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.

// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.

// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

#ifndef KDL_JACOBIAN_HPP
#define KDL_JACOBIAN_HPP

#include "frames.hpp"
#include <Eigen/Core>

namespace KDL
{
    // Equal is friend function, but default arguments for friends are forbidden (§8.3.6.4)
    class Jacobian;
    bool Equal(const Jacobian& a,const Jacobian& b,double eps=epsilon);
    void SetToZero(Jacobian& jac);

    class Jacobian
    {
    public:

        EIGEN_MAKE_ALIGNED_OPERATOR_NEW
        Eigen::Matrix<double,6,Eigen::Dynamic> data;
        Jacobian();
        explicit Jacobian(unsigned int nr_of_columns);
        Jacobian(const Jacobian& arg);

        ///Allocates memory for new size (can break realtime behavior)
        void resize(unsigned int newNrOfColumns);

        ///Allocates memory if size of this and argument is different
        Jacobian& operator=(const Jacobian& arg);

        bool operator ==(const Jacobian& arg)const;
        bool operator !=(const Jacobian& arg)const;

        friend bool Equal(const Jacobian& a,const Jacobian& b,double eps);

        ~Jacobian();

        double operator()(unsigned int i,unsigned int j)const;
        double& operator()(unsigned int i,unsigned int j);
        unsigned int rows()const;
        unsigned int columns()const;

        friend void SetToZero(Jacobian& jac);

        friend bool changeRefPoint(const Jacobian& src1, const Vector& base_AB, Jacobian& dest);
        friend bool changeBase(const Jacobian& src1, const Rotation& rot, Jacobian& dest);
        friend bool changeRefFrame(const Jacobian& src1,const Frame& frame, Jacobian& dest);

        Twist getColumn(unsigned int i) const;
        void setColumn(unsigned int i,const Twist& t);

        void changeRefPoint(const Vector& base_AB);
        void changeBase(const Rotation& rot);
        void changeRefFrame(const Frame& frame);

    };

    bool changeRefPoint(const Jacobian& src1, const Vector& base_AB, Jacobian& dest);
    bool changeBase(const Jacobian& src1, const Rotation& rot, Jacobian& dest);
    bool changeRefFrame(const Jacobian& src1,const Frame& frame, Jacobian& dest);

}

#endif


text:
// Copyright 2018 Hans Dembinski
//
// 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 <boost/config/workaround.hpp>
#if BOOST_WORKAROUND(BOOST_CLANG, >= 1)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wlanguage-extension-token"
#endif
#include <boost/units/quantity.hpp>
#include <boost/units/systems/si/length.hpp>
#if BOOST_WORKAROUND(BOOST_CLANG, >= 1)
#pragma clang diagnostic pop
#endif
#include <boost/core/lightweight_test.hpp>
#include <boost/histogram/axis/ostream.hpp>
#include <boost/histogram/axis/regular.hpp>
#include <boost/histogram/detail/throw_exception.hpp>
#include <boost/histogram/histogram.hpp>
#include <boost/histogram/indexed.hpp>
#include <boost/histogram/literals.hpp>
#include <boost/histogram/make_histogram.hpp>
#include <boost/histogram/ostream.hpp>
#include <limits>
#include "is_close.hpp"

using namespace boost::histogram;
using namespace boost::histogram::literals;
namespace tr = axis::transform;

int main() {
  using namespace boost::units;
  using Q = quantity<si::length>;

  // axis::regular with quantity
  {
    axis::regular<Q> b(2, 0 * si::meter, 2 * si::meter);
    BOOST_TEST_EQ(b.bin(-1).lower() / si::meter,
                  -std::numeric_limits<double>::infinity());
    BOOST_TEST_IS_CLOSE(b.bin(0).lower() / si::meter, 0.0, 1e-9);
    BOOST_TEST_IS_CLOSE(b.bin(1).lower() / si::meter, 1.0, 1e-9);
    BOOST_TEST_IS_CLOSE(b.bin(2).lower() / si::meter, 2.0, 1e-9);
    BOOST_TEST_EQ(b.bin(2).upper() / si::meter, std::numeric_limits<double>::infinity());

    BOOST_TEST_EQ(b.index(-std::numeric_limits<double>::infinity() * si::meter), -1);
    BOOST_TEST_EQ(b.index(-1 * si::meter), -1); // produces NaN in conversion
    BOOST_TEST_EQ(b.index(0 * si::meter), 0);
    BOOST_TEST_EQ(b.index(0.99 * si::meter), 0);
    BOOST_TEST_EQ(b.index(1 * si::meter), 1);
    BOOST_TEST_EQ(b.index(1.99 * si::meter), 1);
    BOOST_TEST_EQ(b.index(2 * si::meter), 2);
    BOOST_TEST_EQ(b.index(100 * si::meter), 2);
    BOOST_TEST_EQ(b.index(std::numeric_limits<double>::infinity() * si::meter), 2);
  }

  // axis::regular with quantity and transform
  {
    axis::regular<Q, tr::log> b(2, 1 * si::meter, 10 * si::meter);
    BOOST_TEST_EQ(b.value(-1) / si::meter, 0);
    BOOST_TEST_IS_CLOSE(b.value(0) / si::meter, 1.0, 1e-9);
    BOOST_TEST_IS_CLOSE(b.value(1) / si::meter, 3.1623, 1e-3);
    BOOST_TEST_IS_CLOSE(b.value(2) / si::meter, 10.0, 1e-9);
    BOOST_TEST_EQ(b.value(3) / si::meter, std::numeric_limits<double>::infinity());
  }

  // histogram with quantity axis
  {
    auto h = make_histogram(axis::regular<Q>(2, 0 * si::meter, 1 * si::meter),
                            axis::regular<>(2, 0, 1));
    h(0.1 * si::meter, 0.1); // fills bin (0, 0)
    BOOST_TEST_EQ(h.at(0, 0), 1);
    for (auto&& x : indexed(h)) {
      BOOST_TEST_THROWS(x.density(), std::runtime_error); // cannot use density method
      BOOST_TEST_EQ(x.index(0), 2.0 * x.bin(0_c).lower() / si::meter);
      BOOST_TEST_EQ(x.index(1), 2.0 * x.bin(1_c).lower());
    }
  }

  return boost::report_errors();
}