text:
#include "Scene_points_with_normal_item.h"
#include "Polyhedron_type.h"
#include <CGAL/Polygon_mesh_processing/compute_normal.h>

#include <CGAL/IO/read_ply_points.h>
#include <CGAL/IO/write_ply_points.h>
#include <CGAL/IO/read_off_points.h>
#include <CGAL/IO/write_off_points.h>
#include <CGAL/IO/read_xyz_points.h>
#include <CGAL/IO/write_xyz_points.h>
#include <CGAL/Timer.h>
#include <CGAL/Memory_sizer.h>

#include <CGAL/Three/Viewer_interface.h>
#include <CGAL/Orthogonal_k_neighbor_search.h>
#include <CGAL/Search_traits_3.h>

#include <QObject>
#include <QMenu>
#include <QGLViewer/manipulatedCameraFrame.h>

#include <set>
#include <stack>
#include <algorithm>
#include <boost/array.hpp>

Scene_points_with_normal_item::Scene_points_with_normal_item()
    : Scene_item(NbOfVbos,NbOfVaos),
    m_points(new Point_set),
    m_has_normals(false)
{
  setRenderingMode(Points);
    is_selected = true;
    nb_points = 0;
    nb_selected_points = 0;
    nb_lines = 0;
}

// Copy constructor
Scene_points_with_normal_item::Scene_points_with_normal_item(const Scene_points_with_normal_item& toCopy)
    :Scene_item(NbOfVbos,NbOfVaos), // do not call superclass' copy constructor
    m_points(new Point_set(*toCopy.m_points)),
    m_has_normals(toCopy.m_has_normals)
{
  if (m_has_normals)
    {
    setRenderingMode(PointsPlusNormals);
        is_selected = true;
    }
  else
    {
    setRenderingMode(Points);
        is_selected = true;
    }
    nb_points = 0;
    nb_selected_points = 0;
    nb_lines = 0;
    invalidateOpenGLBuffers();
}

// Converts polyhedron to point set
Scene_points_with_normal_item::Scene_points_with_normal_item(const Polyhedron& input_mesh)
    : Scene_item(NbOfVbos,NbOfVaos),
    m_points(new Point_set),
    m_has_normals(true)
{
  // Converts Polyhedron vertices to point set.
  // Computes vertices normal from connectivity.

  Polyhedron::Vertex_iterator v;
  for (v = const_cast<Polyhedron&>(input_mesh).vertices_begin();
       v != const_cast<Polyhedron&>(input_mesh).vertices_end(); v++)
  {
    const Kernel::Point_3& p = v->point();
    Kernel::Vector_3 n =
      CGAL::Polygon_mesh_processing::compute_vertex_normal(v, input_mesh);
    m_points->push_back(UI_point(p,n));
  }

  setRenderingMode(PointsPlusNormals);
  is_selected = true;
  nb_points = 0;
  nb_selected_points = 0;
  nb_lines = 0;
  invalidateOpenGLBuffers();
}

Scene_points_with_normal_item::~Scene_points_with_normal_item()
{
  Q_ASSERT(m_points != NULL);
  delete m_points; m_points = NULL;
}

void Scene_points_with_normal_item::initialize_buffers(CGAL::Three::Viewer_interface *viewer) const
{
    compute_normals_and_vertices();
    //vao for the edges
    {
        program = getShaderProgram(PROGRAM_NO_SELECTION, viewer);
        program->bind();

        vaos[Edges]->bind();
        buffers[Edges_vertices].bind();
        buffers[Edges_vertices].allocate(positions_lines.data(),
                            static_cast<int>(positions_lines.size()*sizeof(double)));
        program->enableAttributeArray("vertex");
        program->setAttributeBuffer("vertex",GL_DOUBLE,0,3);
        buffers[Edges_vertices].release();

        vaos[Edges]->release();
        nb_lines = positions_lines.size();
        positions_lines.resize(0);
        std::vector<double>(positions_lines).swap(positions_lines);
        program->release();
    }
    //vao for the points
    {
        program = getShaderProgram(PROGRAM_NO_SELECTION, viewer);
        program->bind();

        vaos[ThePoints]->bind();
        buffers[Points_vertices].bind();
        buffers[Points_vertices].allocate(positions_points.data(),
                            static_cast<int>(positions_points.size()*sizeof(double)));
        program->enableAttributeArray("vertex");
        program->setAttributeBuffer("vertex",GL_DOUBLE,0,3);
        buffers[Points_vertices].release();
        vaos[ThePoints]->release();
        nb_points = positions_points.size();
        positions_points.resize(0);
        std::vector<double>(positions_points).swap(positions_points);
        program->release();
    }
    //vao for the selected points
    {
        program = getShaderProgram(PROGRAM_NO_SELECTION, viewer);
        program->bind();

        vaos[Selected_points]->bind();
        buffers[Selected_points_vertices].bind();
        buffers[Selected_points_vertices].allocate(positions_selected_points.data(),
                            static_cast<int>(positions_selected_points.size()*sizeof(double)));
        program->enableAttributeArray("vertex");
        program->setAttributeBuffer("vertex",GL_DOUBLE,0,3);
        buffers[Selected_points_vertices].release();

        vaos[Selected_points]->release();
        nb_selected_points = positions_selected_points.size();
        positions_selected_points.resize(0);
        std::vector<double>(positions_selected_points).swap(positions_selected_points);
        program->release();
    }
    are_buffers_filled = true;
}

void Scene_points_with_normal_item::compute_normals_and_vertices() const
{
    positions_points.resize(0);
    positions_lines.resize(0);
    positions_selected_points.resize(0);
    normals.resize(0);

    positions_points.reserve(m_points->size() * 3);
    positions_lines.reserve(m_points->size() * 3 * 2);

    //Shuffle container to allow quick display random points
    Point_set_3<Kernel> points = *m_points;
    std::random_shuffle (points.begin(), points.end() - m_points->nb_selected_points());
    std::random_shuffle (points.end() - m_points->nb_selected_points(), points.end());

    //The points
    {
        // The *non-selected* points
      for (Point_set_3<Kernel>::const_iterator it = points.begin(); it != points.first_selected(); it++)
	{
	  const UI_point& p = *it;
	  positions_points.push_back(p.x());
	  positions_points.push_back(p.y());
	  positions_points.push_back(p.z());
	}

        // Draw *selected* points
      for (Point_set_3<Kernel>::const_iterator it = points.first_selected(); it != points.end(); it++)
	{
	  const UI_point& p = *it;
	  positions_selected_points.push_back(p.x());
	  positions_selected_points.push_back(p.y());
	  positions_selected_points.push_back(p.z());
	}
    }

    //The lines
    {
        // Stock normals
        Kernel::Sphere_3 region_of_interest = points.region_of_interest();
        float normal_length = (float)std::sqrt(region_of_interest.squared_radius() / 1000.);

	for (Point_set_3<Kernel>::const_iterator it = points.begin(); it != points.end(); it++)
	  {
	    const UI_point& p = *it;
	    const Point_set_3<Kernel>::Vector& n = p.normal();
	    Point_set_3<Kernel>::Point q = p + normal_length * n;
	    positions_lines.push_back(p.x());
	    positions_lines.push_back(p.y());
	    positions_lines.push_back(p.z());

	    positions_lines.push_back(q.x());
	    positions_lines.push_back(q.y());
	    positions_lines.push_back(q.z());
	  }
    }
}

// Duplicates scene item
Scene_points_with_normal_item*
Scene_points_with_normal_item::clone() const
{
  return new Scene_points_with_normal_item(*this);
}

// Is selection empty?
bool Scene_points_with_normal_item::isSelectionEmpty() const
{
  return (m_points->nb_selected_points() == 0);
}

// Delete selection
void Scene_points_with_normal_item::deleteSelection()
{
  CGAL::Timer task_timer; task_timer.start();
  std::cerr << "Delete " << m_points->nb_selected_points() << " points...";

  // Delete selected points
  m_points->delete_selection();

  std::size_t memory = CGAL::Memory_sizer().virtual_size();
  std::cerr << "done: " << task_timer.time() << " seconds, "
                        << (memory>>20) << " Mb allocated"
                        << std::endl;
  invalidateOpenGLBuffers();
  Q_EMIT itemChanged();
}

// Invert selection
void Scene_points_with_normal_item::invertSelection()
{
  m_points->invert_selection();
  invalidateOpenGLBuffers();
  Q_EMIT itemChanged();
}

// Select everything
void Scene_points_with_normal_item::selectAll()
{
  m_points->select_all();
  invalidateOpenGLBuffers();
  Q_EMIT itemChanged();
}
// Reset selection mark
void Scene_points_with_normal_item::resetSelection()
{
  // Un-select all points
  m_points->unselect_all();
  invalidateOpenGLBuffers();
  Q_EMIT itemChanged();
}
  //Select duplicated points
void Scene_points_with_normal_item::selectDuplicates()
{
  std::set<Kernel::Point_3> unique_points;
  for (Point_set::iterator ptit=m_points->begin(); ptit!=m_points->end();++ptit )
    if ( !unique_points.insert(*ptit).second )
      m_points->select(ptit);
  invalidateOpenGLBuffers();
  Q_EMIT itemChanged();
}

// Loads point set from .PLY file
bool Scene_points_with_normal_item::read_ply_point_set(std::istream& stream)
{
  Q_ASSERT(m_points != NULL);

  m_points->clear();
  bool ok = stream &&
            CGAL::read_ply_points_and_normals(stream,
                                              std::back_inserter(*m_points),
                                              CGAL::make_normal_of_point_with_normal_pmap(Point_set::value_type())) &&
            !isEmpty();
  if (ok)
    {
      for (Point_set::iterator it=m_points->begin(),
             end=m_points->end();it!=end; ++it)
        {
          if (it->normal() != CGAL::NULL_VECTOR)
            {
              m_has_normals=true;
              setRenderingMode(PointsPlusNormals);
              break;
            }
        }
    }
  invalidateOpenGLBuffers();
  return ok;
}

// Write point set to .PLY file
bool Scene_points_with_normal_item::write_ply_point_set(std::ostream& stream) const
{
  Q_ASSERT(m_points != NULL);

  return stream &&
         CGAL::write_ply_points_and_normals(stream,
                                            m_points->begin(), m_points->end(),
                                            CGAL::make_normal_of_point_with_normal_pmap(Point_set::value_type()));
}

// Loads point set from .OFF file
bool Scene_points_with_normal_item::read_off_point_set(std::istream& stream)
{
  Q_ASSERT(m_points != NULL);

  m_points->clear();
  bool ok = stream &&
            CGAL::read_off_points_and_normals(stream,
                                              std::back_inserter(*m_points),
                                              CGAL::make_normal_of_point_with_normal_pmap(Point_set::value_type())) &&
            !isEmpty();
  invalidateOpenGLBuffers();
  return ok;
}

// Write point set to .OFF file
bool Scene_points_with_normal_item::write_off_point_set(std::ostream& stream) const
{
  Q_ASSERT(m_points != NULL);

  return stream &&
         CGAL::write_off_points_and_normals(stream,
                                            m_points->begin(), m_points->end(),
                                            CGAL::make_normal_of_point_with_normal_pmap(Point_set::value_type()));
}

// Loads point set from .XYZ file
bool Scene_points_with_normal_item::read_xyz_point_set(std::istream& stream)
{
  Q_ASSERT(m_points != NULL);

  m_points->clear();
  bool ok = stream &&
            CGAL::read_xyz_points_and_normals(stream,
                                              std::back_inserter(*m_points),
                                              CGAL::make_normal_of_point_with_normal_pmap(Point_set::value_type())) &&
            !isEmpty();

  if (ok)
  {
    for (Point_set::iterator it=m_points->begin(),
                             end=m_points->end();it!=end; ++it)
    {
      if (it->normal() != CGAL::NULL_VECTOR)
      {
        m_has_normals=true;
        setRenderingMode(PointsPlusNormals);
        break;
      }
    }
  }
  invalidateOpenGLBuffers();
  return ok;
}

// Write point set to .XYZ file
bool Scene_points_with_normal_item::write_xyz_point_set(std::ostream& stream) const
{
  Q_ASSERT(m_points != NULL);

  return stream &&
         CGAL::write_xyz_points_and_normals(stream,
                                            m_points->begin(), m_points->end(),
                                            CGAL::make_normal_of_point_with_normal_pmap(Point_set::value_type()));
}

QString
Scene_points_with_normal_item::toolTip() const
{
  Q_ASSERT(m_points != NULL);

  return QObject::tr("
%1 (color: %4)
"
                     "Point set
"
                     "
Number of points: %2
")
    .arg(name())
    .arg(m_points->size())
    .arg(color().name());
}

bool Scene_points_with_normal_item::supportsRenderingMode(RenderingMode m) const
{
    return m==Points ||
            ( has_normals() &&
              ( m==PointsPlusNormals || m==Splatting ) );
}

void Scene_points_with_normal_item::draw_splats(CGAL::Three::Viewer_interface* viewer) const
{
   // TODO add support for selection
   viewer->glBegin(GL_POINTS);
   for ( Point_set_3<Kernel>::const_iterator it = m_points->begin(); it != m_points->end(); it++)
   {
     const UI_point& p = *it;
     viewer->glNormal3dv(&p.normal().x());
     viewer->glMultiTexCoord1d(GL_TEXTURE2, p.radius());
     viewer->glVertex3dv(&p.x());

   }
   viewer->glEnd();

}

void Scene_points_with_normal_item::draw_edges(CGAL::Three::Viewer_interface* viewer) const
{
    double ratio_displayed = 1.0;
    if (viewer->inFastDrawing () &&
        (nb_lines/6 > 300000)) // arbitrary large value
      ratio_displayed = 6 * 300000. / (double)(nb_lines);

    if(!are_buffers_filled)
        initialize_buffers(viewer);
    vaos[Edges]->bind();
    program=getShaderProgram(PROGRAM_NO_SELECTION);
    attrib_buffers(viewer,PROGRAM_NO_SELECTION);
    program->bind();
    program->setAttributeValue("colors", this->color());
    viewer->glDrawArrays(GL_LINES, 0,
                         static_cast<GLsizei>(((std::size_t)(ratio_displayed * nb_lines)/3)));
    vaos[Edges]->release();
    program->release();
}
void Scene_points_with_normal_item::draw_points(CGAL::Three::Viewer_interface* viewer) const
{
    if(!are_buffers_filled)
        initialize_buffers(viewer);

    double ratio_displayed = 1.0;
    if (viewer->inFastDrawing () &&
        ((nb_points + nb_selected_points)/3 > 300000)) // arbitrary large value
      ratio_displayed = 3 * 300000. / (double)(nb_points + nb_selected_points);

    vaos[ThePoints]->bind();
    program=getShaderProgram(PROGRAM_NO_SELECTION);
    attrib_buffers(viewer,PROGRAM_NO_SELECTION);
    program->bind();
    program->setAttributeValue("colors", this->color());
    viewer->glDrawArrays(GL_POINTS, 0,
                         static_cast<GLsizei>(((std::size_t)(ratio_displayed * nb_points)/3)));
    vaos[ThePoints]->release();
    program->release();
    GLfloat point_size;
    viewer->glGetFloatv(GL_POINT_SIZE, &point_size);
    viewer->glPointSize(4.f);

    vaos[Selected_points]->bind();
    program=getShaderProgram(PROGRAM_NO_SELECTION);
    attrib_buffers(viewer,PROGRAM_NO_SELECTION);
    program->bind();
    program->setAttributeValue("colors", QColor(255,0,0));
    viewer->glDrawArrays(GL_POINTS, 0,
                         static_cast<GLsizei>(((std::size_t)(ratio_displayed * nb_selected_points)/3)));
    vaos[Selected_points]->release();
    program->release();
    viewer->glPointSize(point_size);
}
// Gets wrapped point set
Point_set* Scene_points_with_normal_item::point_set()
{
  Q_ASSERT(m_points != NULL);
  return m_points;
}
const Point_set* Scene_points_with_normal_item::point_set() const
{
  Q_ASSERT(m_points != NULL);
  return m_points;
}

bool
Scene_points_with_normal_item::isEmpty() const
{
  Q_ASSERT(m_points != NULL);
  return m_points->empty();
}

void
Scene_points_with_normal_item::compute_bbox() const
{
  Q_ASSERT(m_points != NULL);

  Kernel::Iso_cuboid_3 bbox = m_points->bounding_box();
  _bbox = Bbox(bbox.xmin(),bbox.ymin(),bbox.zmin(),
              bbox.xmax(),bbox.ymax(),bbox.zmax());
}

void Scene_points_with_normal_item::computes_local_spacing(int k)
{
  typedef Kernel Geom_traits;
  typedef CGAL::Search_traits_3<Geom_traits> TreeTraits;
  typedef CGAL::Orthogonal_k_neighbor_search<TreeTraits> Neighbor_search;
  typedef Neighbor_search::Tree Tree;

  Point_set::iterator end(m_points->end());

  // build kdtree
  Tree tree(m_points->begin(), end);

  // Compute the radius of each point = (distance max to k nearest neighbors)/2.
  {
    int i=0;
    for (Point_set::iterator it=m_points->begin(); it!=end; ++it, ++i)
    {
      Neighbor_search search(tree, *it, k+1);
      double maxdist2 = (--search.end())->second; // squared distance to furthest neighbor
      it->radius() = sqrt(maxdist2)/2.;
    }
  }

  m_points->set_radii_uptodate(true);
}

QMenu* Scene_points_with_normal_item::contextMenu()
{
    const char* prop_name = "Menu modified by Scene_points_with_normal_item.";

    QMenu* menu = Scene_item::contextMenu();

    // Use dynamic properties:
    // http://doc.qt.io/qt-5/qobject.html#property
    bool menuChanged = menu->property(prop_name).toBool();

    if(!menuChanged) {
        actionDeleteSelection = menu->addAction(tr("Delete Selection"));
        actionDeleteSelection->setObjectName("actionDeleteSelection");
        connect(actionDeleteSelection, SIGNAL(triggered()),this, SLOT(deleteSelection()));

        actionResetSelection = menu->addAction(tr("Reset Selection"));
        actionResetSelection->setObjectName("actionResetSelection");
        connect(actionResetSelection, SIGNAL(triggered()),this, SLOT(resetSelection()));

        actionSelectDuplicatedPoints = menu->addAction(tr("Select duplicated points"));
        actionSelectDuplicatedPoints->setObjectName("actionSelectDuplicatedPoints");
        connect(actionSelectDuplicatedPoints, SIGNAL(triggered()),this, SLOT(selectDuplicates()));

        menu->setProperty(prop_name, true);
    }

    if (isSelectionEmpty())
    {
        actionDeleteSelection->setDisabled(true);
        actionResetSelection->setDisabled(true);
    }
    else
    {
        actionDeleteSelection->setDisabled(false);
        actionResetSelection->setDisabled(false);
    }

    return menu;
}

void Scene_points_with_normal_item::setRenderingMode(RenderingMode m)
{
    Scene_item::setRenderingMode(m);
    if (rendering_mode==Splatting && (!m_points->are_radii_uptodate()))
    {
        computes_local_spacing(6); // default value = small
    }
}

bool Scene_points_with_normal_item::has_normals() const { return m_has_normals; }

void Scene_points_with_normal_item::set_has_normals(bool b) {
  if (b!=m_has_normals){
    m_has_normals=b;
    //reset the context menu
    delete this->defaultContextMenu;
    this->defaultContextMenu = 0;
  }
}

void Scene_points_with_normal_item::invalidateOpenGLBuffers()
{
    are_buffers_filled = false;
    compute_bbox();
}

max_stars_repo_name: hlzz/dotfiles

max_issues_repo_name: hlzz/dotfiles

max_forks_repo_name: hlzz/dotfiles


text:
#ifndef _IOEvent_HTTP_SERVER_H
#define _IOEvent_HTTP_SERVER_H

#include <boost/asio/basic_socket_acceptor.hpp>
#include <boost/asio/basic_stream_socket.hpp>
#include <boost/asio/io_context.hpp>
#include <boost/noncopyable.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <glog/logging.h>
#include <functional>
#include "StrandStream.h"
#include "Traits.hpp"
#include <string>
#include <atomic>
#include "HttpSession.hpp"
#include "BasicRouter.hpp"
#include "ChainRouter.hpp"

#define HTTP_SERVER_DECLARE \
    template <typename> class OnAccept,\
	template <typename> class OnError,\
	template <typename> class Endpoint,\
	typename Protocol,\
	typename Acceptor,\
	typename Socket

#define HTTP_SERVER_ATTRIBUTES \
    OnAccept, OnError, Endpoint, Protocol, Acceptor, Socket

namespace IOEvent
{
template
<
    template <typename> class OnAction = std::function,
	template <typename> class OnError = std::function,
	template <typename> class Endpoint = boost::asio::ip::basic_endpoint,
	typename Protocol = boost::asio::ip::tcp,
	typename Acceptor = boost::asio::basic_socket_acceptor<Protocol>,
	typename Socket = boost::asio::basic_stream_socket<Protocol>
>
class HttpServer final
	: public StrandStream,
	boost::noncopyable
{
    using HttpSessionMap = std::map<std::string, _Default::http_session>;
public:
    using self_type = HttpServer;
    using acceptor_type = Acceptor;
    using protocol_type = Protocol;
    using socket_type = Socket;
    using io_context = boost::asio::io_context;
    using asio_executor = typename socket_type::executor_type;
    using endpoint_type = Endpoint<protocol_type>;
    using on_action_type = OnAction<void(const socket_type&)>;
    using on_error_type = OnError<void(const boost::system::error_code&, std::string_view)>;
    using session_type = _Default::http_session;
    using basic_router_type = Http::BasicRouter<session_type>;
    using chain_router_type = Http::ChainRouter<session_type>;
public:
    template <typename _OnAction>
    explicit HttpServer(io_context& loop,
        _OnAction&& on_action,
        const std::string& _name = "HttpServer",
        typename std::enable_if<TryInvoke<_OnAction, void(const socket_type&)>::value, int>::type = 0)
        :StrandStream{ loop.get_executor()},
		loop_{ loop },
        acceptor_{ loop_ },
        onActionCallback_{ std::forward<_OnAction>(on_action) },
        name_{ _name },
		start_{false},
		nextConnectionId_{ 1 },
        basicRouter_{ std::regex::ECMAScript },
        chainRouter_{ std::regex::ECMAScript }
	{}

    template <typename _OnAction, typename _OnError>
    explicit HttpServer(io_context& loop,
        _OnAction&& on_action,
        _OnError&& on_error,
        const std::string& _name = "HttpServer",
        typename std::enable_if<TryInvoke<_OnAction, void(socket_type)>::value
        && TryInvoke<_OnError, void(const boost::system::error_code&, std::string_view)>::value, int>::type = 0)
        :StrandStream{ loop.get_executor() },
		loop_{ loop },
        acceptor_{ loop_ },
        onActionCallback_{ std::forward<_OnAction>(on_action) },
        onErrorCallback_{ std::forward<_OnError>(on_error) },
        name_{ _name },
        start_{ false },
        nextConnectionId_{ 1 },
        basicRouter_{ std::regex::ECMAScript },
		chainRouter_{ std::regex::ECMAScript }
    {}
    void start(const endpoint_type& endpoint);

    basic_router_type& basicRouter() { return basicRouter_; }
    chain_router_type& chainRouter() { return chainRouter_; }

    ~HttpServer() { LOG(ERROR) << "~HttpServer()"; }
private:
    const std::string& name() const { return name_; }
    void loop(const endpoint_type& endpoint);
    void doAccept();
    void onAccept(socket_type&& socket);
private:
    io_context &loop_;
    uint32_t nextConnectionId_;
    acceptor_type acceptor_;
    endpoint_type endpoint_;
    on_action_type onActionCallback_;
    on_error_type onErrorCallback_;
    const std::string name_;
    std::atomic<bool> start_;
    HttpSessionMap connection_;
    basic_router_type basicRouter_;
    chain_router_type chainRouter_;
};

template<HTTP_SERVER_DECLARE>
void HttpServer<HTTP_SERVER_ATTRIBUTES>::start(const endpoint_type& endpoint)
{
    if (!start_)
    {
        start_ = true;
        loop(endpoint);
    }
}

template<HTTP_SERVER_DECLARE>
void HttpServer<HTTP_SERVER_ATTRIBUTES>::loop(const endpoint_type& endpoint)
{
    auto error = boost::system::error_code{};
    acceptor_.open(endpoint.protocol(), error);
    if (error)
    {
        if (onErrorCallback_) onErrorCallback_(error, "acceptor open error");
        return;
    }

    acceptor_.set_option(boost::asio::socket_base::reuse_address(true), error);
    if (error)
    {
        if (onErrorCallback_) onErrorCallback_(error, "acceptor set_option error");
        return;
    }

    acceptor_.bind(endpoint, error);
    if (error)
    {
        if (onErrorCallback_) onErrorCallback_(error, "acceptor bind error");
        return;
    }

    acceptor_.listen(boost::asio::socket_base::max_listen_connections, error);
    if (error)
    {
        if (onErrorCallback_) onErrorCallback_(error, "acceptor listen error");
        return;
    }

    endpoint_ = endpoint;
    doAccept();
}

template <HTTP_SERVER_DECLARE>
void HttpServer<HTTP_SERVER_ATTRIBUTES>::doAccept()
{
    acceptor_.async_accept([&](const boost::system::error_code& error, socket_type&& socket)
    {
        boost::asio::post(static_cast<StrandStream&>(*this).get_inner_executor(), std::bind([&](const boost::system::error_code& ec, socket_type& sock)
        {
            if (ec)
            {
                if (onErrorCallback_) onErrorCallback_(ec, "accept/do_loop");
                return;
            }

            if (onActionCallback_) onActionCallback_(sock);

            onAccept(std::move(sock));
        }, error, std::move(socket)));

        doAccept();
    });
}

template <HTTP_SERVER_DECLARE>
void HttpServer<HTTP_SERVER_ATTRIBUTES>::onAccept(socket_type&& socket)
{
    LOG(INFO) << socket.remote_endpoint().address().to_string() << ":" << std::to_string(endpoint_.port()) << " connected!";
    _Default::http_session::recv(std::move(socket), basicRouter_, onErrorCallback_);
}

namespace _Default
{
using http_server_type = HttpServer<>;
}

}

#endif // !_IOEvent_HTTP_SERVER_H

ext: hpp

max_stars_repo_name: Txhua/IOLoop

max_issues_repo_name: Txhua/IOLoop

max_forks_repo_name: Txhua/IOLoop


text:
// shared_from_test.cpp
//
// Copyright 2019 Peter Dimov
//
// Distributed under the Boost Software License, Version 1.0.
// http://www.boost.org/LICENSE_1_0.txt)

#include <boost/smart_ptr/enable_shared_from.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/core/lightweight_test.hpp>

//

class X
{
private:

    int m_;

public:

    X(): m_() {}
};

class Y: public boost::enable_shared_from
{
};

class Z: public X, public Y
{
public:

    boost::shared_ptr<Z> shared_from_this()
    {
        return boost::shared_from( this );
    }
};

void null_deleter( void const* )
{
}

int main()
{
    boost::shared_ptr<Z> p( new Z );

    try
    {
        boost::shared_ptr<Z> q = p->shared_from_this();

        BOOST_TEST_EQ( p, q );
        BOOST_TEST( !( p < q ) && !( q < p ) );
    }
    catch( boost::bad_weak_ptr const & )
    {
        BOOST_ERROR( "p->shared_from_this() failed" );
    }

    Z v2( *p );

    try
    {
        boost::shared_ptr<Z> q = v2.shared_from_this();
        BOOST_ERROR( "v2.shared_from_this() failed to throw" );
    }
    catch( boost::bad_weak_ptr const & )
    {
    }

    *p = Z();

    try
    {
        boost::shared_ptr<Z> q = p->shared_from_this();

        BOOST_TEST_EQ( p, q );
        BOOST_TEST( !( p < q ) && !( q < p ) );
    }
    catch( boost::bad_weak_ptr const & )
    {
        BOOST_ERROR( "p->shared_from_this() threw bad_weak_ptr after *p = Z()" );
    }

    {
        boost::shared_ptr<Z> p2( p.get(), null_deleter );
    }

    try
    {
        boost::shared_ptr<Z> q = p->shared_from_this();

        BOOST_TEST_EQ( p, q );
        BOOST_TEST( !( p < q ) && !( q < p ) );
    }
    catch( boost::bad_weak_ptr const& )
    {
        BOOST_ERROR( "p->shared_from_this() failed" );
    }

    return boost::report_errors();
}

ext: cpp


text:
#include "problemes.h"
#include "arithmetique.h"

#include <fstream>

#include <boost/range/adaptor/reversed.hpp>
#include <boost/math/constants/constants.hpp>

typedef unsigned long long nombre;
typedef std::vector<nombre> vecteur;

namespace {
    const long double epsilon = 1e-9L;

    struct comparedouble {
        bool operator()(const long double &lhs, const long double &rhs) const {
            return std::abs(lhs - rhs) < epsilon ? false : lhs < rhs;
        }
    };
}

ENREGISTRER_PROBLEME(177, "Integer angled Quadrilaterals") {
    // Let ABCD be a convex quadrilateral, with diagonals AC and BD. At each vertex the diagonal makes an angle with
    // each of the two sides, creating eight corner angles.
    //
    // For example, at vertex A, the two angles are CAD, CAB.
    //
    // We call such a quadrilateral for which all eight corner angles have integer values when measured in degrees an
    // "integer angled quadrilateral". An example of an integer angled quadrilateral is a square, where all eight corner
    // angles are 45°. Another example is given by DAC = 20°, BAC = 60°, ABD = 50°, CBD = 30°, BCA = 40°, DCA = 30°,
    // CDB = 80°, ADB = 50°.
    //
    // What is the total number of non-similar integer angled quadrilaterals?
    //
    // Note: In your calculations you may assume that a calculated angle is integral if it is within a tolerance of 10-9
    // of an integer value.
    std::vector<long double> sinus(180, 0.0L);
    std::vector<long double> cosinus(180, 0.0L);
    std::vector<long double> rad(180, 0.0L);
    std::vector<bool> prevalue(10000 + 1, false);

    std::vector<nombre> solution(8 + 1, 0);

    std::set<long double, comparedouble> fs;
    for (nombre i = 1; i < 180; i++) {
        rad[i] = static_cast<long double>(i) * M_PIl / 180.0L;
        sinus[i] = std::sin(rad[i]);
        cosinus[i] = std::cos(rad[i]);
        auto j = static_cast<nombre>(sinus[i] * 10000);
        prevalue[j] = true;
        fs.insert(sinus[i]);
    }
    prevalue[10000] = true; // sin90
    prevalue[10000 - 1] = true; // sin90
    prevalue[5000] = true; // sin30
    prevalue[5000 - 1] = true; //sin30

    for (nombre a = 1; a <= 45; a++)
        for (nombre b = a; a + b < 180 - 1; b++)
            for (nombre c = 1; a + b + c < 180; c++) {
                nombre d = 180 - a - b - c;
                for (nombre e = 1; e < b + d; e++) {
                    nombre f = b + d - e;
                    long double m = (sinus[b] * sinus[c] * sinus[f]) / (sinus[a] * sinus[e] * sinus[d]);
                    long double n = cosinus[a + c];
                    long double siny = std::sqrt((1 - n * n) / (m * m + 2 * m * n + 1));
                    auto j = static_cast<nombre>(siny * 10000);
                    if (!prevalue[j]) continue;
                    if (fs.find(siny) != fs.end()) {
                        if (siny > 1) siny = 1;

                        auto y = static_cast<nombre>(std::asin(siny) * 180 / M_PIl + 0.01L);
                        long double sinx = m * siny;
                        long double xangle = (std::abs(sinx - 1) < epsilon) ? 90 : std::asin(sinx) * 180 / M_PIl;
                        auto x = static_cast<nombre>(xangle + 0.01L);
                        if (xangle < x + epsilon && xangle > x - epsilon) {
                            x = (180 - x + y == a + c) ? 180 - x : x;
                            y = (180 + x - y == a + c) ? 180 - y : y;

                            std::vector<vecteur> quadrilateres
                                    {
                                            {a, b, d, y, x, f, e, c},
                                            {d, y, x, f, e, c, a, b},
                                            {x, f, e, c, a, b, d, y},
                                            {e, c, a, b, d, y, x, f},
                                            {b, a, c, e, f, x, y, d},
                                            {c, e, f, x, y, d, b, a},
                                            {f, x, y, d, b, a, c, e},
                                            {y, d, b, a, c, e, f, x}
                                    };

                            std::set<vecteur> s;
                            for (auto quadrilatere: quadrilateres) {
                                if (quadrilatere.front() <= quadrilatere.at(1) && quadrilatere.front() <= 45)
                                    s.insert(quadrilatere);
                            }

                            solution[s.size()]++;
                        }
                    }
                }
            }

    nombre resultat = 0;
    for (nombre i = 1; i <= 8; i++)
        resultat += solution[i] / i;

    return std::to_string(resultat);
}

max_stars_repo_name: ZongoForSpeed/ProjectEuler

max_issues_repo_name: ZongoForSpeed/ProjectEuler

max_forks_repo_name: ZongoForSpeed/ProjectEuler


text:
#pragma once

#include <roerei/performance.hpp>
#include <roerei/ml/ml_type.hpp>
#include <roerei/ml/posetcons_type.hpp>

#include <boost/fusion/include/adapt_struct.hpp>

namespace roerei
{

struct knn_params_t
{
  size_t k;

  bool operator==(knn_params_t const rhs) const
  {
    return k == rhs.k;
  }

  bool operator<(knn_params_t const rhs) const
  {
    return k < rhs.k;
  }
};

struct nb_params_t
{
  float pi, sigma, tau;

  bool operator==(nb_params_t const rhs) const
  {
    return std::tie(pi, sigma, tau) == std::tie(rhs.pi, rhs.sigma, rhs.tau);
  }

  bool operator<(nb_params_t const rhs) const
  {
    return std::tie(pi, sigma, tau) < std::tie(rhs.pi, rhs.sigma, rhs.tau);
  }
};

struct adarank_params_t
{
	size_t T;

  bool operator==(adarank_params_t const rhs) const
  {
    return T == rhs.T;
  }

	bool operator<(adarank_params_t const rhs) const
	{
	  return T < rhs.T;
	}
};

struct cv_result_v1_t
{
  std::string corpus;
  posetcons_type strat;
  ml_type ml;
  boost::optional<knn_params_t> knn_params;
  boost::optional<nb_params_t> nb_params;
  boost::optional<adarank_params_t> adarank_params;
  size_t n, k;
  performance::metrics_t metrics;
};

struct cv_result_v2_t
{
  std::string corpus;
  bool prior;
  posetcons_type strat;
  ml_type ml;
  boost::optional<knn_params_t> knn_params;
  boost::optional<nb_params_t> nb_params;
  boost::optional<adarank_params_t> adarank_params;
  size_t n, k;
  performance::metrics_t metrics;
};

typedef cv_result_v2_t cv_result_t;

inline bool operator==(cv_result_t const& lhs, cv_result_t const& rhs)
{
  return
    std::tie(lhs.corpus, lhs.prior, lhs.strat, lhs.ml, lhs.knn_params, lhs.nb_params, lhs.adarank_params, lhs.n, lhs.k, lhs.metrics) ==
    std::tie(rhs.corpus, rhs.prior, rhs.strat, rhs.ml, rhs.knn_params, rhs.nb_params, rhs.adarank_params, rhs.n, rhs.k, rhs.metrics);
}

inline bool result_same_base(cv_result_t const& lhs, cv_result_t const& rhs) {
  return
  std::tie(lhs.corpus, lhs.prior, lhs.strat, lhs.ml, lhs.knn_params, lhs.nb_params, lhs.adarank_params, lhs.n, lhs.k) ==
  std::tie(rhs.corpus, rhs.prior, rhs.strat, rhs.ml, rhs.knn_params, rhs.nb_params, rhs.adarank_params, rhs.n, rhs.k);
}

inline std::ostream& operator<<(std::ostream& os, cv_result_t const& rhs)
{
  os << rhs.corpus;
  if (!rhs.prior) {
    os << " (without prior)";
  }

  os << ": [" << rhs.strat << "] " << rhs.ml << " ";
  switch(rhs.ml)
  {
  case ml_type::knn:
    os << "K=" << rhs.knn_params->k << " ";
    break;
  case ml_type::knn_adaptive:
  case ml_type::omniscient:
  case ml_type::ensemble:
	break;
  case ml_type::adarank:
	os << "T=" << rhs.adarank_params->T;
    break;
  case ml_type::naive_bayes:
    os << rhs.nb_params->pi << " " << rhs.nb_params->sigma << " " << rhs.nb_params->tau << " ";
    break;
  }
  return os << " " << rhs.metrics;
}

}

BOOST_FUSION_ADAPT_STRUCT(
    roerei::knn_params_t,
    (size_t, k)
)

BOOST_FUSION_ADAPT_STRUCT(
    roerei::nb_params_t,
    (float, pi)
    (float, sigma)
    (float, tau)
)

BOOST_FUSION_ADAPT_STRUCT(
	roerei::adarank_params_t,
	(size_t, T)
)

BOOST_FUSION_ADAPT_STRUCT(
  roerei::cv_result_v1_t,
  (std::string, corpus)
  (roerei::posetcons_type, strat)
  (roerei::ml_type, ml)
  (boost::optional<roerei::knn_params_t>, knn_params)
  (boost::optional<roerei::nb_params_t>, nb_params)
  (boost::optional<roerei::adarank_params_t>, adarank_params)
  (size_t, n)
  (size_t, k)
  (roerei::performance::metrics_t, metrics)
)

BOOST_FUSION_ADAPT_STRUCT(
  roerei::cv_result_t,
  (std::string, corpus)
  (bool, prior)
  (roerei::posetcons_type, strat)
  (roerei::ml_type, ml)
  (boost::optional<roerei::knn_params_t>, knn_params)
  (boost::optional<roerei::nb_params_t>, nb_params)
  (boost::optional<roerei::adarank_params_t>, adarank_params)
  (size_t, n)
  (size_t, k)
  (roerei::performance::metrics_t, metrics)
)

max_stars_repo_name: Wassasin/roerei

max_issues_repo_name: Wassasin/roerei

max_forks_repo_name: Wassasin/roerei


text:
//=======================================================================
// Copyright 2002 Indiana University.
// Authors: Andrew Lumsdaine, Lie-Quan Lee, Jeremy G. Siek
//
// 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/concept_archetype.hpp>
#include <boost/graph/depth_first_search.hpp>
#include <boost/graph/graph_archetypes.hpp>

int main()
{
  using namespace boost;
  typedef default_constructible_archetype<
    sgi_assignable_archetype<
    equality_comparable_archetype<> > > vertex_t;
  {
    typedef incidence_graph_archetype<vertex_t, directed_tag,
      allow_parallel_edge_tag> IncidenceGraph;
    typedef vertex_list_graph_archetype<vertex_t, directed_tag,
      allow_parallel_edge_tag, IncidenceGraph> graph_t;
    graph_t& g = static_object<graph_t>::get();
    read_write_property_map_archetype<vertex_t, color_value_archetype> color;
    depth_first_search(g, color_map(color));
  }
  {
    typedef incidence_graph_archetype<vertex_t, directed_tag,
      allow_parallel_edge_tag> IncidenceGraph;
    typedef vertex_list_graph_archetype<vertex_t, directed_tag,
      allow_parallel_edge_tag, IncidenceGraph> graph_t;
    graph_t& g = static_object<graph_t>::get();
    readable_property_map_archetype<vertex_t, std::size_t> v_index;
    depth_first_search(g, vertex_index_map(v_index));
  }
  {
    typedef incidence_graph_archetype<vertex_t, undirected_tag,
      allow_parallel_edge_tag> IncidenceGraph;
    typedef vertex_list_graph_archetype<vertex_t, undirected_tag,
      allow_parallel_edge_tag, IncidenceGraph> Graph;
    typedef property_graph_archetype<Graph, vertex_index_t, std::size_t>
      graph_t;
    graph_t& g = static_object<graph_t>::get();
    dfs_visitor<> v;
    depth_first_search(g, visitor(v));
  }
  return 0;
}

max_stars_repo_name: randolphwong/mcsema

max_issues_repo_name: randolphwong/mcsema

max_forks_repo_name: randolphwong/mcsema


text:
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
 * Copyright (c) 2011-2015  Regents of the University of California.
 *
 * This file is part of ndnSIM. See AUTHORS for complete list of ndnSIM authors and
 * contributors.
 *
 * ndnSIM is free software: you can redistribute it and/or modify it under the terms
 * of the GNU General Public License as published by the Free Software Foundation,
 * either version 3 of the License, or (at your option) any later version.
 *
 * ndnSIM is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
 * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
 * PURPOSE.  See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * ndnSIM, e.g., in COPYING.md file.  If not, see <http://www.gnu.org/licenses/>.
 **/

#ifndef MULTI_TYPE_CONTAINER_H_
#define MULTI_TYPE_CONTAINER_H_

/// @cond include_hidden

#include <boost/mpl/inherit_linearly.hpp>
#include <boost/mpl/inherit.hpp>
#include <boost/mpl/at.hpp>

namespace ns3 {
namespace ndn {
namespace ndnSIM {
namespace detail {

template<class T>
struct wrap {
  T value_;
};

template<class Vector>
struct multi_type_container
  : public boost::mpl::inherit_linearly<Vector, boost::mpl::inherit<wrap<boost::mpl::_2>,
                                                                    boost::mpl::_1>>::type {
  template<int N>
  struct index {
    typedef typename boost::mpl::at_c<Vector, N>::type type;
  };

  template<class T>
  T&
  get()
  {
    return static_cast<wrap<T>&>(*this).value_;
  }

  template<class T>
  const T&
  get() const
  {
    return static_cast<const wrap<T>&>(*this).value_;
  }

  template<int N>
  typename boost::mpl::at_c<Vector, N>::type&
  get()
  {
    typedef typename boost::mpl::at_c<Vector, N>::type T;
    return static_cast<wrap<T>&>(*this).value_;
  }

  template<int N>
  const typename boost::mpl::at_c<Vector, N>::type&
  get() const
  {
    typedef typename boost::mpl::at_c<Vector, N>::type T;
    return static_cast<const wrap<T>&>(*this).value_;
  }
};

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

/// @cond include_hidden

#endif // MULTI_TYPE_CONTAINER_H_

max_stars_repo_name: seanbraley/ndn-split-caching

max_issues_repo_name: seanbraley/ndn-split-caching

max_forks_repo_name: seanbraley/ndn-split-caching


text:
#include "Util.h"

#include "platform.h"
#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/split.hpp>
#include <boost/filesystem/operations.hpp>

namespace fs = boost::filesystem;

std::string strToUpper(const char* from)
{
	std::string str(from);
	for(unsigned int i = 0; i < str.size(); i++)
		str[i] = (char)toupper(from[i]);
	return str;
}

std::string& strToUpper(std::string& str)
{
	for(unsigned int i = 0; i < str.size(); i++)
		str[i] = (char)toupper(str[i]);

	return str;
}

std::string strToUpper(const std::string& str)
{
	return strToUpper(str.c_str());
}

// embedded resources, e.g. ":/font.ttf", need to be properly handled too
std::string getCanonicalPath(const std::string& path)
{
	if(path.empty() || !boost::filesystem::exists(path))
		return path;

	return boost::filesystem::canonical(path).generic_string();
}

// expands "./my/path.sfc" to "[relativeTo]/my/path.sfc"
// if allowHome is true, also expands "~/my/path.sfc" to "/home/pi/my/path.sfc"
fs::path resolvePath(const fs::path& path, const fs::path& relativeTo, bool allowHome)
{
	// nothing here
	if(path.begin() == path.end())
		return path;

	if(*path.begin() == ".")
	{
		fs::path ret = relativeTo;
		for(auto it = ++path.begin(); it != path.end(); ++it)
			ret /= *it;
		return ret;
	}

	if(allowHome && *path.begin() == "~")
	{
		fs::path ret = getHomePath();
		for(auto it = ++path.begin(); it != path.end(); ++it)
			ret /= *it;
		return ret;
	}

	return path;
}

fs::path removeCommonPathUsingStrings(const fs::path& path, const fs::path& relativeTo, bool& contains)
{
#ifdef WIN32
	std::wstring pathStr = path.c_str();
	std::wstring relativeToStr = relativeTo.c_str();
#else
	std::string pathStr = path.c_str();
	std::string relativeToStr = relativeTo.c_str();
#endif
	if (pathStr.find_first_of(relativeToStr) == 0) {
		contains = true;
		return pathStr.substr(relativeToStr.size() + 1);
	}
	else {
		contains = false;
		return path;
	}
}

// example: removeCommonPath("/home/pi/roms/nes/foo/bar.nes", "/home/pi/roms/nes/") returns "foo/bar.nes"
fs::path removeCommonPath(const fs::path& path, const fs::path& relativeTo, bool& contains)
{
	// if either of these doesn't exist, fs::canonical() is going to throw an error
	if(!fs::exists(path) || !fs::exists(relativeTo))
	{
		contains = false;
		return path;
	}

	// if it's a symlink we don't want to apply fs::canonical on it, otherwise we'll lose the current parent_path
	fs::path p = (fs::is_symlink(path) ? fs::canonical(path.parent_path()) / path.filename() : fs::canonical(path));
	fs::path r = fs::canonical(relativeTo);

	if(p.root_path() != r.root_path())
	{
		contains = false;
		return p;
	}

	fs::path result;

	// find point of divergence
	auto itr_path = p.begin();
	auto itr_relative_to = r.begin();
	while(*itr_path == *itr_relative_to && itr_path != p.end() && itr_relative_to != r.end())
	{
		++itr_path;
		++itr_relative_to;
	}

	if(itr_relative_to != r.end())
	{
		contains = false;
		return p;
	}

	while(itr_path != p.end())
	{
		if(*itr_path != fs::path("."))
			result = result / *itr_path;

		++itr_path;
	}

	contains = true;
	return result;
}

// usage: makeRelativePath("/path/to/my/thing.sfc", "/path/to") -> "./my/thing.sfc"
// usage: makeRelativePath("/home/pi/my/thing.sfc", "/path/to", true) -> "~/my/thing.sfc"
fs::path makeRelativePath(const fs::path& path, const fs::path& relativeTo, bool allowHome)
{
	bool contains = false;

	fs::path ret = removeCommonPath(path, relativeTo, contains);
	if(contains)
	{
		// success
		ret = "." / ret;
		return ret;
	}

	if(allowHome)
	{
		contains = false;
		std::string homePath = getHomePath();
		ret = removeCommonPath(path, homePath, contains);
		if(contains)
		{
			// success
			ret = "~" / ret;
			return ret;
		}
	}

	// nothing could be resolved
	return path;
}

std::string strreplace(std::string str, const std::string& replace, const std::string& with)
{
	size_t pos;
	while((pos = str.find(replace)) != std::string::npos)
		str = str.replace(pos, replace.length(), with.c_str(), with.length());

	return str;
}

// plaform-specific escape path function
// on windows: just puts the path in quotes
// everything else: assume bash and escape special characters with backslashes
std::string escapePath(const boost::filesystem::path& path)
{
#ifdef WIN32
	// windows escapes stuff by just putting everything in quotes
	return '"' + fs::path(path).make_preferred().string() + '"';
#else
	// a quick and dirty way to insert a backslash before most characters that would mess up a bash path
	std::string pathStr = path.string();

	const char* invalidChars = " '\"\\!$^&*(){}[]?;<>";
	for(unsigned int i = 0; i < pathStr.length(); i++)
	{
		char c;
		unsigned int charNum = 0;
		do {
			c = invalidChars[charNum];
			if(pathStr[i] == c)
			{
				pathStr.insert(i, "\\");
				i++;
				break;
			}
			charNum++;
		} while(c != '\0');
	}

	return pathStr;
#endif
}

std::string removeParenthesis(const std::string& str)
{
	// remove anything in parenthesis or brackets
	// should be roughly equivalent to the regex replace "\((.*)\)|\[(.*)\]" with ""
	// I would love to just use regex, but it's not worth pulling in another boost lib for one function that is used once

	std::string ret = str;
	size_t start, end;

	static const int NUM_TO_REPLACE = 2;
	static const char toReplace[NUM_TO_REPLACE*2] = { '(', ')', '[', ']' };

	bool done = false;
	while(!done)
	{
		done = true;
		for(int i = 0; i < NUM_TO_REPLACE; i++)
		{
			end = ret.find_first_of(toReplace[i*2+1]);
			start = ret.find_last_of(toReplace[i*2], end);

			if(start != std::string::npos && end != std::string::npos)
			{
				ret.erase(start, end - start + 1);
				done = false;
			}
		}
	}

	// also strip whitespace
	end = ret.find_last_not_of(' ');
	if(end != std::string::npos)
		end++;

	ret = ret.substr(0, end);

	return ret;
}

std::vector<std::string> commaStringToVector(std::string commaString)
{
	// from a comma separated string, get a vector of strings
	std::vector<std::string> strs;
	boost::split(strs, commaString, boost::is_any_of(","));
	std::sort(strs.begin(), strs.end());
	return strs;
}

std::string vectorToCommaString(std::vector<std::string> stringVector)
{
	std::string out = "";
	std::sort(stringVector.begin(), stringVector.end());
	// from a vector of system names get comma separated string
	for(std::vector<std::string>::const_iterator it = stringVector.cbegin() ; it != stringVector.cend() ; it++ )
	{
		out = out + (out == "" ? "" : ",") + (*it);
	}
	return out;
}

max_stars_repo_name: Odroid-RetroArena/EmulationStation

max_issues_repo_name: Odroid-RetroArena/EmulationStation

max_forks_repo_name: Odroid-RetroArena/EmulationStation


text:
/**
 * Copyright (c) 2017 Melown Technologies SE
 *
 * 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.
 *
 * 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 COPYRIGHT HOLDER 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.
 */
#ifndef vtslibs_storage_range_hpp_included_
#define vtslibs_storage_range_hpp_included_

#include <limits>
#include <iterator>

#include <boost/iterator/counting_iterator.hpp>
#include <boost/iterator/reverse_iterator.hpp>
#include <boost/range/iterator_range.hpp>

#include "utility/streams.hpp"

#include "lod.hpp"

namespace vtslibs { namespace storage {

//! Helper range class for use on the command line or in configs (e.g., "10,25")
template<typename T>
struct Range
{
    typedef T value_type;
    T min, max;

    Range() : min(), max() {}
    Range(T l) : min(l), max(l) {}
    Range(T min, T max) : min(min), max(max) {}

    template <typename U>
    explicit Range(const Range<U> &r)
        : min(r.min), max(r.max)
    {}

    T size() const { return max - min; }

    bool empty() const { return max < min; }

    typedef boost::counting_iterator<T> iterator;
    typedef iterator const_iterator;

    const_iterator begin() const { return const_iterator(min); }
    const_iterator cbegin() const { return const_iterator(min); }

    const_iterator end() const { return const_iterator(max + 1); }
    const_iterator cend() const { return const_iterator(max + 1); }

    bool operator==(const Range &o) const {
        return (min == o.min) && (max == o.max);
    }

    bool operator!=(const Range &o) const { return !operator==(o); }

    static Range emptyRange() { return { T(1), T(0) }; }
    static Range maxRange() {
        return { std::numeric_limits<T>::lowest()
                , std::numeric_limits<T>::max() };
    }
};

typedef Range<Lod> LodRange;

template<typename T>
inline Range<T> range(const T min, const T max)
{
    return { min, max };
}

template <typename T, typename Q>
inline Q clamp(const Range<T> &range, Q value)
{
    if (value < range.min) { return range.min; }
    if (value > range.max) { return range.max; }
    return value;
}

template<typename T>
inline Range<T> unite(const Range<T> &l, const Range<T> &r)
{
    if (l.empty()) { return r; }
    if (r.empty()) { return l; }
    return { std::min(l.min, r.min), std::max(l.max, r.max) };
}

template<typename T>
inline void update(Range<T> &r, const T &v)
{
    if (r.empty()) { r = { v }; }
    if (v < r.min) { r.min = v; }
    if (v > r.max) { r.max = v; }
}

/** Grow range up/down by given value.
 */
template<typename T>
inline Range<T> operator+(const Range<T> &r, int value)
{
    // empty range has undefined min and max -> cannot grow
    if (r.empty()) { return r; }
    if (!value) { return r; }

    if (value < 0) {
        auto min(std::numeric_limits<T>::min());
        if ((min - value) > r.min) {
            // underflow -> set to type's minimum
            return { min, r.max };
        }
        return { T(r.min + value), r.max };
    }

    auto max(std::numeric_limits<T>::max());
    if ((max - value) > r.max) {
        // overflow -> set to type's minimum
        return { r.min, max };
    }
    return { r.min, T(r.max + value) };
}

/** Grow range up/down by given value.
 */
template<typename T>
inline Range<T> operator-(const Range<T> &r, int value)
{
    return operator+(r, -value);
}

template<typename T>
inline bool in(const T &value, const Range<T> &range)
{
    return (value >= range.min) && (value <= range.max);
}

template<typename CharT, typename Traits, typename RangeT>
inline std::basic_istream<CharT, Traits>&
operator>>(std::basic_istream<CharT, Traits> &is,
           Range<RangeT> &range)
{
    RangeT min, max;
    is >> min >> utility::expect(',') >> max;
    if (!is.fail()) { range.min = min; range.max = max; }
    return is;
}

template <typename E, typename T, typename RangeT>
std::basic_ostream<E, T>&
operator<<(std::basic_ostream<E,T> &os,
           const Range<RangeT> &range)
{
    if (range.empty()) {
        os << "empty";
    } else {
        os << range.min << "," << range.max;
    }
    return os;
}

} } // namesapce vtslibs::storage

#endif // vtslibs_storage_range_hpp_included_

max_stars_repo_name: melowntech/vts-libs

max_issues_repo_name: HanochZhu/vts-browser-unity-plugin

max_forks_repo_name: HanochZhu/vts-browser-unity-plugin


text: #include <boost/fusion/adapted/boost_array/tag_of.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text: #include <boost/spirit/home/x3/auxiliary/eoi.hpp>


text:
#include <iostream>
#include <fstream>
#include <opencv2/opencv.hpp>
#include <boost/filesystem.hpp>
#include <boost/foreach.hpp>
using namespace std;
namespace fs = boost::filesystem;

int CheckAnswer(int &true_count, int &TP, int &TN, int &FP, int &FN, string teacher_dir, string predict_dir, string filename)
{
	cv::Mat p = imread(predict_dir + filename,cv::IMREAD_GRAYSCALE);
	cv::Mat t = imread(teacher_dir + filename,cv::IMREAD_GRAYSCALE);
	if(p.empty() || t.empty())
	{
		return 1;
	}
	for(int x=0; x<p.cols; x++)
	{
		for(int y=0; y<p.rows; y++)
		{
			bool P = p.at<unsigned char>(y,x) > 0;
			bool T = t.at<unsigned char>(y,x) > 0;
			if(P)
				true_count++;
			if(P && T)
				TP++;
			else if(!T && P)
				FP++;
			else if(T && !P)
				FN++;
			else
				TN++;
		}
	}
	return 0;
}

int main(int argc, char **argv)
{
	ofstream ofs("output.csv");
	int filecount = 0;
	int true_count = 0;
	int TP=0;
	int TN=0;
	int FP=0;
	int FN=0;
	const fs::path teacher_dir(argv[1]);
	const fs::path predict_dir(argv[2]);
	BOOST_FOREACH(const fs::path& p, std::make_pair(fs::directory_iterator(teacher_dir),fs::directory_iterator()))
	{
		if (!fs::is_directory(p))
		{
			fs::path extension = p.extension();
			if(extension.generic_string() == ".png")
			{
				if(!CheckAnswer(true_count,TP,TN,FP,FN, teacher_dir.c_str(), predict_dir.c_str(), p.filename().c_str()))
				{
					cout << p.filename() << endl;
					filecount++;
				}
			}
		}
	}
	//int pixels = filecount * 320 * 240;
	ofs << filecount << "," << true_count<< ","<< TP << "," << TN << "," << FP << "," << FN << endl;
	ofs.close();
	return 0;
}

max_stars_repo_name: yotaseki/caffe-FCNNs

max_issues_repo_name: yotaseki/caffe-FCNNs

max_forks_repo_name: yotaseki/caffe-FCNNs


text:
#include <stdint.h>
#include <boost/python/numpy.hpp>

namespace scitbx { namespace af { namespace boost_python {

#define SCITBX_LOC(pyname, ElementType) \
  boost::python::object \
  flex_##pyname##_as_numpy_array( \
    ref<ElementType, flex_grid<> > const& O, \
    bool optional=false); \
 \
  versa<ElementType, flex_grid<> >* \
  flex_##pyname##_from_numpy_array( \
    boost::python::numpy::ndarray const& arr_obj);

  SCITBX_LOC(bool, bool)
  SCITBX_LOC(int, int)
  SCITBX_LOC(long, long)
  SCITBX_LOC(float, float)
  SCITBX_LOC(double, double)
#define SCITBX_LOC2 std::complex<double>
  SCITBX_LOC(complex_double, SCITBX_LOC2)
#undef SCITBX_LOC2
  SCITBX_LOC(size_t, std::size_t)
  SCITBX_LOC(int8, int8_t)
  SCITBX_LOC(int16, int16_t)
  // SCITBX_LOC(int32, int32_t)
  #if defined(_MSC_VER)
  SCITBX_LOC(int64, int64_t)
  #endif
  SCITBX_LOC(uint8, uint8_t)
  SCITBX_LOC(uint16, uint16_t)
  SCITBX_LOC(uint32, uint32_t)
  // SCITBX_LOC(uint64, uint64_t)
#undef SCITBX_LOC

}}} // namespace scitbx::af::boost_python


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

// Copyright (c) 2011-2012 Barend Gehrels, Amsterdam, the Netherlands.

// This file was modified by Oracle on 2015.
// Modifications copyright (c) 2015 Oracle and/or its affiliates.

// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle

// Use, modification and distribution is subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

//[relation
//` Shows how to calculate the spatial relation between a point and a polygon

#include <iostream>
#include <string>

#include <boost/geometry.hpp>
#include <boost/geometry/geometries/point_xy.hpp>
#include <boost/geometry/geometries/polygon.hpp>
/*<-*/ #include "create_svg_two.hpp" /*->*/

int main()
{
    typedef boost::geometry::model::d2::point_xy<double> point_type;
    typedef boost::geometry::model::polygon<point_type> polygon_type;

    polygon_type poly;
    boost::geometry::read_wkt(
        "POLYGON((2 1.3,2.4 1.7,2.8 1.8,3.4 1.2,3.7 1.6,3.4 2,4.1 3,5.3 2.6,5.4 1.2,4.9 0.8,2.9 0.7,2 1.3)"
            "(4.0 2.0, 4.2 1.4, 4.8 1.9, 4.4 2.2, 4.0 2.0))", poly);

    point_type p(4, 1);

    boost::geometry::de9im::matrix matrix = boost::geometry::relation(p, poly);
    std::string code = matrix.str();

    std::cout << "relation: " << code << std::endl;
    /*<-*/ create_svg("relation.svg", poly, p); /*->*/
    return 0;
}

//]

//[relation_output
/*`
Output:
[pre
relation: 0FFFFF212

[$img/algorithms/within.png]
]

*/
//]


text:
/*
 * Copyright (c), Pierre-Anthony Lemieux (pal@palemieux.com)
 * 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.
 *
 * 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 COPYRIGHT HOLDER 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 <KM_fileio.h>
#include <KM_prng.h>
#include <AS_02.h>
#include <Metadata.h>
#include <assert.h>
#include <boost/program_options.hpp>
#include <boost/algorithm/string.hpp>
#include <stdexcept>
#include <iostream>
#include <string>
#include <map>
#include <iomanip>
#include <fstream>

#ifdef WIN32
#include <io.h>
#include <fcntl.h>
#else
#include <stdio.h>
#endif

/* enumeration of supported input formats */

enum class OutputFormats {
    J2C,
    MJC
};

std::istream& operator>>(std::istream& is, OutputFormats& f) {

    std::string s;

    is >> s;

    if (s == "J2C") {
        f = OutputFormats::J2C;
    } else if (s == "MJC") {
        f = OutputFormats::MJC;
    } else {
        throw std::runtime_error("Unknown input file format");
    }

    return is;
}

std::ostream& operator<<(std::ostream& os, const OutputFormats& f) {

    switch (f) {
    case OutputFormats::J2C:
        os << "J2C";
        break;
    case OutputFormats::MJC:
        os << "MJC";
        break;
    }

    return os;
}

int main(int argc, const char* argv[]) {

    ASDCP::Result_t result = ASDCP::RESULT_OK;

    /* initialize command line options */

    boost::program_options::options_description cli_opts{ "Unwraps JPEG 2000 codestreams from IMF Image Track Files" };

    cli_opts.add_options()
        ("help", "Prints usage")
        ("format", boost::program_options::value<OutputFormats>()->default_value(OutputFormats::J2C), "Output format\n"
            "  MJC: \t16-byte header followed by a sequence of J2C codestreams, each preceded by a 4-byte little-endian length\n"
            "  J2C: \tindividual JPEG 2000 codestreams")
        ("buffer-size", boost::program_options::value<uint32_t>()->default_value(8192*8192*3*2 /* 8K */), "Read buffer size (8K 4:4:4 16-bit if unspecified)")
        ("out", boost::program_options::value<std::string>(), "Output path (or stdout if none is specified)")
        ("in", boost::program_options::value<std::string>()->required(), "Input MXF file path");

    boost::program_options::variables_map cli_args;

    try {

        boost::program_options::store(boost::program_options::parse_command_line(argc, argv, cli_opts), cli_args);

        boost::program_options::notify(cli_args);

        /* display help options */

        if (cli_args.count("help")) {
            std::cout << cli_opts << "\n";
            return 1;
        }

        /* setup the output */

        const OutputFormats format = cli_args["format"].as<OutputFormats>();

        FILE* mjc_output = NULL;

        switch (format) {

        case OutputFormats::J2C:

            if (cli_args["out"].empty() || (! Kumu::PathIsDirectory(cli_args["out"].as<std::string>()) )) {
                throw std::runtime_error("Output path must be an existing directory when J2C output format is selected.");
            }

            break;

        case OutputFormats::MJC:

            if (cli_args["out"].empty()) {

                /* open stdout in binary mode */

#ifdef WIN32

                int mode = _setmode(_fileno(stdout), O_BINARY);

                if (mode == -1) {
                    throw std::runtime_error("Cannot reopen stdout");
                }
#endif

                mjc_output = stdout;

            } else {

                /* create output file */

                mjc_output = fopen(cli_args["out"].as<std::string>().c_str(), "wb");

                if (!mjc_output) {
                    throw std::runtime_error("Cannot create output file");
                }

            }

            break;

        default:

            throw std::runtime_error("Unknown output format");

        }

        /* open input file */

        AS_02::JP2K::MXFReader reader;

        result = reader.OpenRead(cli_args["in"].as<std::string>());

        if (result.Failure()) {
            throw std::runtime_error("Cannot open input file");
        }

        if (format == OutputFormats::MJC) {

            /* output MJC header */

            ASDCP::MXF::InterchangeObject* obj = 0;

            result = reader.OP1aHeader().GetMDObjectByType(
                reader.OP1aHeader().m_Dict->Type(ASDCP::MDD_RGBAEssenceDescriptor).ul,
                &obj
            );

            uint32_t flags = result.Success() ? 2 /* KDU_SIMPLE_VIDEO_RGB */ : 1 /* KDU_SIMPLE_VIDEO_YCC */;

            ASDCP::Rational edit_rate;

            if (!ASDCP::MXF::GetEditRateFromFP(reader.OP1aHeader(), edit_rate)) {

                throw std::runtime_error("Cannot read edit rate from input file");

            }

            std::array<uint8_t, 16> header = {
                'M',
                'J',
                'C',
                '2',
                (uint8_t) ((edit_rate.Numerator >> 24) & 0xFF),
                (uint8_t) ((edit_rate.Numerator >> 16) & 0xFF),
                (uint8_t) ((edit_rate.Numerator >> 8) & 0xFF),
                (uint8_t) (edit_rate.Numerator & 0xFF),
                (uint8_t) ((edit_rate.Denominator >> 24) & 0xFF),
                (uint8_t) ((edit_rate.Denominator >> 16) & 0xFF),
                (uint8_t) ((edit_rate.Denominator >> 8) & 0xFF),
                (uint8_t) (edit_rate.Denominator & 0xFF),
                (uint8_t) ((flags >> 24) & 0xFF),
                (uint8_t) ((flags >> 16) & 0xFF),
                (uint8_t) ((flags >> 8) & 0xFF),
                (uint8_t) (flags & 0xFF),
            };

            fwrite(header.data(), sizeof(header), 1, mjc_output);

        }

        /* Codestream frame buffer for the MXF writer */

        ASDCP::JP2K::FrameBuffer fb(cli_args["buffer-size"].as<uint32_t>());

        uint32_t frame_count = reader.AS02IndexReader().GetDuration();

        for (uint32_t i = 0; i < frame_count; i++) {

            result = reader.ReadFrame(i, fb);

            if (result.Failure()) {
                throw std::runtime_error("Cannot read frame");
            }

            if (format == OutputFormats::J2C) {

                /* write single J2C */

                std::stringstream ss;

                ss << cli_args["out"].as<std::string>() << "/" << std::setfill('0') << std::setw(6) << i << ".j2c";

                std::ofstream f(ss.str(), std::ios_base::out | std::ios_base::binary);

                if (!f.good()) {
                    throw std::runtime_error("Cannot open output file");
                }

                f.write((const char*) fb.RoData(), fb.Size());

                f.close();

            } else {

                /* write single MJC frame */

                uint32_t csz = KM_i32_BE(fb.Size());

                fwrite(&csz, 4, 1, mjc_output);

                fwrite((const char*)fb.RoData(), 1, fb.Size(), mjc_output);

            }

        }

        /* close reader */

        result = reader.Close();

        if (ASDCP_FAILURE(result)) {
            throw std::runtime_error("Cannot close file");
        }

    } catch (boost::program_options::required_option e) {

        std::cout << cli_opts << std::endl;
        return 1;

    } catch (std::runtime_error e) {

        std::cout << e.what() << std::endl;
        return 1;
    }

    return 0;
}

max_stars_repo_name: sandflow/jid

max_issues_repo_name: sandflow/jid

max_forks_repo_name: sandflow/jid


text: #include <boost/algorithm/cxx11/none_of.hpp>


text:
#include <gtest/gtest.h>
#include <vector>
#include <Eigen/Dense>

#include "opw_kinematics/opw_kinematics.h"
#include "opw_kinematics/opw_parameters_examples.h"
#include "opw_kinematics/opw_utilities.h"

const double TOLERANCE = 1e-5; // absolute tolerance for EXPECT_NEAR checks

using opw_kinematics::Transform;

/** @brief Compare every element of two eigen Isometry3 poses.
 */
template <typename T>
void comparePoses(const Transform<T> & Ta, const Transform<T> & Tb)
{
  using Matrix = Eigen::Matrix<T, 3, 3>;
  using Vector = Eigen::Matrix<T, 3, 1>;

  Matrix Ra = Ta.rotation(), Rb = Tb.rotation();
  for (int i = 0; i < Ra.rows(); ++i)
  {
    for (int j = 0; j < Ra.cols(); ++j)
    {
      EXPECT_NEAR(Ra(i, j), Rb(i, j), TOLERANCE);
    }
  }

  Vector pa = Ta.translation(), pb = Tb.translation();
  EXPECT_NEAR(pa[0], pb[0], TOLERANCE);
  EXPECT_NEAR(pa[1], pb[1], TOLERANCE);
  EXPECT_NEAR(pa[2], pb[2], TOLERANCE);
}

TEST(kuka_kr6, forward_kinematics)
{
  const auto kuka = opw_kinematics::makeKukaKR6_R700_sixx<float>();

  std::vector<float> joint_values = {0.2f, 0.2f, 0.2f, 0.2f, 0.2f, 0.2f};
  Transform<float> forward_pose = opw_kinematics::forward(kuka, &joint_values[0]);

  // Compare with copied results from forward kinematics using MoveIt!
  Transform<float> actual_pose;
  actual_pose.matrix()  << -0.5965795, 0.000371195,   0.8025539, 0,
     -0.2724458,   0.9405218,   -0.202958, 0,
     -0.7548948,  -0.3397331,  -0.5609949, 0,
      0        ,   0        ,   0        , 1;
  actual_pose.translation() << 0.7341169, -0.1520347, 0.182639;

  comparePoses(forward_pose, actual_pose);
}

TEST(kuka_kr6, inverse_kinematics)
{
  // this test assumes that the forward kinematics for joint values
  // {0.2, 0.2, 0.2, 0.2, 0.2, 0.2} are correct

  const auto kuka = opw_kinematics::makeKukaKR6_R700_sixx<float>();

  std::vector<float> joint_values = {0.2f, 0.2f, 0.2f, 0.2f, 0.2f, 0.2f};
  Transform<float> forward_pose = opw_kinematics::forward(kuka, &joint_values[0]);

  std::array<float, 6 * 8> sols;
  opw_kinematics::inverse(kuka, forward_pose, sols.data());

  Transform<float> pose;
  for (int i = 0; i < 8; ++i)
  {
    if (opw_kinematics::isValid(&sols[6 * i]))
    {
      // Forward kinematics of a solution should result in the same pose
      pose = opw_kinematics::forward(kuka, &sols[6 * i]);
      comparePoses(forward_pose, pose);
    }
  }
}

int main(int argc, char **argv)
{
  testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}


text: #include <boost/iostreams/device/mapped_file.hpp>


text:
/**
 * Content
 * An optimizated network graph class
 *
 * The optimization is achieved by recording the output
 * of routing in two variables predecessor map and distance map
 * and regularly updating and cleaning them.
 *
 * It avoids intialization of distances and predecessors vector
 * in each iteration of the driving distance calculation. With a
 * large road network, a small proportion of their nodes are visited
 * in the precomputation. 2018.03.09
 *
 * Add a property map for vertices in the graph to store discontinuous ID
 * for nodes.
 *
 * @author: Can Yang
 * @version: 2018.03.09
 */
#ifndef MM_NETWORK_GRAPH_OMP_HPP
#define MM_NETWORK_GRAPH_OMP_HPP
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <fstream>
#include <deque>
#include <boost/config.hpp>
#include <boost/graph/graph_traits.hpp>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/dijkstra_shortest_paths.hpp>
#include "bgl_driving_dist.hpp"
#include <boost/property_map/property_map.hpp>
#include <boost/graph/copy.hpp>
#include "types.hpp"
#include "reader.hpp"
#include "float.h"
#include "network.hpp"
#include <omp.h>
#include <algorithm> // std::reverse
#include <unordered_map>
#include <boost/archive/binary_oarchive.hpp> // Binary output of UBODT
namespace MM {
class NetworkGraphOmp
{
public:
    // A infinity value used in the routing algorithm
    static constexpr double DIST_NOT_FOUND = DBL_MAX;
    /**
     *  Construct a network graph from a network object
     */
    NetworkGraphOmp(Network *network){
        std::vector<Edge> *edges = network->get_edges();
        std::cout << "Construct graph from network edges start" << '\n';
        // Key is the external ID and value is the index of vertice
        std::unordered_map<int, int> vertex_map;
        int current_idx = -1;
        edge_descriptor e;
        bool inserted;
        g = Graph_T(); //18
        int N = edges->size();
        int source_idx = 0;
        int target_idx = 0;
        // printf("Network edges :%d \n", N);
        for (int i = 0; i < N; ++i) {
            Edge &network_edge = (*edges)[i];
            auto search = vertex_map.find(network_edge.source);
            // Search for source node idx
            if (search != vertex_map.end()) {
                // A node exists already
                source_idx = search->second;
            } else {
                // A new node is found
                ++current_idx;
                vertex_map.insert({network_edge.source, current_idx});
                source_idx = current_idx;
                vertex_id_vec.push_back(network_edge.source);
            };
            // Search for target node idx
            search = vertex_map.find(network_edge.target);
            if (search != vertex_map.end()) {
                // A node exists already
                target_idx = search->second;
            } else {
                // A new node is found
                ++current_idx;
                vertex_map.insert({network_edge.target, current_idx});
                target_idx = current_idx;
                vertex_id_vec.push_back(network_edge.target);
            };
            // boost::tie(e, inserted) = add_edge(network_edge.source, network_edge.target, g);
            boost::tie(e, inserted) = add_edge(source_idx, target_idx, g);
            // id is the FID read, id_attr is the external property in SHP
            g[e].id = network_edge.id;
            g[e].length = network_edge.length;
            //// printf( "Edge read %d,%d,%d,%lf\n",network_edge.id,network_edge.source,network_edge.target,network_edge.length);
        }
        num_vertices = boost::num_vertices(g);
        std::cout << "Graph nodes " << num_vertices << '\n';
        int num_threads = omp_get_num_procs();
        std::cout << "Number of thread available is " << num_threads << '\n';
        // initialize_distances_predecessors(num_threads);
        std::cout << "Construct graph from network edges end" << '\n';
    };

    /**
     * Precompute an UBODT with delta and save it to the file
     * @param filename [description]
     * @param delta    [description]
     */
    void precompute_ubodt(const std::string &filename, double delta, bool binary=true) {
        if (binary){
            precompute_ubodt_binary(filename,delta);
        } else {
            precompute_ubodt_csv(filename,delta);
        }
    };

    /**
     * Precompute an UBODT with delta and save it to the file
     * @param delta    [description]
     */
    void precompute_ubodt_csv(const std::string &filename, double delta) {
        int step_size = num_vertices / 10;
        if (step_size < 10) step_size = 10;
        std::ofstream m_fstream(filename);
        std::cout << "Start to generate UBODT CSV file with delta " << delta << '\n';
        m_fstream << "source;target;next_n;prev_n;next_e;distance\n";
        int progress = 0;
        // if (K>50000){
        //     K =50000;
        // }
        // std::cout << "Start to generate UBODT with k " << K << '\n';
        #pragma omp parallel
        {
            double thread_start_time = omp_get_wtime();
            // The copy is not complete here
            // boost::copy_graph(grid, graph, boost::vertex_copy(detail::grid_to_graph_vertex_copier(grid, graph))
            // .edge_copy(detail::grid_to_graph_edge_copier()));
            // Graph_T g;
            // boost::copy_graph(mg, g);
            std::vector<vertex_descriptor> predecessors_map(num_vertices);
            std::vector<double> distances_map(num_vertices);
            for (int i = 0; i < num_vertices; ++i) {
                distances_map[i] = std::numeric_limits<double>::max();
                predecessors_map[i] = i;
            }
            std::vector<vertex_descriptor> examined_vertices; // Nodes whose distance in the dist_map is updated.
            int thread_process_count=0;
            // If buf placed here, then the result almost doubles
            // Position 1
            // std::stringstream node_output_buf;
            #pragma omp for
            for (int source = 0; source < num_vertices; ++source) {
                std::vector<vertex_descriptor> nodesInDistance;
                examined_vertices.push_back(source);
                double inf = std::numeric_limits<double>::max();
                distances_map[source] = 0;
                // make_iterator_property_map maps the vertex indices vector to predecessors.
                boost::dijkstra_shortest_paths_upperbound(g,
                        source,
                        make_iterator_property_map(predecessors_map.begin(), get(boost::vertex_index, g), predecessors_map[0]),
                        make_iterator_property_map(distances_map.begin(), get(boost::vertex_index, g), distances_map[0]),
                        get(&Edge_Property::length, g),
                        get(boost::vertex_index, g),
                        std::less<double>(), //DistanceCompare distance_compare,
                        boost::closed_plus<double>(inf),
                        inf,
                        0, delta, nodesInDistance,examined_vertices
                );
                std::vector<vertex_descriptor> successors = get_successors(nodesInDistance, predecessors_map);
                double cost;
                int edge_id;
                int k = 0;
                vertex_descriptor node;
                std::stringstream node_output_buf;
                // Position 2
                while (k < nodesInDistance.size()) {
                    node = nodesInDistance[k];
                    if (source != node) {
                        cost = distances_map[successors[k]] - distances_map[source];
                        edge_id = get_edge_id(source, successors[k], cost);
                        node_output_buf << vertex_id_vec[source]<< ";" << vertex_id_vec[node]
                         << ";" << vertex_id_vec[successors[k]] << ";" << vertex_id_vec[predecessors_map[node]]
                         << ";" << edge_id << ";" << distances_map[node] << "\n";
                    }
                    ++k;
                }
                ++progress;
                if (progress % step_size == 0) {
                    printf("Progress %d / %d \n",progress, num_vertices);
                }
                // Clean the result
                int N = examined_vertices.size();
                for (int i = 0; i < N; ++i) {
                    vertex_descriptor v = examined_vertices[i];
                    distances_map[v] = std::numeric_limits<double>::max();
                    predecessors_map[v] = v;
                }
                examined_vertices.clear();
                #pragma omp critical
                m_fstream << node_output_buf.str();
            } // end of omp for
        } // end of omp parallel
        m_fstream.close();
    };
    /**
     * Precompute an UBODT with delta and save it to the file
     * @param delta    [description]
     */
    void precompute_ubodt_binary(const std::string &filename, double delta) {
        int step_size = num_vertices / 10;
        if (step_size < 10) step_size = 10;
        std::ofstream myfile(filename);
        boost::archive::binary_oarchive oa(myfile);
        std::cout << "Start to generate UBODT binary file with delta " << delta << '\n';
        int progress = 0;
        #pragma omp parallel
        {
            double thread_start_time = omp_get_wtime();
            // The copy is not complete here
            // boost::copy_graph(grid, graph, boost::vertex_copy(detail::grid_to_graph_vertex_copier(grid, graph))
            // .edge_copy(detail::grid_to_graph_edge_copier()));
            // Graph_T g;
            // boost::copy_graph(mg, g);
            std::vector<vertex_descriptor> predecessors_map(num_vertices);
            std::vector<double> distances_map(num_vertices);
            for (int i = 0; i < num_vertices; ++i) {
                distances_map[i] = std::numeric_limits<double>::max();
                predecessors_map[i] = i;
            }
            std::vector<vertex_descriptor> examined_vertices; // Nodes whose distance in the dist_map is updated.
            int thread_process_count=0;
            // If buf placed here, then the result almost doubles
            // Position 1
            #pragma omp for
            for (int source = 0; source < num_vertices; ++source) {
                std::vector<vertex_descriptor> nodesInDistance;
                examined_vertices.push_back(source);
                double inf = std::numeric_limits<double>::max();
                distances_map[source] = 0;
                // make_iterator_property_map maps the vertex indices vector to predecessors.
                boost::dijkstra_shortest_paths_upperbound(g,
                        source,
                        make_iterator_property_map(predecessors_map.begin(), get(boost::vertex_index, g), predecessors_map[0]),
                        make_iterator_property_map(distances_map.begin(), get(boost::vertex_index, g), distances_map[0]),
                        get(&Edge_Property::length, g),
                        get(boost::vertex_index, g),
                        std::less<double>(), //DistanceCompare distance_compare,
                        boost::closed_plus<double>(inf),
                        inf,
                        0, delta, nodesInDistance,examined_vertices
                );
                std::vector<vertex_descriptor> successors = get_successors(nodesInDistance, predecessors_map);
                double cost;
                int edge_id;
                int k = 0;
                vertex_descriptor node;
                std::vector<Record> source_map;
                // Position 2
                while (k < nodesInDistance.size()) {
                    node = nodesInDistance[k];
                    if (source != node) {
                        cost = distances_map[successors[k]] - distances_map[source];
                        edge_id = get_edge_id(source, successors[k], cost);
                        source_map.push_back({vertex_id_vec[source],vertex_id_vec[node]
                         ,vertex_id_vec[successors[k]], vertex_id_vec[predecessors_map[node]]
                         , edge_id, distances_map[node],nullptr});
                    }
                    ++k;
                }
                ++progress;
                if (progress % step_size == 0) {
                    printf("Progress %d / %d \n",progress, num_vertices);
                }
                // Clean the result
                int N = examined_vertices.size();
                for (int i = 0; i < N; ++i) {
                    vertex_descriptor v = examined_vertices[i];
                    distances_map[v] = std::numeric_limits<double>::max();
                    predecessors_map[v] = v;
                }
                examined_vertices.clear();
                #pragma omp critical
                for (Record &r:source_map){
                    oa << r.source << r.target << r.first_n <<r.prev_n <<r.next_e << r.cost;
                }
            } // end of omp for
        } // end of omp parallel
        myfile.close();
    };
private:
    /* Type definition for the property stored at each edge */
    struct Edge_Property
    {
        int id;
        double length;
    };
    // Boost graph type definition
    typedef boost::adjacency_list <boost::vecS, boost::vecS, boost::directedS, boost::no_property, Edge_Property> Graph_T;
    typedef Graph_T::vertex_descriptor vertex_descriptor;
    typedef Graph_T::edge_descriptor edge_descriptor;
    typedef boost::graph_traits<Graph_T>::vertex_iterator vertex_iterator;
    typedef boost::graph_traits<Graph_T>::out_edge_iterator out_edge_iterator;

    Graph_T g; // The member storing a boost graph
    /**
     *  Find the edge ID given a pair of nodes and its cost
     */
    int get_edge_id(vertex_descriptor source, vertex_descriptor target, double cost) {
        edge_descriptor e;
        out_edge_iterator out_i, out_end;
        for (boost::tie(out_i, out_end) = boost::out_edges(source, g);
                out_i != out_end; ++out_i) {
            e = *out_i; // Can we directly get edge id here or latter from the graph
            if (target == boost::target(e, g) && (g[e].length - cost <= DOUBLE_MIN)) {
                return  g[e].id;
            }
        }
        std::cout << "Edge not found for source " << source << " target " << target
                  << " cost " << cost << '\n';
        return -1;
    };

    /**
     *  Get the successors (next node visited) for each node in a
     *  shortest path tree defined by a deque and a predecessor vector
     */
    std::vector<vertex_descriptor> get_successors(std::vector<vertex_descriptor> &nodesInDistance, std::vector<vertex_descriptor>& predecessors) {
        int N = nodesInDistance.size();
        std::vector<vertex_descriptor> successors = std::vector<vertex_descriptor>(N);
        int i;
        vertex_descriptor u, v;
        vertex_descriptor source = nodesInDistance[0];// source node
        for (i = 0; i < N; ++i) {
            v = nodesInDistance[i];
            while ((u = predecessors[v]) != source) {
                v = u;
            }
            successors[i] = v;
        }
        return successors;
    };
    static constexpr double DOUBLE_MIN = 1.e-6; // This is used for comparing double values
    // Two maps record the routing output
    // The _pool variables are used by OpenMP
    // std::vector<std::vector<vertex_descriptor>> predecessors_map_pool;
    // a list of costs stored for one node to all nodes in the graph
    // std::vector<std::vector<double>> distances_map_pool;
    std::vector<int> vertex_id_vec; // stores the external ID of each vertex in G
    // std::vector<std::vector<vertex_descriptor>> examined_vertices_pool; // Nodes whose distance in the dist_map is updated.
    //std::vector<std::stringstream> stream_pool; // Nodes whose distance in the dist_map is updated.
    int num_vertices = 0;
}; // NetworkGraphOmp
} // MM
#endif /* MM_NETWORK_GRAPH_OPT_OMP_HPP */

max_stars_repo_name: BrunoSalerno/fmm

max_issues_repo_name: BrunoSalerno/fmm

max_forks_repo_name: BrunoSalerno/fmm


text:
//          Copyright Gavin Band 2008 - 2012.
// 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 METRO_LOG_SUM_EXP_HPP
#define METRO_LOG_SUM_EXP_HPP

#include <vector>
#include <Eigen/Core>

namespace metro {
	// Compute the log of a sum of exponentials via an algorithm that
	template< typename Matrix, typename Nonmissingness >
	double log_sum_exp( Matrix const& data, Nonmissingness const& nonmissingness ) {
		assert( data.rows() == nonmissingness.rows() ) ;
		assert( data.cols() == nonmissingness.cols() ) ;
		if( data.size() == 0 || nonmissingness.sum() == 0 ) {
			return 0.0 ;
		}
		double max_value = ( data.array() * nonmissingness.array() ).maxCoeff() ;
		if( max_value == -std::numeric_limits< double >::infinity() ) {
			return max_value ;
		}
		Eigen::MatrixXd const exponential = ( data - Eigen::MatrixXd::Constant( data.rows(), data.cols(), max_value ) ).array().exp() ;
		return max_value + std::log( ( exponential.array() * nonmissingness.array() ).sum() ) ;
	}

	// Ditto but assuming all values are present.
	template< typename Matrix >
	double log_sum_exp( Matrix const& data ) {
		if( data.size() == 0 ) {
			return 0.0 ;
		}
		double max_value = data.array().maxCoeff() ;
		if( max_value == -std::numeric_limits< double >::infinity() ) {
			return max_value ;
		}
		Eigen::MatrixXd const exponential = ( data - Eigen::MatrixXd::Constant( data.rows(), data.cols(), max_value ) ).array().exp() ;
		return max_value + std::log( exponential.array().sum() ) ;
	}

	// Ditto but assuming all values are present.
	template<>
	double log_sum_exp( std::vector< double > const& data ) ;

	void rowwise_log_sum_exp( Eigen::MatrixXd const&, Eigen::VectorXd* result ) ;
	void rowwise_log_sum_exp( Eigen::MatrixXd const&, Eigen::MatrixXd const& nonmissingness, Eigen::VectorXd* result ) ;
}

#endif

max_stars_repo_name: gavinband/qctool

max_issues_repo_name: gavinband/qctool

max_forks_repo_name: gavinband/qctool


text:
#include "gtest.h"

#ifdef HAS_EIGEN3
#include <Eigen/Core>
#endif

#include "../../core/GSLAM.h"
#include "../../core/Event.h"

TEST(SLAM,LoadRelease)
{
    std::string slamPlugin=svar.GetString("SLAM","");
    if(slamPlugin.empty()) return;
    GSLAM::SLAMPtr slam=GSLAM::SLAM::create(slamPlugin);
    slam->call("Stop");
    slam.reset();
}

#ifdef EIGEN_MATRIX_H

TEST(SLAM,EigenPoint)
{
    Eigen::Vector2d pt2_eigen;
    GSLAM::Point2f  pt2_gslam=pt2_eigen;
    pt2_eigen=pt2_gslam;

    Eigen::Vector3d pt3_eigen;
    GSLAM::Point3f  pt3_gslam=pt3_eigen;
    pt3_eigen=pt3_gslam;

    pi::SE3f      se3;
    Eigen::Matrix<float,6,1> ln=se3.ln();
}

#endif

max_stars_repo_name: whu-lyh/GSLAM


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

#include <cstddef>
#include <boost/detail/workaround.hpp>
#include <nt2/sdk/config/bootstrap.hpp>

////////////////////////////////////////////////////////////////////////////////
// On g++ before 4.3, alignment can't be more than 16
////////////////////////////////////////////////////////////////////////////////
#if BOOST_WORKAROUND(__GNUC__, == 4) && BOOST_WORKAROUND(__GNUC_MINOR__, < 3)
#undef  NT2_CONFIG_ALIGNMENT
#define NT2_CONFIG_ALIGNMENT 16
#endif

////////////////////////////////////////////////////////////////////////////////
// On some system, the qlignment detection fail, force it to be 16
////////////////////////////////////////////////////////////////////////////////
#if (NT2_CONFIG_ALIGNMENT <= 1)
#undef  NT2_CONFIG_ALIGNMENT
#define NT2_CONFIG_ALIGNMENT 16
#endif

#endif


text:
/*
The MIT License (MIT)

Copyright (c) 2013-2018 menonon

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

#pragma once

#include <GL/glew.h>
#ifdef __APPLE__
#include <OpenGL/gl.h>
#else
#include <GL/gl.h>
#endif

#include <map>
#include <string>
#include <iostream>
#include <fstream>
#include <vector>

#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <IL/il.h>
#include <IL/ilu.h>
#include <boost/regex.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/filesystem/operations.hpp>

#include "texture.hpp"
#include "geometry.hpp"
#include "shader.hpp"

class MarchingCubes {

public:
	MarchingCubes();
	~MarchingCubes();

	void setData(Texture<GLfloat>* aTexture);
	void generateGeometry();

	void setThreshold(GLfloat aPercentage);

	void bind(int i);
	void unbind(int i);

	void render(glm::mat4 aProjection, glm::mat4 aView);

private:

	Texture<GLfloat>* mData;
	Geometry* mCells[100];
	static Shader* mMCShader;

	glm::ivec3 mSlices;
	glm::mat4 mModel;
	GLfloat mThreshold;

	static bool isInitialized;
	static GLint* mEdgeConnection;
	static GLint* mEdgeFlags;
	static Texture<GLint>* mTexEdgeConnection;

	void staticInit();
	void initTables();
	void initBuffers();
	void initShader();

	const int d = 1;

};

max_stars_repo_name: menonon/SimpleGLWrapper

max_issues_repo_name: menonon/SimpleGLWrapper

max_forks_repo_name: menonon/SimpleGLWrapper


text:
/**
 * @file   Unit-Tests/test-xpath-mini-grammar.cpp
 * @date   Started 2018-08-15
 * @author Lester J. Dowling
 */
#include "pch-unit-tests.hpp"
#include <boost/test/unit_test.hpp>
#include "Pseudo-XPath/mini-grammar.hpp"
#include "Pseudo-XPath/Grade.hpp"
namespace utf = boost::unit_test;

BOOST_AUTO_TEST_SUITE(test_xpath_mini_grammar_suite, *utf::enabled())

/*
 * Unit tests to verify the correct operation of the pseudo XPath grammar.
 */

namespace fsn = boost::fusion;
namespace spirit = boost::spirit;
namespace qi = spirit::qi;
namespace ascii = spirit::ascii;
namespace phx = boost::phoenix;
using Stream_Iterator = boost::spirit::basic_istream_iterator<char>;
using XPath_Grammar = pseudo_xpath::mini_grammar<Stream_Iterator>;
using Grade = pseudo_xpath::Grade;

BOOST_AUTO_TEST_CASE(single_attribute_filter)
{
	const char* const xpath_text = "Cell[ Column=1 ]   ";
	XPath_Grammar g;
	std::istringstream sample_stream{ xpath_text };
	sample_stream.unsetf(std::ios::skipws);
	sample_stream >> qi::phrase_match(g, ascii::space);
	BOOST_REQUIRE(sample_stream.good() || sample_stream.eof());
	int path_depth = 0;
	Grade::SP v = g.result;
	BOOST_TEST(v);

	v = v->next();
	BOOST_TEST(v);
	path_depth++;
	BOOST_TEST(path_depth == 1);
	BOOST_TEST(v->name() == "Cell");
	BOOST_TEST(v->filters().size() == 1);
	BOOST_TEST(v->filters().front().attribute_name == "Column");
	BOOST_TEST(v->filters().front().filter_operator == '=');
	BOOST_TEST(v->filters().front().filter_number == 1);
	BOOST_TEST(v->filters().front().filter_value == "1");
	BOOST_TEST(Grade::path_to_string(g.result) == "Cell[Column=1]");
}

BOOST_AUTO_TEST_CASE(implicit_attribute_filter_named)
{
	const char* const xpath_text = "Worksheet['Profit and Loss']";
	XPath_Grammar g;
	std::istringstream sample_stream{ xpath_text };
	sample_stream.unsetf(std::ios::skipws);
	sample_stream >> qi::phrase_match(g, ascii::space);
	BOOST_REQUIRE(sample_stream.good() || sample_stream.eof());
	int path_depth = 0;
	Grade::SP v = g.result;
	BOOST_TEST(v);

	v = v->next();
	BOOST_TEST(v);
	path_depth++;
	BOOST_TEST(path_depth == 1);
	BOOST_TEST(v->name() == "Worksheet");
	BOOST_TEST(v->filters().size() == 1);
	BOOST_TEST(v->filters().front().attribute_name == "Worksheet");
	BOOST_TEST(v->filters().front().filter_operator == '=');
	BOOST_TEST(v->filters().front().filter_value == "Profit and Loss");
	BOOST_TEST(Grade::path_to_string(g.result) == "Worksheet[Worksheet='Profit and Loss']");
}

BOOST_AUTO_TEST_CASE(implicit_attribute_filter_numbered)
{
	const char* const xpath_text = "Worksheet[1]";
	XPath_Grammar g;
	std::istringstream sample_stream{ xpath_text };
	sample_stream.unsetf(std::ios::skipws);
	sample_stream >> qi::phrase_match(g, ascii::space);
	BOOST_REQUIRE(sample_stream.good() || sample_stream.eof());
	int path_depth = 0;
	Grade::SP v = g.result;
	BOOST_TEST(v);

	v = v->next();
	BOOST_TEST(v);
	path_depth++;
	BOOST_TEST(path_depth == 1);
	BOOST_TEST(v->name() == "Worksheet");
	BOOST_TEST(v->filters().size() == 1);
	BOOST_TEST(v->filters().front().attribute_name == "Worksheet");
	BOOST_TEST(v->filters().front().filter_operator == '=');
	BOOST_TEST(v->filters().front().filter_value == "1");
	BOOST_TEST(v->filters().front().good_filter_number);
	BOOST_TEST(Grade::path_to_string(g.result) == "Worksheet[Worksheet=1]");
}

BOOST_AUTO_TEST_CASE(implicit_attribute_filter_alternation)
{
	const char* const xpath_text = "Worksheet[1|2|3]";
	XPath_Grammar g;
	std::istringstream sample_stream{ xpath_text };
	sample_stream.unsetf(std::ios::skipws);
	sample_stream >> qi::phrase_match(g, ascii::space);
	BOOST_REQUIRE(sample_stream.good() || sample_stream.eof());
	int path_depth = 0;
	Grade::SP v = g.result;
	BOOST_TEST(v);

	v = v->next();
	BOOST_TEST(v);
	path_depth++;
	BOOST_TEST(path_depth == 1);
	BOOST_TEST(v->name() == "Worksheet");
	BOOST_TEST(v->filters().size() == 3);
	BOOST_TEST(v->filters().front().attribute_name == "Worksheet");
	BOOST_TEST(v->filters().front().filter_operator == '=');
	BOOST_TEST(v->filters().front().filter_value == "1");
	BOOST_TEST(v->filters().front().good_filter_number);
	BOOST_TEST(Grade::path_to_string(g.result) == "Worksheet[Worksheet=1 Worksheet=2 Worksheet=3]");
}

BOOST_AUTO_TEST_CASE(column_path_1)
{
	const char* const xpath_text =
	  "Workbook, Worksheet[1], Table, Row[1],Cell,Data[ss:Type=String]";
	XPath_Grammar g;
	std::istringstream sample_stream{ xpath_text };
	sample_stream.unsetf(std::ios::skipws);
	sample_stream >> qi::phrase_match(g, ascii::space);
	BOOST_REQUIRE(sample_stream.good() || sample_stream.eof());
	int path_depth = 0;
	Grade::SP v = g.result;
	BOOST_TEST(v);
}

BOOST_AUTO_TEST_CASE(grammar_xml_attribute_filter)
{
	const char* const xpath_text = "  Worksheet   ,   Table   ,   Row[ Row=12 ] , "
								   "Cell[ Column=1  ss::ValueType=Number ]   ";
	XPath_Grammar g;
	std::istringstream sample_stream{ xpath_text };
	sample_stream.unsetf(std::ios::skipws);
	sample_stream >> qi::phrase_match(g, ascii::space);
	BOOST_REQUIRE(sample_stream.good() || sample_stream.eof());
	int path_depth = 0;
	Grade::SP v = g.result;
	BOOST_TEST(v);

	v = v->next();
	BOOST_TEST(v);
	path_depth++;
	BOOST_TEST(path_depth == 1);
	BOOST_TEST(v->name() == "Worksheet");
	BOOST_TEST(v->filters().empty());

	v = v->next();
	BOOST_TEST(v);
	path_depth++;
	BOOST_TEST(path_depth == 2);
	BOOST_TEST(v->name() == "Table");
	BOOST_TEST(v->filters().empty());

	v = v->next();
	BOOST_TEST(v);
	path_depth++;
	BOOST_TEST(path_depth == 3);
	BOOST_TEST(v->name() == "Row");
	BOOST_TEST(v->filters().size() == 1);
	BOOST_TEST(v->filters().front().attribute_name == "Row");
	BOOST_TEST(v->filters().front().filter_operator == '=');
	BOOST_TEST(v->filters().front().filter_value == "12");
	BOOST_TEST(v->filters().front().good_filter_number);

	v = v->next();
	BOOST_TEST(v);
	path_depth++;
	BOOST_TEST(path_depth == 4);
	BOOST_TEST(v->name() == "Cell");
	BOOST_TEST(v->filters().size() == 2);
	BOOST_TEST(v->filters().front().attribute_name == "Column");
	BOOST_TEST(v->filters().front().filter_operator == '=');
	BOOST_TEST(v->filters().front().filter_value == "1");
	BOOST_TEST(v->filters().front().good_filter_number);
	BOOST_TEST(v->filters().back().attribute_name == "ss::ValueType");
	BOOST_TEST(v->filters().back().filter_operator == '=');
	BOOST_TEST(v->filters().back().filter_value == "Number");
	BOOST_TEST(!v->filters().back().good_filter_number);

	BOOST_TEST(
	  Grade::path_to_string(g.result) ==
	  "Worksheet --> Table --> Row[Row=12] --> Cell[Column=1 ss::ValueType='Number']");
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: Lester-Dowling/Pseudo-XPath

max_issues_repo_name: Lester-Dowling/Pseudo-XPath

max_forks_repo_name: Lester-Dowling/Pseudo-XPath