text:
// Copyright 2018-2022 Emil Dotchevski and Reverge Studios, Inc.

// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#include <boost/leaf/config.hpp>

#ifdef BOOST_LEAF_NO_EXCEPTIONS

#include <iostream>

int main()
{
    std::cout << "Unit test not applicable." << std::endl;
    return 0;
}

#else

#ifdef BOOST_LEAF_TEST_SINGLE_HEADER
#   include "leaf.hpp"
#else
#   include <boost/leaf/handle_errors.hpp>
#   include <boost/leaf/pred.hpp>
#   include <boost/leaf/result.hpp>
#endif

#include "lightweight_test.hpp"

namespace leaf = boost::leaf;

template <int> struct info { int value; };

struct my_exception: std::exception
{
    int value;

    my_exception():
        value(0)
    {
    }

    my_exception(int v):
        value(v)
    {
    }
};

int main()
{
    {
        leaf::result<int> r = leaf::try_handle_some(
            []() -> leaf::result<int>
            {
                return 42;
            },
            []
            {
                return 1;
            } );
        BOOST_TEST(r);
        BOOST_TEST_EQ(r.value(), 42);
    }
    {
        leaf::result<int> r = leaf::try_handle_some(
            []() -> leaf::result<int>
            {
                throw leaf::exception( my_exception(), info<1>{1} );
            },
            []( my_exception const &, info<1> const & x )
            {
                BOOST_TEST_EQ(x.value, 1);
                return 1;
            } );
        BOOST_TEST(r);
        BOOST_TEST_EQ(r.value(), 1);
    }
    {
        leaf::result<int> r = leaf::try_handle_some(
            []() -> leaf::result<int>
            {
                throw leaf::exception( info<1>{1} );
            },
            []( info<1> const & x )
            {
                BOOST_TEST_EQ(x.value, 1);
                return 1;
            } );
        BOOST_TEST(r);
        BOOST_TEST_EQ(r.value(), 1);
    }
    {
        leaf::result<int> r = leaf::try_handle_some(
            []() -> leaf::result<int>
            {
                return leaf::new_error( info<1>{1} );
            },
            []( info<1> const & x )
            {
                BOOST_TEST_EQ(x.value, 1);
                return 1;
            } );
        BOOST_TEST(r);
        BOOST_TEST_EQ(r.value(), 1);
    }

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

    {
        auto error_handlers = std::make_tuple(
            []( my_exception const &, info<1> const & x ) -> leaf::result<int>
            {
                BOOST_TEST_EQ(x.value, 1);
                return 1;
            },
            []( info<1> const & x ) -> leaf::result<int>
            {
                BOOST_TEST_EQ(x.value, 1);
                return 2;
            } );
        {
            leaf::result<int> r = leaf::try_handle_some(
                []() -> leaf::result<int>
                {
                    return 42;
                },
                error_handlers );
            BOOST_TEST(r);
            BOOST_TEST_EQ(r.value(), 42);
        }
        {
            leaf::result<int> r = leaf::try_handle_some(
                []() -> leaf::result<int>
                {
                    throw leaf::exception( my_exception(), info<1>{1} );
                },
                error_handlers );
            BOOST_TEST(r);
            BOOST_TEST_EQ(r.value(), 1);
        }
        {
            leaf::result<int> r = leaf::try_handle_some(
                []() -> leaf::result<int>
                {
                    throw leaf::exception( info<1>{1} );
                },
                error_handlers );
            BOOST_TEST(r);
            BOOST_TEST_EQ(r.value(), 2);
        }
        {
            leaf::result<int> r = leaf::try_handle_some(
                []() -> leaf::result<int>
                {
                    return leaf::new_error( info<1>{1} );
                },
                error_handlers );
            BOOST_TEST(r);
            BOOST_TEST_EQ(r.value(), 2);
        }
    }

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

    {
        int r = leaf::try_handle_all(
            []() -> leaf::result<int>
            {
                return 42;
            },
            []
            {
                return 1;
            } );
        BOOST_TEST_EQ(r, 42);
    }
    {
        int r = leaf::try_handle_all(
            []() -> leaf::result<int>
            {
                throw leaf::exception( my_exception(), info<1>{1} );
            },
            []( my_exception const &, info<1> const & x )
            {
                BOOST_TEST_EQ(x.value, 1);
                return 1;
            },
            []
            {
                return 2;
            } );
        BOOST_TEST_EQ(r, 1);
    }
    {
        int r = leaf::try_handle_all(
            []() -> leaf::result<int>
            {
                throw leaf::exception( info<1>{1} );
            },
            []( info<1> const & x )
            {
                BOOST_TEST_EQ(x.value, 1);
                return 1;
            },
            []
            {
                return 2;
            } );
        BOOST_TEST_EQ(r, 1);
    }
    {
        int r = leaf::try_handle_all(
            []() -> leaf::result<int>
            {
                return leaf::new_error( info<1>{1} );
            },
            []( info<1> const & x )
            {
                BOOST_TEST_EQ(x.value, 1);
                return 1;
            },
            []
            {
                return 2;
            } );
        BOOST_TEST_EQ(r, 1);
    }

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

    {
        auto error_handlers = std::make_tuple(
            []( my_exception const &, info<1> const & x )
            {
                BOOST_TEST_EQ(x.value, 1);
                return 1;
            },
            []( info<1> const & x )
            {
                BOOST_TEST_EQ(x.value, 1);
                return 2;
            },
            []
            {
                return 1;
            } );
        {
            int r = leaf::try_handle_all(
                []() -> leaf::result<int>
                {
                    return 42;
                },
                error_handlers );
            BOOST_TEST_EQ(r, 42);
        }
        {
            int r = leaf::try_handle_all(
                []() -> leaf::result<int>
                {
                    throw leaf::exception( my_exception(), info<1>{1} );
                },
                error_handlers );
            BOOST_TEST_EQ(r, 1);
        }
        {
            int r = leaf::try_handle_all(
                []() -> leaf::result<int>
                {
                    throw leaf::exception( info<1>{1} );
                },
                error_handlers );
            BOOST_TEST_EQ(r, 2);
        }
        {
            int r = leaf::try_handle_all(
                []() -> leaf::result<int>
                {
                    return leaf::new_error( info<1>{1} );
                },
                error_handlers );
            BOOST_TEST_EQ(r, 2);
        }
    }

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

    {
        int r = leaf::try_handle_all(
            []() -> leaf::result<int>
            {
                return leaf::try_handle_all(
                    []() -> leaf::result<int>
                    {
                        return leaf::new_error( info<1>{1} );
                    },
                    []( info<1> const & ) -> int
                    {
                        BOOST_LEAF_THROW_EXCEPTION(my_exception());
                    },
                    []
                    {
                        return 1;
                    } );
            },
            []( my_exception const &, info<1> )
            {
                return 2;
            },
            []( my_exception const & )
            {
                return 3;
            },
            []
            {
                return 4;
            } );

        BOOST_TEST_EQ(r, 3);
    }
    {
        int r = leaf::try_handle_all(
            []() -> leaf::result<int>
            {
                return leaf::try_handle_all(
                    []() -> leaf::result<int>
                    {
                        return leaf::new_error( info<1>{1} );
                    },
                    []( info<1> const & x ) -> int
                    {
                        BOOST_TEST_EQ(x.value, 1);
                        BOOST_LEAF_THROW_EXCEPTION();
                    },
                    []
                    {
                        return 1;
                    } );
            },
            []( my_exception const &, info<1> )
            {
                return 2;
            },
            []( my_exception const & )
            {
                return 3;
            },
            []
            {
                return 4;
            } );

        BOOST_TEST_EQ(r, 4);
    }

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

    {
        auto error_handlers = std::make_tuple(
            []( info<1> const & x ) -> int
            {
                BOOST_TEST_EQ(x.value, 1);
                BOOST_LEAF_THROW_EXCEPTION(my_exception());
            },
            []
            {
                return 1;
            } );
        int r = leaf::try_handle_all(
            [&]() -> leaf::result<int>
            {
                return leaf::try_handle_all(
                    [&]() -> leaf::result<int>
                    {
                        return leaf::new_error( info<1>{1} );
                    },
                    error_handlers );
            },
            []( my_exception const &, info<1> )
            {
                return 2;
            },
            []( my_exception const & )
            {
                return 3;
            },
            []
            {
                return 4;
            } );

        BOOST_TEST_EQ(r, 3);
    }
    {
        auto error_handlers = std::make_tuple(
            []( info<1> const & x ) -> int
            {
                BOOST_TEST_EQ(x.value, 1);
                BOOST_LEAF_THROW_EXCEPTION();
            },
            []
            {
                return 1;
            } );
        int r = leaf::try_handle_all(
            [&]() -> leaf::result<int>
            {
                return leaf::try_handle_all(
                    [&]() -> leaf::result<int>
                    {
                        return leaf::new_error( info<1>{1} );
                    },
                    error_handlers );
            },
            []( my_exception const &, info<1> )
            {
                return 2;
            },
            []( my_exception const & )
            {
                return 3;
            },
            []
            {
                return 4;
            } );

        BOOST_TEST_EQ(r, 4);
    }

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

    {
        int r = leaf::try_handle_all(
            []() -> leaf::result<int>
            {
                return leaf::try_handle_some(
                    []() -> leaf::result<int>
                    {
                        return leaf::new_error( info<1>{1} );
                    },
                    []( info<1> const & x ) -> int
                    {
                        BOOST_TEST_EQ(x.value, 1);
                        BOOST_LEAF_THROW_EXCEPTION(my_exception());
                    },
                    []
                    {
                        return 1;
                    } );
            },
            []( my_exception const &, info<1> )
            {
                return 3;
            },
            []( my_exception const & )
            {
                return 4;
            },
            []
            {
                return 5;
            } );

        BOOST_TEST_EQ(r, 4);
    }
    {
        int r = leaf::try_handle_all(
            []() -> leaf::result<int>
            {
                return leaf::try_handle_some(
                    []() -> leaf::result<int>
                    {
                        return leaf::new_error( info<1>{1} );
                    },
                    []( info<1> const & x ) -> int
                    {
                        BOOST_TEST_EQ(x.value, 1);
                        BOOST_LEAF_THROW_EXCEPTION();
                    },
                    []
                    {
                        return 1;
                    } );
            },
            []( my_exception const &, info<1> )
            {
                return 3;
            },
            []( my_exception const & )
            {
                return 4;
            },
            []
            {
                return 5;
            } );

        BOOST_TEST_EQ(r, 5);
    }

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

    {
        auto error_handlers = std::make_tuple(
            []( info<1> const & x ) -> leaf::result<int>
            {
                BOOST_TEST_EQ(x.value, 1);
                BOOST_LEAF_THROW_EXCEPTION(my_exception());
            },
            []() -> leaf::result<int>
            {
                return 1;
            } );
        int r = leaf::try_handle_all(
            [&]() -> leaf::result<int>
            {
                return leaf::try_handle_some(
                    [&]() -> leaf::result<int>
                    {
                        return leaf::new_error( info<1>{1} );
                    },
                    error_handlers );
            },
            []( my_exception const &, info<1> )
            {
                return 3;
            },
            []( my_exception const & )
            {
                return 4;
            },
            []
            {
                return 5;
            } );

        BOOST_TEST_EQ(r, 4);
    }
    {
        auto error_handlers = std::make_tuple(
            []( info<1> const & x ) -> leaf::result<int>
            {
                BOOST_TEST_EQ(x.value, 1);
                BOOST_LEAF_THROW_EXCEPTION();
            },
            []() -> leaf::result<int>
            {
                return 1;
            } );
        int r = leaf::try_handle_all(
            [&]() -> leaf::result<int>
            {
                return leaf::try_handle_some(
                    [&]() -> leaf::result<int>
                    {
                        return leaf::new_error( info<1>{1} );
                    },
                    error_handlers );
            },
            []( my_exception const &, info<1> )
            {
                return 3;
            },
            []( my_exception const & )
            {
                return 4;
            },
            []
            {
                return 5;
            } );

        BOOST_TEST_EQ(r, 5);
    }

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

    // match_value<> with exceptions, try_handle_some
    {
        leaf::result<int> r = leaf::try_handle_some(
            []() -> leaf::result<int>
            {
                throw leaf::exception( my_exception(42) );
            },
            []( leaf::match_value<my_exception, 42> m )
            {
                return m.matched.value;
            } );
        BOOST_TEST(r);
        BOOST_TEST_EQ(r.value(), 42);
    }
    {
        leaf::result<int> r = leaf::try_handle_some(
            []() -> leaf::result<int>
            {
                throw my_exception(42);
            },
            []( leaf::match_value<my_exception, 42> m )
            {
                return m.matched.value;
            } );
        BOOST_TEST(r);
        BOOST_TEST_EQ(r.value(), 42);
    }
    {
        leaf::result<int> r = leaf::try_handle_some(
            []() -> leaf::result<int>
            {
                throw leaf::exception( my_exception(42) );
            },
            []( leaf::match_value<my_exception, 41> m )
            {
                return m.matched.value;
            },
            []( leaf::error_info const & unmatched )
            {
                return unmatched.error();
            } );
        BOOST_TEST(!r);
    }
    {
        leaf::result<int> r = leaf::try_handle_some(
            []() -> leaf::result<int>
            {
                throw my_exception(42);
            },
            []( leaf::match_value<my_exception, 41> m )
            {
                return m.matched.value;
            },
            []( leaf::error_info const & unmatched )
            {
                return unmatched.error();
            } );
        BOOST_TEST(!r);
    }

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

    // match_value<> with exceptions, try_handle_all
    {
        int r = leaf::try_handle_all(
            []() -> leaf::result<int>
            {
                throw leaf::exception( my_exception(42) );
            },
            []( leaf::match_value<my_exception, 42> m )
            {
                return m.matched.value;
            },
            []
            {
                return -1;
            } );
        BOOST_TEST_EQ(r, 42);
    }
    {
        int r = leaf::try_handle_all(
            []() -> leaf::result<int>
            {
                throw my_exception(42);
            },
            []( leaf::match_value<my_exception, 42> m )
            {
                return m.matched.value;
            },
            []
            {
                return -1;
            } );
        BOOST_TEST_EQ(r, 42);
    }
    {
        int r = leaf::try_handle_all(
            []() -> leaf::result<int>
            {
                throw leaf::exception( my_exception(42) );
            },
            []( leaf::match_value<my_exception, 41> m )
            {
                return m.matched.value;
            },
            []
            {
                return -1;
            } );
        BOOST_TEST_EQ(r, -1);
    }
    {
        int r = leaf::try_handle_all(
            []() -> leaf::result<int>
            {
                throw my_exception(42);
            },
            []( leaf::match_value<my_exception, 41> m )
            {
                return m.matched.value;
            },
            []
            {
                return -1;
            } );
        BOOST_TEST_EQ(r, -1);
    }

    return boost::report_errors();
}

#endif

max_stars_repo_name: clayne/leaf

max_issues_repo_name: clayne/leaf

max_forks_repo_name: clayne/leaf


text:
#include <memory>
#include <boost/foreach.hpp>

#include <framework/model.h>
#include <framework/model_node.h>
#include <framework/texture.h>
#include <framework/colour.h>
#include <framework/graphics.h>
#include <framework/shader.h>

namespace fw {

model_node::model_node() : transform(fw::identity()), mesh_index(-1) {
}

model_node::~model_node() {
}

void model_node::initialize(model *mdl) {
  _model = mdl;

  if (mesh_index >= 0) {
    std::shared_ptr<model_mesh> mesh = mdl->meshes[mesh_index];
    set_vertex_buffer(mesh->get_vertex_buffer());
    set_index_buffer(mesh->get_index_buffer());
    set_shader(mesh->get_shader());
    set_primitive_type(sg::primitive_trianglelist);

    std::shared_ptr<shader_parameters> params = get_shader()->create_parameters();
    if (mdl->texture) {
      params->set_texture("entity_texture", mdl->texture);
    }
    params->set_colour("mesh_colour", fw::colour(1, 1, 1));
    set_shader_parameters(params);
  }

  BOOST_FOREACH(std::shared_ptr<node> node, _children) {
    std::dynamic_pointer_cast<model_node>(node)->initialize(mdl);
  }
}

void model_node::render(sg::scenegraph *sg, fw::matrix const &model_matrix /*= fw::identity()*/) {
  if (_model->get_wireframe()) {
//    device = fw::framework::get_instance()->get_graphics()->get_device();
//    device->SetRenderState(D3DRS_FILLMODE, D3DFILL_WIREFRAME);
  }

  if (mesh_index >= 0) {
    get_shader_parameters()->set_colour("mesh_colour", _colour);
  }

  node::render(sg, transform * model_matrix);

  if (_model->get_wireframe()) {
//    device->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID);
  }
}

void model_node::populate_clone(std::shared_ptr<sg::node> clone) {
  node::populate_clone(clone);

  std::shared_ptr<model_node> mnclone(std::dynamic_pointer_cast<model_node>(clone));
  mnclone->_model = _model;
  mnclone->mesh_index = mesh_index;
  mnclone->node_name = node_name;
  mnclone->transform = transform;
  mnclone->_colour = _colour;
}

void model_node::set_colour(fw::colour colour) {
  _colour = colour;
  BOOST_FOREACH(std::shared_ptr<node> &child_node, _children) {
    std::dynamic_pointer_cast<model_node>(child_node)->set_colour(colour);
  }
}

std::shared_ptr<sg::node> model_node::clone() {
  std::shared_ptr<sg::node> clone(new model_node());
  populate_clone(clone);
  return clone;
}

}

ext: cc

max_stars_repo_name: codeka/ravaged-planets

max_issues_repo_name: codeka/ravaged-planets

max_forks_repo_name: codeka/ravaged-planets


text:
#pragma once

#include "shader_asset.h"
#include "core/math/math.h"
#include "core/misc/string.h"
#include "core/asset/asset_subsystem.h"
#include "render/render_subsystem.h"
#include <boost/regex.h>

namespace luna
{
namespace render
{

REIGSTER_TYPE_IMPLEMENT(ShaderAsset)
{
	cls->Ctor<ShaderAsset>();
};

void ShaderAsset::OnAssetFileRead(LSharedPtr<Dictionary> meta, LSharedPtr<LFile> file)
{
 	LTextAsset::OnAssetFileRead(meta, file);
// 	size_t pos;
// 	std::vector<std::string> m_lines;
// 	boost::algorithm::split(m_lines, m_content.str(), boost::is_any_of("\n"));
// 	std::string res;
// 	for (std::string &line : m_lines)
// 	{
// 		auto pos = line.find("#include");
// 		if (pos != std::string::npos)
// 		{
// 			std::string file = line.substr(pos + 8);
// 			boost::algorithm::replace_all(file, "\r", "");
// 			boost::algorithm::trim(file);
// 			ShaderAsset* header = g_asset_sys->LoadAsset<ShaderAsset>(file.c_str());
// 			line = header->m_content.str();
// 		}
// 		res += line;
// 	}
// 	m_content.Assign(res);
//
}

void ShaderAsset::Init()
{
	if (!m_init)
	{
		m_shader = g_render_sys->GetDevice()->CreateShader();
		m_shader->Init(GetContent(), GetAssetPath());
		m_init = true;
	}
}

}
};

ext: cpp

max_stars_repo_name: LunarGameTeam/Lunar-GameEngine

max_issues_repo_name: LunarGameTeam/Lunar-GameEngine

max_forks_repo_name: LunarGameTeam/Lunar-GameEngine


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

#include "pinocchio/bindings/python/algorithm/algorithms.hpp"
#include "pinocchio/algorithm/centroidal-derivatives.hpp"

#include <boost/python/tuple.hpp>

namespace pinocchio
{
  namespace python
  {

    bp::tuple computeCentroidalDynamicsDerivatives_proxy(const Model & model,
                                                         Data & data,
                                                         const Eigen::VectorXd & q,
                                                         const Eigen::VectorXd & v,
                                                         const Eigen::VectorXd & a)
    {
      typedef Data::Matrix6x Matrix6x;
      Matrix6x partialh_dq(Matrix6x::Zero(6,model.nv));
      Matrix6x partial_dq(Matrix6x::Zero(6,model.nv));
      Matrix6x partial_dv(Matrix6x::Zero(6,model.nv));
      Matrix6x partial_da(Matrix6x::Zero(6,model.nv));

      computeCentroidalDynamicsDerivatives(model,data,q, v, a,
                                           partialh_dq, partial_dq, partial_dv, partial_da);

      return bp::make_tuple(partialh_dq, partial_dq,partial_dv,partial_da);
    }

    bp::tuple getCentroidalDynamicsDerivatives_proxy(const Model & model,
                                                     Data & data)
    {
      typedef Data::Matrix6x Matrix6x;

      Matrix6x partialh_dq(Matrix6x::Zero(6,model.nv));
      Matrix6x partial_dq(Matrix6x::Zero(6,model.nv));
      Matrix6x partial_dv(Matrix6x::Zero(6,model.nv));
      Matrix6x partial_da(Matrix6x::Zero(6,model.nv));

      getCentroidalDynamicsDerivatives(model,data, partialh_dq, partial_dq, partial_dv, partial_da);
      return bp::make_tuple(partialh_dq,partial_dq,partial_dv,partial_da);
    }

    void exposeCentroidalDerivatives()
    {
      using namespace Eigen;

      bp::def("computeCentroidalDynamicsDerivatives",
              computeCentroidalDynamicsDerivatives_proxy,
              bp::args("Model","Data",
                       "q: configuration vector (size model.nq)",
                       "v: velocity vector (size model.nv)",
                       "a: acceleration vector (size model.nv)"),
              "Computes the analytical derivatives of the centroidal dynamics\n"
              "with respect to the joint configuration vector, velocity and acceleration.");
      bp::def("getCentroidalDynamicsDerivatives",
              getCentroidalDynamicsDerivatives_proxy,
              bp::args("Model","Data"),
              "Retrive the analytical derivatives of the centroidal dynamics\n"
              "from the RNEA derivatives.\n"
              "pinocchio.computeRNEADerivatives should have been called first.");
    }

  } // namespace python
} // namespace pinocchio

max_stars_repo_name: ikalevatykh/pinocchio

max_issues_repo_name: ikalevatykh/pinocchio

max_forks_repo_name: ikalevatykh/pinocchio


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

/**
 * \file mpc_solver_XUopt.hpp
 * \brief
 * \details
 *
 * \author Autonomous Space Robotics Lab (ASRL)
 */
#pragma once

#include <algorithm>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>

#include <Eigen/Cholesky>
#include <Eigen/Dense>
#include <unsupported/Eigen/SparseExtra>

#include <vtr_path_tracker/robust_mpc/optimization/mpc_solver_base.hpp>

const int SOLN_OK = 1;
const int UNCERT_EXCEEDS_CONSTRAINTS = 2;

namespace vtr {
namespace path_tracker {

class MpcSolverXUopt : public MpcSolverBase {
 public:
  EIGEN_MAKE_ALIGNED_OPERATOR_NEW

  /** \brief Constructor */
  MpcSolverXUopt();

  /** \brief Destructor */
  ~MpcSolverXUopt();

  /// \todo: add documentation

  /** \brief This reset occurs once per timestep */
  void reset_solver_specific() override;
  MpcNominalModel::model_state_t *select_x_pred(int index) override;
  MpcNominalModel::model_trajectory_t *select_x_pred() override;
  void set_desired_speed_ctrl(int &index, const double &speed,
                              const double &ctrl) override;
  void set_desired_speed(int &index, const double &speed) override;
  void get_desired_ctrl(int &index) override;
  void post_process_x_pred(int &index) override;

  /** \brief This computation occurs for each iteration of the solver */
  void compute_solver_update(const local_path_t &local_path,
                             int iteration) override;

  void get_u(Eigen::MatrixXf &u_mat) override;
  void get_v(Eigen::MatrixXf &v_mat) override;
  void get_w(Eigen::MatrixXf &w_mat) override;
  void set_cmd_km1(const float &u_km1_in, const float &v_km1_in) override;
  void set_exp_consts(float c_in, float c_out);
  float c_in, c_out;

 private:
  // Timing variables
  std::vector<float> norm_ds_opt;
  float step_size_;
  int iterations_small_step;

  // The variable mu is used by constrained optimization and varies as a
  // function of iteration
  float mu_value;
  int mu_index;
  void update_mu_value(float &mu_value);

  // Optimization matrix sizes & indices
  int size_x_vec, size_u_vec, size_v_vec, size_y_vec, size_z_vec, size_w_vec;
  int x_offset_index, u_offset_index, v_offset_index, y_offset_index;
  int z_lb_offset_index, z_ub_offset_index, w_lb_offset_index,
      w_ub_offset_index;

  // Intermediate optimization variables
  Eigen::MatrixXf x_ub_lims, x_lb_lims;
  Eigen::MatrixXf x_ub_abc, x_lb_abc;
  mtx_triplet_list_t weight_Q_triplet, weight_Ru_triplet, weight_Rv_triplet;
  Eigen::SparseMatrix<float, 0> weight_Q;  // weight_Ru, weight_Rv;
  Eigen::MatrixXf weight_Ru_diag, weight_Rv_diag, dI_t_Rdu_dI, dI_t_Rdv_dI,
      weight_u0, weight_v0;
  int solution_result;
  Eigen::MatrixXf x_minus_fx_, gx_minus_w_;

  Eigen::MatrixXf exp_bw, f_1, df_1, d2f_1, d2_cost_w;

  // Final optimization variables: opt_update = - J_grad_L_mtx^(-1)*grad_L;
  Eigen::MatrixXf s_bar, ds_bar;
  Eigen::MatrixXf grad_L;
  Eigen::SparseMatrix<float> J_grad_L_mtx;
  mtx_triplet_list_t J_grad_L_triplet_list;
  std::vector<bool> J_grad_L_mtx_entries_flg;
  std::vector<int> J_grad_L_mtx_indices;
  Eigen::MatrixXf grad_L_im1, ds_opt_im1;

  /** \brief Utility function
   * Finds the sign of a number
   * \todo duplicated in utilities.h
   */
  float getSign(float number);

  // Optimization algorithm helper functions
  void compute_mtx_offsets_and_sizes();
  void reset_solver_variables();
  void compute_weight_mtxs();
  void extract_x(const local_path_t &local_path);
  void compute_constraints_V2(const local_path_t &local_path);
  void extract_grad_L();
  void extract_J_grad_L(int iteration);

  void insert_triplet_list(mtx_triplet_list_t &triplet_list_out,
                           mtx_triplet_list_t &triplet_list_in, float &mult,
                           int &i, int &j, float sign = 1.0f);
  void insert_mtx(mtx_triplet_list_t &triplet_list_out,
                  const Eigen::MatrixXf &gradients_in, int &i, int &j,
                  float sign = 1.0f, bool transpose = false);
  void insert_triplet(mtx_triplet_list_t &triplet_list_out, const int &i,
                      const int &j, float v_ij, float sign = 1.0f);

  void insert_triplet_list(Eigen::MatrixXf &mtx,
                           mtx_triplet_list_t &triplet_list_in, float &mult,
                           int &i, int &j, float sign = 1.0f);
  void insert_mtx(Eigen::MatrixXf &mtx, const Eigen::MatrixXf &gradients_in,
                  int &i, int &j, float sign = 1.0f, bool transpose = false);
  void insert_triplet(Eigen::MatrixXf &mtx, const int &i, const int &j,
                      float v_ij, float sign = 1.0f);

  void populate_mtx(Eigen::SparseMatrix<float, 0> &mtx_sm,
                    mtx_triplet_list_t &triplet_list);
  void reset_index_list(mtx_triplet_list_t &triplet_list_in);
  void compute_limiting_step_size(float &step_size, float &s_km1, float &ds,
                                  float lb, float ub);
};

}  // namespace path_tracker
}  // namespace vtr

ext: hpp


text:
#include <boost/concept_check.hpp>

int
main ()
{
  return 0;
}


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

#ifndef IROHA_POSTGRES_BLOCK_QUERY_HPP
#define IROHA_POSTGRES_BLOCK_QUERY_HPP

#include "ametsuchi/block_query.hpp"

#include <soci/soci.h>
#include <boost/optional.hpp>
#include "ametsuchi/key_value_storage.hpp"
#include "interfaces/iroha_internal/block_json_deserializer.hpp"
#include "logger/logger_fwd.hpp"

namespace iroha {
  namespace ametsuchi {

    /**
     * Class which implements BlockQuery with a Postgres backend.
     */
    class PostgresBlockQuery : public BlockQuery {
     public:
      PostgresBlockQuery(
          soci::session &sql,
          KeyValueStorage &file_store,
          std::shared_ptr<shared_model::interface::BlockJsonDeserializer>
              converter,
          logger::LoggerPtr log);

      PostgresBlockQuery(
          std::unique_ptr<soci::session> sql,
          KeyValueStorage &file_store,
          std::shared_ptr<shared_model::interface::BlockJsonDeserializer>
              converter,
          logger::LoggerPtr log);

      BlockResult getBlock(
          shared_model::interface::types::HeightType height) override;

      shared_model::interface::types::HeightType getTopBlockHeight() override;

      boost::optional<TxCacheStatusType> checkTxPresence(
          const shared_model::crypto::Hash &hash) override;

     private:
      std::unique_ptr<soci::session> psql_;
      soci::session &sql_;

      KeyValueStorage &block_store_;
      std::shared_ptr<shared_model::interface::BlockJsonDeserializer>
          converter_;

      logger::LoggerPtr log_;
    };
  }  // namespace ametsuchi
}  // namespace iroha

#endif  // IROHA_POSTGRES_BLOCK_QUERY_HPP

max_stars_repo_name: IvanTyulyandin/iroha


text:
//
// Created by artem on 14.08.20.
//

#include <boost/algorithm/hex.hpp>
#include <string>

#include "mini_btc/data_types/data_types.h"

#ifdef HAVE_OPENSSL
#include "crypto.hpp"
#endif

#include "utils.h"

void remove0x(std::string &s) {
  if(s.rfind("0x", 0) == 0)
    s.erase(0, 2);
}

Hash sha256bytes(const std::string &strBytes) {
  std::string hashRes = SimpleWeb::Crypto::Crypto::sha256(strBytes);

  Hash res;
  std::copy(hashRes.begin(), hashRes.end(), res.begin());
  return res;
}

std::string sigToHexStr(const Signature &s) {
  return objToHexStr(s);
}

std::string hashToHexStr(const Hash &h) {
  return objToHexStr(h);
}

Signature hexStrToSig(const std::string &s) {
  return hexStrToObj<Signature>(s);
}

Hash hexStrToHash(const std::string &s) {
  return hexStrToObj<Hash>(s);
}


text:
/*
	MIT-LICENSE
	Copyright (c) 2017-2018 Higher Edge Software, LLC

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

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

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

#include "RadJav.h"
#include "RadJavString.h"
#include "cpp/RadJavCPPNetWebServer.h"
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include <boost/uuid/uuid_io.hpp>

#ifdef USE_V8
#include "v8/RadJavV8JavascriptEngine.h"
#endif

namespace RadJAV
{
	namespace CPP
	{
		namespace Net
		{
		        const int NID_COMMON_NAME = 13;
		        const int NID_COUNTRY = 14;
		        const int NID_LOCALITY = 15;
		        const int NID_STATE = 16;
		        const int NID_ORGANIZATION = 17;
		        const int NID_ORGANIZATIONAL_UNIT = 18;

   		        const int NID_EMAIL_ADDRESS = 48;

		        const int NID_GIVEN_NAME = 99;
		        const int NID_SURNAME = 100;
		        const int NID_INITIALS = 101;
		        const int NID_SERIAL_NUMBER = 105;
		        const int NID_TITLE = 106;
		        const int NID_DESCRIPTION = 107;

		        const int NID_STREET_ADDRESS = 660;

		        bool partialMatch(const X509_NAME* name, const std::vector<std::shared_ptr<CertMatchType>> &certFilter);
		        bool exactMatch(const X509_NAME* name, const std::vector<std::shared_ptr<CertMatchType>> &certFilter);

		        WebSocketServerSsl::WebSocketServerSsl(std::map<std::string, std::string> &parms) :
			m_ctx(boost::asio::ssl::context::sslv23)
			{

				m_port = 0;
				m_isAlive = false;

				//for (auto elem : parms)
				//std::cout << elem.first << " -> " << elem.second << std::endl;

			        m_ctx.use_certificate_chain_file(parms["certificateStore"]);
				m_ctx.use_private_key_file(parms["keyStore"], boost::asio::ssl::context::pem);

				m_ctx.set_password_callback(
							    [&parms](std::size_t,
							       boost::asio::ssl::context_base::password_purpose)
							    {
							      std::cout << "PWD CALLBACK" << std::endl;
							      return parms["keystorePwd"];
							    });

				if (parms.find("verifyMode") != parms.end() && parms["verifyMode"] != "")
				  {
				    std::string::size_type posBegin, posEnd  = 0;
				    std::string input = parms["verifyMode"];
				    std::string delims = ",";

				    input.erase(std::remove_if(input.begin(),
							       input.end(),
							       [](char x){return std::isspace(x);}),input.end());

				    //boost::asio::ssl::verify_mode verifyMode;
				    while ((posBegin = input.find_first_not_of(delims,posEnd)) != std::string::npos)
				      {
					posEnd = input.find_first_of(delims,posBegin);
					if (posEnd == std::string::npos) posEnd = input.length();

					std::cout << '\'' << input.substr(posBegin,posEnd-posBegin) << '\'' << std::endl;

					if (input.substr(posBegin,posEnd-posBegin) == "VerifyNone")
					  m_verifyMode |= boost::asio::ssl::verify_none;
					else if (input.substr(posBegin,posEnd-posBegin) == "VerifyPeer")
					  m_verifyMode |= boost::asio::ssl::verify_peer;
					else if (input.substr(posBegin,posEnd-posBegin) == "VerifyFailIfNoPeerCert")
					  m_verifyMode |= boost::asio::ssl::verify_fail_if_no_peer_cert;
					else if (input.substr(posBegin,posEnd-posBegin) == "VerifyClientOnce")
					  m_verifyMode |= boost::asio::ssl::verify_client_once;
					else
					  {
					    throw std::invalid_argument(std::string("WebSocket Server: invalid sll verifier flag: ") + input.substr(posBegin,posEnd-posBegin));
					    break;
					  }
				      }

				    m_ctx.set_verify_mode(m_verifyMode);

				  }

				if (parms.find("certFilterMode") == parms.end())
				  m_certFilterMode = CertFilterMode::noFiltering;
				else if (parms.find("certFilterMode") != parms.end() && parms["certFilterMode"] == "")
				  m_certFilterMode = CertFilterMode::noFiltering;
				else if (parms["certFilterMode"] == "exactMatch")
				  m_certFilterMode = CertFilterMode::exactMatch;
				else if (parms["certFilterMode"] == "partialMatch")
				  m_certFilterMode = CertFilterMode::partialMatch;
				else
				  throw std::invalid_argument("WebSocketServer: invalid certFilterMode: " + parms["certFilterMode"] +
							      ". Supported values: empty/undefined, 'exactMatch', 'partialMatch'.");

				// If trustStore provided, load it.
				if (parms.find("trustStore") != parms.end() && parms["trustStore"] != "")
				  m_ctx.load_verify_file(parms["trustStore"]);
				else
				  {
				    if (m_verifyMode & boost::asio::ssl::verify_peer ||
					m_verifyMode & boost::asio::ssl::verify_fail_if_no_peer_cert ||
					m_verifyMode & boost::asio::ssl::verify_client_once)
					throw std::invalid_argument("WebSocket Server: no trustStore defined, but one of VerifyPeer, VerifyFailIfNoPeerCert or VerifyClientOnce was specified");
				  }

			} // End of constructor

			WebSocketServerSsl::~WebSocketServerSsl()
			{
				DELETEOBJ(m_io_context);
			} // End of destructor

		         void WebSocketServerSsl::open_new_cert_match()
			 {
			   m_certFilter.push_back(std::make_shared<CertMatchType>());
			 } // End of open_new_cert_match

		         void WebSocketServerSsl::add_cert_match(std::string nidStr, std::string str)
			 {

			   std::cout << "Adding cert match: " << nidStr << ": " << str << std::endl;
			   int nid;

			   if (nidStr == "commonName")
			     nid = NID_COMMON_NAME;
			   else if (nidStr == "country")
			     nid = NID_COUNTRY;
			   else if (nidStr == "locality")
			     nid = NID_LOCALITY;
			   else if (nidStr == "state")
			     nid = NID_STATE;
			   else if (nidStr == "organization")
			     nid = NID_ORGANIZATION;
			   else if (nidStr == "organizationalUnit")
			     nid = NID_ORGANIZATIONAL_UNIT;
			   else if (nidStr == "emailAddress")
			     nid = NID_EMAIL_ADDRESS;
			   else if (nidStr == "givenName")
			     nid = NID_GIVEN_NAME;
			   else if (nidStr == "surname")
			     nid = NID_SURNAME;
			   else if (nidStr == "initials")
			     nid = NID_INITIALS;
			   else if (nidStr == "serialNumber")
			     nid = NID_SERIAL_NUMBER;
			   else if (nidStr == "title")
			     nid = NID_TITLE;
			   else if (nidStr == "description")
			     nid = NID_DESCRIPTION;
			   else if (nidStr == "streetAddress")
			     nid = NID_STREET_ADDRESS;
			   else
			     {
			       throw std::invalid_argument("Unsupported certificate attribute: " + nidStr);
			     }

			   m_certFilter.back() -> push_back(std::make_tuple(nid, str));
			 } // End of add_cert_match

			void WebSocketServerSsl::listen(unsigned short port_)
			{
				auto const address = boost::asio::ip::make_address("127.0.0.1");
				m_port = port_;

				// The io_context is required for all I/O
				auto const threads = std::max<int>(1, std::atoi("1"));
				m_io_context = RJNEW boost::asio::io_context{ threads };
				m_listener = std::make_shared<WebSocketServerSslListener>(*m_io_context, std::ref(m_ctx), boost::asio::ip::tcp::endpoint(address, m_port), &m_sessions, this);

				m_listener -> set_on_accept_callback(m_serverAcceptEvent);
				m_listener -> set_on_receive_callback(m_serverReceiveEvent);

				m_listener -> run();

				/*
				WebServerThread* thread = RJNEW WebServerThread(m_io_context);
				thread->Run();
				*/

				// Just one thread now.
				for  (int i=0; i<threads; i++)
				  {
				    std::cout << "----> Thread: " << i << std::endl;
				    std::thread th{[this]
					{
					  /// @fixme If we throw and exception in any of the handlers, it will come out of m_io_context -> run()
					  try
					    {
					      m_io_context -> run();
					    }
					  catch (std::exception &e)
					    {
					      /// @fixme Exception handler here can propagate the error to JavaScript
					      std::cout << "======================= CAUGHT: " << e.what() << std::endl;
					    }
					}
				    };
				    m_IocThreads.push_back(std::move(th));
				  }

				//#ifdef GUI_USE_WXWIDGETS
				//				m_isAlive = thread->IsAlive();
				//#else
				m_isAlive = true;
				//#endif
			} // End of listen

			void WebSocketServerSsl::send(String id_, String message_)
			{
				for (const auto& s : m_sessions)
					if (s.m_session_id == id_)
					{
						s.m_session->do_write(message_);
						break;
					}
			} // End of send

		        void WebSocketServerSsl::send(String id_, const void* message_, int msg_len)
			{
				for (const auto& s : m_sessions)
					if (s.m_session_id == id_)
					{
					        s.m_session->do_write(message_, msg_len);
						break;
					}
			} // End of send

			void WebSocketServerSsl::sendToAll(String message_)
			{
				for(const auto& s: m_sessions)
					s.m_session->do_write(message_);
			} // End of sendToAll

			String WebSocketServerSsl::receive()
			{
				if (m_sessions.size() > 0)
				{
				  std::string message = m_sessions[0].m_last_message;
				  m_sessions[0].m_last_message = "";

					return message;
				}

				return String("");
			} // End of receive

			void WebSocketServerSsl::close()
			{
				m_io_context->stop();
			} // End of close

			void WebSocketServerSsl::set_on_accept_callback(v8::Persistent<v8::Function>* callback)
			{
			  m_serverAcceptEvent = callback;
			} // End of set_on_accept_callback

			void WebSocketServerSsl::set_on_receive_callback(v8::Persistent<v8::Function>* callback)
			{
			  m_serverReceiveEvent = callback;
			} // End of set_on_receive_callback

		        WebSocketServerSsl::WebSocketServerSslSession::WebSocketServerSslSession(boost::asio::ip::tcp::socket socket_,
												 boost::asio::ssl::context &context_,
												 std::string sessionID_,
												 std::vector <RadJAV::CPP::Net::WebSocketServerSsl::session_data> *sessions_,
												 WebSocketServerSsl *parent
												 )
			  : m_ws(std::move(socket_), context_), m_strand(m_ws.get_executor()), m_sessionID(sessionID_), m_sessions(sessions_), m_parent(parent)
			{

			  m_ws.next_layer().set_verify_callback([this](bool preVerified, boost::asio::ssl::verify_context& vctx) -> bool {
			      return verify_cert(preVerified, vctx);
			    });

			} // End of WebSocketServerSslSession constructor

		        bool WebSocketServerSsl::WebSocketServerSslSession::verify_cert(bool preVerified,
											boost::asio::ssl::verify_context &vctx)
			{

			  X509* cert = X509_STORE_CTX_get_current_cert(vctx.native_handle());

			  int isCa = X509_check_ca(cert);
			  std::cout << "CA status: " << isCa << std::endl << std::flush;

			  X509_NAME *name = X509_get_subject_name(cert);

			  bool certVerificationResult = true;

			  if (!isCa)
			    {

			      std::cout << "OKAY, might be doing more verification" << std::endl;

			      //certVerificationResult = false;

			      switch (m_parent -> m_certFilterMode)
				{
				case CertFilterMode::noFiltering:
				  std::cout << "########## noFiltering" << std::endl;
				  certVerificationResult = true;
				  break;

				case CertFilterMode::partialMatch:
				  std::cout << "########## partialMatch" << std::endl;
				  certVerificationResult = partialMatch(name, m_parent -> m_certFilter);
				  break;

				case CertFilterMode::exactMatch:
				  std::cout << "########## exactMatch" << std::endl;
				  certVerificationResult = exactMatch(name, m_parent -> m_certFilter);
				  break;
				}

			    }

			  return certVerificationResult;
			} // End of verify_cert

			void WebSocketServerSsl::WebSocketServerSslSession::run()
			{
			  m_ws.next_layer().async_handshake(
							    boost::asio::ssl::stream_base::server,
							    boost::asio::bind_executor(
										       m_strand,
										       std::bind(
												 &WebSocketServerSslSession::on_handshake,
												 shared_from_this(),
												 std::placeholders::_1)));
			} // End of run

		        void WebSocketServerSsl::WebSocketServerSslSession::on_handshake (boost::system::error_code ec)
			{

				if (ec)
				{

				  /// @fixme This doesn't work, we need to throw a regular exception, catch it in io_service thread, then propagate to JavaScript.
				  RadJav::throwException(ec.message());

					return;

				}

				m_ws.async_accept(
					boost::asio::bind_executor(
						m_strand,
						std::bind(
							&WebSocketServerSslSession::on_accept,
							shared_from_this(),
							std::placeholders::_1)));

			} // End of on_handshake

		        void WebSocketServerSsl::WebSocketServerSslSession::set_on_receive_callback(v8::Persistent<v8::Function>* callback)
			{
			  m_serverReceiveEvent = callback;
			} // End of set_on_receive_callback

			void WebSocketServerSsl::WebSocketServerSslSession::on_accept(boost::system::error_code ec)
			{
				if (ec)
				{
				        /// @fixme This doesn't work, we need to throw a regular exception, catch it in io_service thread, then propagate to JavaScript.
					RadJav::throwException(ec.message());

					return;
				}

				// Read a message
				do_read();
			} // End of on_accept

			void WebSocketServerSsl::WebSocketServerSslSession::do_read()
			{

				// Read a message into our buffer
				m_ws.async_read(
					m_readBuffer,
					boost::asio::bind_executor(
						m_strand,
						std::bind(
							&WebSocketServerSslSession::on_read,
							shared_from_this(),
							std::placeholders::_1,
							std::placeholders::_2)));
			} // End of do_read

			void WebSocketServerSsl::WebSocketServerSslSession::do_write(String message_)
			{
			  m_ws.text(true);
				m_activeMessage = std::make_shared<std::string>(std::move(message_));
				m_ws.async_write(
					boost::asio::buffer(*m_activeMessage),
					boost::asio::bind_executor(
						m_strand,
						std::bind(
							&WebSocketServerSslSession::on_write,
							shared_from_this(),
							std::placeholders::_1,
							std::placeholders::_2)));
			} // End of do_write

		        void WebSocketServerSsl::WebSocketServerSslSession::do_write(const void *message_, int msg_len)
			{
			  //TODO: will have to copy the message
			  m_ws.binary(true);
				m_ws.async_write(
					boost::asio::buffer(message_, msg_len),
					boost::asio::bind_executor(
						m_strand,
						std::bind(
							&WebSocketServerSslSession::on_write,
							shared_from_this(),
							std::placeholders::_1,
							std::placeholders::_2)));
			} // End of do_write

		        v8::Local<v8::Function> WebSocketServerSsl::WebSocketServerSslSession::get_on_receive_callback()
			{
			  return m_serverReceiveEvent->Get(V8_JAVASCRIPT_ENGINE->isolate);
			} // End of get_on_receive_callback

			void WebSocketServerSsl::WebSocketServerSslSession::on_read(
				boost::system::error_code ec,
				std::size_t bytes_transferred)
			{

				boost::ignore_unused(bytes_transferred);

				// This indicates that the session was closed
				if (ec == boost::beast::websocket::error::closed)
				{
					//Remove the session from the list
					for (auto it = m_sessions -> begin(); it != m_sessions -> end(); ++it)
						if (it->m_session_id == m_sessionID)
						{
							m_sessions -> erase(it);
							break;
						}

					return;
				}

				if (ec)
				{
				        /// @fixme This doesn't work, we need to throw a regular exception, catch it in io_service thread, then propagate to JavaScript.
					RadJav::throwException(ec.message());

					return;

				}

				#ifdef USE_V8

				if (m_serverReceiveEvent != nullptr)
				{
				v8::Locker myLocker(V8_JAVASCRIPT_ENGINE->isolate);
				V8_JAVASCRIPT_ENGINE->isolate -> Enter();

				v8::Local<v8::Function> evt = get_on_receive_callback();

					String id = m_sessionID.c_str();

					v8::Local<v8::Value> *args = RJNEW v8::Local<v8::Value>[2];

					args[0] = id.toV8String(V8_JAVASCRIPT_ENGINE->isolate);

					if (m_ws.got_text())
					  {
					    String message = boost::beast::buffers_to_string(m_readBuffer.data()).c_str();
					    args[1] = message.toV8String(V8_JAVASCRIPT_ENGINE->isolate);
					  }
					else
					  {
					    auto msgLen = boost::beast::buffers_front(m_readBuffer.data()).size();
					    auto message = v8::ArrayBuffer::New(V8_JAVASCRIPT_ENGINE->isolate, msgLen);
					    std::memcpy(message -> GetContents().Data(), boost::beast::buffers_front(m_readBuffer.data()).data(), msgLen);
					    args[1] = message;
					  }

					if (V8_JAVASCRIPT_ENGINE->v8IsNull(evt) == false)
						evt->Call(V8_JAVASCRIPT_ENGINE->globalContext->Global(), 2, args);

					DELETE_ARRAY(args);
				V8_JAVASCRIPT_ENGINE->isolate -> Exit();
				}
				#endif
				m_readBuffer.consume(m_readBuffer.size());
				do_read();
			}

			void WebSocketServerSsl::WebSocketServerSslSession::on_write(
				boost::system::error_code ec,
				std::size_t bytes_transferred)
			{
				boost::ignore_unused(bytes_transferred);

				if (ec)
				{
				        /// @fixme This doesn't work, we need to throw a regular exception, catch it in io_service thread, then propagate to JavaScript.
					RadJav::throwException(ec.message());

					return;
				}

			} // End of on_read

			WebSocketServerSsl::WebSocketServerSslListener::WebSocketServerSslListener(
				boost::asio::io_context& ioc_,
				std::reference_wrapper<boost::asio::ssl::context> context_,
				boost::asio::ip::tcp::endpoint endpoint_,
				std::vector <RadJAV::CPP::Net::WebSocketServerSsl::session_data> *sessions_,
				WebSocketServerSsl *parent

								  )
			  : m_acceptor(ioc_), m_ctx(context_), m_socket(ioc_), m_sessions(sessions_), m_parent(parent)

			{

				boost::system::error_code ec;

				// Open the acceptor
				m_acceptor.open(endpoint_.protocol(), ec);
				if (ec)
				{
					RadJav::throwException(ec.message());

					return;
				}

				// Allow address reuse
				m_acceptor.set_option(boost::asio::socket_base::reuse_address(true));
				if (ec)
				{
					RadJav::throwException(ec.message());

					return;
				}

				// Bind to the server address
				m_acceptor.bind(endpoint_, ec);
				if (ec)
				{
					RadJav::throwException(ec.message());

					return;
				}

				// Start listening for connections
				m_acceptor.listen(
					boost::asio::socket_base::max_listen_connections, ec);
				if (ec)
				{
					RadJav::throwException(ec.message());

					return;
				}
			} // End of WebSocketServerSslListener

		        void WebSocketServerSsl::WebSocketServerSslListener::set_on_accept_callback(v8::Persistent<v8::Function>* callback)
			{
			  m_serverAcceptEvent = callback;
			} // End of set_on_accept_callback

		        void WebSocketServerSsl::WebSocketServerSslListener::set_on_receive_callback(v8::Persistent<v8::Function>* callback)
			{
			  m_serverReceiveEvent = callback;
			} // End of set_on_receive_callback

			// Start accepting incoming connections
			void WebSocketServerSsl::WebSocketServerSslListener::run()
			{
				if (!m_acceptor.is_open())
					return;

				do_accept();
			} // End of run

			void WebSocketServerSsl::WebSocketServerSslListener::do_accept()
			{

				m_acceptor.async_accept(
					m_socket,
					std::bind(
						&WebSocketServerSslListener::on_accept,
						shared_from_this(),
						std::placeholders::_1));
			} // End of do_accept

		        v8::Local<v8::Function> WebSocketServerSsl::WebSocketServerSslListener::get_on_accept_callback()
			{

			  return v8::Local<v8::Function>::Cast(RadJAV::CPP::Net::WebSocketServerSsl::WebSocketServerSslListener::m_serverAcceptEvent->Get(V8_JAVASCRIPT_ENGINE->isolate));
			} // End of get_on_accept_callback
		        v8::Persistent<v8::Function> *WebSocketServerSsl::WebSocketServerSslListener::get_on_receive_persistent_evt()
			{

			  return m_serverReceiveEvent;
			} // get_on_receive_callback

			void WebSocketServerSsl::WebSocketServerSslListener::on_accept(boost::system::error_code ec)
			{
				if (ec)
				{
					RadJav::throwException(ec.message());

					return;
				}
				else
				{
					// Create the session and run it
					session_data this_session;

					std::string sessionId = boost::uuids::to_string(boost::uuids::random_generator()());
					auto session = std::make_shared<WebSocketServerSslSession>(std::move(m_socket), m_ctx, sessionId, m_sessions, m_parent);
					session -> set_on_receive_callback(get_on_receive_persistent_evt());

					this_session.m_session = session;
					this_session.m_session_id = sessionId;
					m_sessions -> push_back(this_session);
					session->run();

					#ifdef USE_V8
					if (m_serverAcceptEvent != nullptr)
					{
					  v8::Locker myLocker(V8_JAVASCRIPT_ENGINE->isolate);
					  V8_JAVASCRIPT_ENGINE->isolate -> Enter();

					  v8::Local<v8::Function> evt = get_on_accept_callback();

						String id = sessionId.c_str();
						v8::Local<v8::Value> *args = RJNEW v8::Local<v8::Value>[1];
						args[0] = id.toV8String(V8_JAVASCRIPT_ENGINE->isolate);

						if (V8_JAVASCRIPT_ENGINE->v8IsNull(evt) == false)
						  evt->Call(V8_JAVASCRIPT_ENGINE->globalContext->Global(), 1, args);

						DELETE_ARRAY(args);
					  V8_JAVASCRIPT_ENGINE->isolate -> Exit();

					}
					#endif

				}

				// Accept another connection
				do_accept();
			} // End of on_accept

		        bool partialMatch(const X509_NAME* name, const CertMatchType &certMatch)
			{
			  bool match = false;
			  for (int i = 0; i < X509_NAME_entry_count(name); i++)
			    {
			      X509_NAME_ENTRY *nameEntry = X509_NAME_get_entry(name, i);
			      ASN1_STRING *nameStr = X509_NAME_ENTRY_get_data(nameEntry);
			      //const unsigned char *str = ASN1_STRING_get0_data(nameStr);
			      const char *str = reinterpret_cast<const char*>(ASN1_STRING_get0_data(nameStr));

			      ASN1_OBJECT *asn1Obj = X509_NAME_ENTRY_get_object(nameEntry);

			      int attrNid = OBJ_obj2nid(asn1Obj);
			      int attrLen = ASN1_STRING_length(nameStr);

			      for (auto matchAttr : certMatch)
				{
				  std::cout << "Checking:" << std::get<1>(matchAttr) << std::endl;

				  if (attrNid == std::get<0>(matchAttr))
				    {

				      std::cout << "NID match: " << attrNid << std::endl;
				      if (attrLen == std::get<1>(matchAttr).size() &&
					  !std::strncmp(str, std::get<1>(matchAttr).c_str(), attrLen))
					{
					  match = true;
					  std::cout << "Checking the match: " << std::get<0>(matchAttr) << ':' << std::get<1>(matchAttr)
						    << " -> " << match<< std::endl;

					}
				      else
					{
					  match = false;
					  std::cout << "Checking the match: " << std::get<0>(matchAttr) << ':' << std::get<1>(matchAttr)
						    << " -> " << match<< std::endl;
					  return match;
					}
				    }

				}

			      std::cout << "N: " << ASN1_STRING_type(nameStr) << ": " << OBJ_obj2nid(asn1Obj) << ": ";
			      for (int i=0; i<ASN1_STRING_length(nameStr); i++)
				std::cout << str[i];
			      std::cout << std::endl;
			    }

			  return match;
			} // End of partialMatch

  		        bool exactMatch(const X509_NAME *name, const CertMatchType &certMatch)
			{

			  // If elements counts are different, obviously, we have no match.

			  int certAttrCount = X509_NAME_entry_count(name);
			  if (certAttrCount != certMatch.size())
			    return false;

			  // Since a certificate can have more than one organizational unit, we will tackle these separately, after parsing through other elements.
			  std::vector <std::tuple<const char*, int>> certOu;
			  std::vector <const std::string*> matchOu;

			  bool match = false;
			  for (int i = 0; i < certAttrCount; i++)
			    {
			      X509_NAME_ENTRY *nameEntry = X509_NAME_get_entry(name, i);
			      ASN1_STRING *nameStr = X509_NAME_ENTRY_get_data(nameEntry);
			      //const unsigned char *str = ASN1_STRING_get0_data(nameStr);
			      const char *str = reinterpret_cast<const char*>(ASN1_STRING_get0_data(nameStr));

			      ASN1_OBJECT *asn1Obj = X509_NAME_ENTRY_get_object(nameEntry);

			      int attrNid = OBJ_obj2nid(asn1Obj);
			      int attrLen = ASN1_STRING_length(nameStr);

			      for (auto& matchAttr : certMatch)
				{

				  std::cout << "Checking:" << std::get<1>(matchAttr) << ", Addr: "  << " -> " << &std::get<1>(matchAttr) << std::endl;

				  if (attrNid == std::get<0>(matchAttr))
				    {
				      std::cout << "NID match: " << attrNid << std::endl;

				      if (attrNid == NID_ORGANIZATIONAL_UNIT)
					{
					  certOu.push_back(std::make_tuple(str, attrLen));
					  matchOu.push_back(&std::get<1>(matchAttr));
					  std::cout << "PUSHING cert, match attributes: ";
					  std::cout.write(str, attrLen);
					  std::cout << std::get<1>(matchAttr)
						    << " -> " << &std::get<1>(matchAttr) << std::endl;
					}
				      else
					if (attrLen == std::get<1>(matchAttr).size() &&
					    !std::strncmp(str, std::get<1>(matchAttr).c_str(), attrLen))
					  {
					    match = true;
					    std::cout << "Checking the match: " << std::get<0>(matchAttr) << ':' << std::get<1>(matchAttr)
						      << " -> " << match<< std::endl;
					  }
					else
					  {
					    match = false;
					    std::cout << "Checking the match: " << std::get<0>(matchAttr) << ':' << std::get<1>(matchAttr)
						      << " -> " << match<< std::endl;
					    return match;
					  }
				    }

				}

			      std::cout << "N: " << ASN1_STRING_type(nameStr) << ": " << OBJ_obj2nid(asn1Obj) << ": ";
			      for (int i=0; i<ASN1_STRING_length(nameStr); i++)
				std::cout << str[i];
			      std::cout << std::endl;
			    }

			  std::cout << "PHASE 2: " << certOu.size() << ", " << matchOu.size() << std::endl;

			  for (auto certOuAttr = certOu.begin(); certOuAttr != certOu.end(); )
			    {
			      int certOuSize = certOu.size();
			      for (auto matchOuAttr = matchOu.begin(); matchOuAttr != matchOu.end(); )
				{
				  std::cout << "Comparing OU: ";
				  std::cout.write(std::get<0>(*certOuAttr), std::get<1>(*certOuAttr));
				  std::cout << " <-> " << **matchOuAttr << std::endl;

				  // Comparison.
				  if (std::get<1>(*certOuAttr) == (*matchOuAttr) -> size() &&
				      !std::strncmp(std::get<0>(*certOuAttr), (*matchOuAttr) -> c_str(), std::get<1>(*certOuAttr)))
				    {
				      //std::cout << "Erasing: " << *certOuAttr << ", " << *matchOuAttr << std::endl;
				      certOuAttr = certOu.erase(certOuAttr);
				      matchOuAttr = matchOu.erase(matchOuAttr);
				    }
				  else
				    {
				      ++matchOuAttr;
				      if (matchOuAttr != matchOu.end())
					std::cout << "will try matchOuAttr = " << **matchOuAttr << std::endl;
				      else
					std::cout << "matchOu loop done" << std::endl;

				    }
				}
			      if (matchOu.size() && certOu.size() == certOuSize && certOuAttr != certOu.end() )
				++certOuAttr;

			      std::cout << "Still here" << std::endl;
			    }

			  if (certOu.size() || matchOu.size())
			    match = false;
			  else
			    match = true;

			  return match;
			} // End of exactmatch

		        bool partialMatch(const X509_NAME* name, const std::vector<std::shared_ptr<CertMatchType>> &certFilter)
			{

			  // If any of the patterns matches, return success, otherwise return failure (false)
			  for (auto certMatch : certFilter)
			    {
			      if (partialMatch(name, *certMatch))
				return true;
			    }
			  return false;
			} // End of partialMatch

		        bool exactMatch(const X509_NAME* name, const std::vector<std::shared_ptr<CertMatchType>> &certFilter)
			{
			  // If any of the patterns matches, return success, otherwise return failure (false)
			  for (auto certMatch : certFilter)
			    {
			      if (exactMatch(name, *certMatch.get()))
				return true;
			    }
			  return false;
			} // End of exactMatch

		} // namespace Net
	} // namespace CPP
} // namespace RadJav

max_stars_repo_name: FogChainInc/RadJavPrivate

max_issues_repo_name: FogChainInc/RadJavPrivate

max_forks_repo_name: FogChainInc/RadJavPrivate


text:
// Copyright (c) 2019-2021 The Bigbang developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <boost/test/unit_test.hpp>

#include "address.h"
#include "block.h"
#include "test_big.h"
#include "timeseries.h"

using namespace std;
using namespace xengine;
using namespace bigbang;
using namespace bigbang::storage;
using namespace boost::filesystem;

BOOST_FIXTURE_TEST_SUITE(storage_tests, BasicUtfSetup)

// basic config
const uint32 nMagicNum = 0x5E33A1EF;

BOOST_AUTO_TEST_CASE(filetest)
{
    cout << GetLocalTime() << "  file test.........." << endl;
    int64 nBeginTime = GetTime();

    std::string fullpath = boost::filesystem::initial_path<boost::filesystem::path>().string() + "/test/block/block_000001.dat";
    std::cout << "block file path: " << fullpath << std::endl;

    try
    {
        xengine::CFileStream fs(fullpath.c_str());
        fs.Seek(0);

        uint32 nOffset = 0;
        uint32 nBlockCount = 0;

        while (!fs.IsEOF())
        {
            cout << "file test: nBlockCount: " << nBlockCount << endl;
            uint32 nMagic, nSize;
            CBlockEx t;
            try
            {
                fs >> nMagic >> nSize >> t;
            }
            catch (const std::exception& e)
            {
                break;
            }
            cout << "nMagic error, nMagic: " << nMagic << ", nMagicNum: " << nMagicNum << ", GetCurPos: " << fs.GetCurPos() << ", nOffset: " << nOffset << ", nSize: " << nSize << endl;
            BOOST_CHECK(nMagic == nMagicNum);
            BOOST_CHECK(fs.GetCurPos() - nOffset - 8 == nSize);
            nOffset = fs.GetCurPos();
            nBlockCount++;
        }
        cout << GetLocalTime() << " file test success: nBlockCount: " << nBlockCount << ", time: " << GetTime() - nBeginTime << endl;
        BOOST_CHECK(nBlockCount == 11);
    }
    catch (const std::exception& e)
    {
        BOOST_FAIL(e.what());
    }
}

#define BLOCKFILE_PREFIX "block"

class CMyBlockWalker : public CTSWalker<CBlockEx>
{
public:
    CMyBlockWalker()
      : nBlockCount(0) {}
    ~CMyBlockWalker() {}

    bool Walk(const CBlockEx& block, uint32 nFile, uint32 nOffset) override
    {
        nBlockCount++;
        return true;
    }

public:
    int nBlockCount;
};

BOOST_AUTO_TEST_CASE(timewalk)
{
    CTimeSeriesCached tsBlock;
    if (!tsBlock.Initialize(path("./.bigbang") / "block", BLOCKFILE_PREFIX))
    {
        BOOST_FAIL("Initialize fail");
    }

    cout << GetLocalTime() << "  WalkThrough start...." << endl;

    uint32 nLastFileRet = 0;
    uint32 nLastPosRet = 0;
    CMyBlockWalker walker;
    BOOST_CHECK(tsBlock.WalkThrough(walker, nLastFileRet, nLastPosRet, false));
    cout << GetLocalTime() << "  WalkThrough success, count: " << walker.nBlockCount << endl;
}

BOOST_AUTO_TEST_CASE(fileread)
{
    cout << GetLocalTime() << "  start...." << endl;

    std::string fullpath = boost::filesystem::initial_path<boost::filesystem::path>().string() + "/test/block/block_000001.dat";
    std::cout << "block file path: " << fullpath << std::endl;

    FILE* f = fopen(fullpath.c_str(), "rb");
    BOOST_CHECK(f != nullptr);
    fseek(f, 0, SEEK_END);
    int filesize = ftell(f);
    cout << GetLocalTime() << "  filesize: " << filesize << endl;
    fseek(f, 0, SEEK_SET);

    uint32 nDataLen = 0;
    uint8* pBuf = (uint8*)malloc(filesize);
    BOOST_CHECK(pBuf != nullptr);
    uint8* pos = pBuf;
    while (!feof(f))
    {
        int sylen = filesize - nDataLen;
        if (sylen > 1024 * 1024 * 4)
        {
            sylen = 1024 * 1024 * 4;
        }
        else
        {
            if (sylen <= 0)
            {
                break;
            }
        }
        size_t nLen = fread(pos, 1, sylen, f);
        if (nLen > 0)
        {
            nDataLen += nLen;
            pos += nLen;
        }
    }
    fclose(f);
    cout << GetLocalTime() << "  read end, nDataLen: " << nDataLen << endl;

    CBufStream is;
    is.Write((const char*)pBuf, nDataLen);

    int nBlockCount = 0;
    uint32 nSyDataLen = nDataLen;
    while (nSyDataLen > 0)
    {
        uint32 nMagic, nSize;
        CBlockEx t;
        try
        {
            is >> nMagic >> nSize >> t;
        }
        catch (std::exception& e)
        {
            break;
        }
        nBlockCount++;
        nSyDataLen -= (nSize + 8);
    }
    cout << GetLocalTime() << "  data end, nDataLen: " << nDataLen << ", nBlockCount: " << nBlockCount << ", nSyDataLen: " << nSyDataLen << endl;
    BOOST_CHECK(nBlockCount == 11);
    free(pBuf);
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: BigBang-Foundation/BigBang

max_issues_repo_name: BigBang-Foundation/BigBang

max_forks_repo_name: BigBang-Foundation/BigBang


text:
#include "stdafx.h"

#include <boost\test\unit_test.hpp>

#include <boost\gil\extension\opencv\opencv_all.hpp>

#include <boost\gil\extension\io_new\png_all.hpp>

using namespace boost::gil;
using namespace boost::gil::opencv;

BOOST_AUTO_TEST_CASE( test_convert_scale )
{
    rgb32f_image_t src( 640, 480 );
    fill_pixels( view( src ), rgb32f_pixel_t( 1000.0, 0.0, 34.0 ) );

    rgb16_image_t dst( view( src ).dimensions() );

    convert_scale( view( src )
                 , view( dst )
                 );

    write_view( "..\\out\\convert_scale.png", view( dst ), png_tag() );
}

BOOST_AUTO_TEST_CASE( test_convert_scale_abs )
{
    rgb32f_image_t src( 640, 480 );
    fill_pixels( view( src ), rgb32f_pixel_t( 1000.0, 0.0, 34.0 ) );

    rgb8_image_t dst( view( src ).dimensions() );

    convert_scale( view( src )
                 , view( dst )
                 );

    write_view( "..\\out\\convert_scale_abs.png", view( dst ), png_tag() );
}

max_stars_repo_name: boost-gil/gil-contributions

max_issues_repo_name: boost-gil/gil-contributions-archive

max_forks_repo_name: boost-gil/gil-contributions-archive


text:
/*
 Copyright (C) GridGain Systems. All Rights Reserved.

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

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

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

/*  _________        _____ __________________        _____
 *  __  ____/___________(_)______  /__  ____/______ ____(_)_______
 *  _  / __  __  ___/__  / _  __  / _  / __  _  __ `/__  / __  __ \
 *  / /_/ /  _  /    _  /  / /_/ /  / /_/ /  / /_/ / _  /  _  / / /
 *  \____/   /_/     /_/   \_,__/   \____/   \__,_/  /_/   /_/ /_/
 */
#include "gridgain/impl/utils/gridclientdebug.hpp"

#include <algorithm>

#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/uuid/uuid_io.hpp>

#include "gridgain/impl/gridclientimpl.hpp"
#include "gridgain/impl/gridclientdataprojection.hpp"
#include "gridgain/impl/gridclientcomputeprojection.hpp"
#include "gridgain/impl/cmd/gridclientcommandexecutor.hpp"
#include "gridgain/impl/marshaller/gridnodemarshallerhelper.hpp"
#include "gridgain/gridclientexception.hpp"
#include "gridgain/gridclienttopologylistener.hpp"
#include "gridgain/gridclientnode.hpp"

#include "gridgain/impl/utils/gridclientlog.hpp"

/**
 * Public constructor.
 */
GridClientImpl::GridClientImpl(const GridClientConfiguration& cfg,
        std::shared_ptr<GridClientCommandExecutorPrivate>& exec)
        : sharedData(new GridClientSharedData(cfg.protocolConfiguration().uuid(), cfg, exec))
           ,topRefresher(new GridClientTopologyRefresher(cfg.topologyRefreshFrequency(), *this))
           ,threadPool(new GridThreadPool(cfg.threadPoolSize())) {
    // Check configuration sanity
    if (!cfg.servers().empty() && !cfg.routers().empty())
        throw GridClientException("Both servers and routers are specified in configuration, which is not allowed.");

    TGridClientTopologyListenerList topLsnrs = cfg.topologyListeners();

    for (auto i = topLsnrs.begin(); i != topLsnrs.end(); i++)
        addTopologyListener(*i);

    // Refresh the topology based on new data.
    refreshTopology();
}

/**
 * Gets a unique client identifier. This identifier is generated by factory on client creation
 * and used in identification and authentication procedure on server node.
 *
 * @return Generated client id.
 */
GridClientUuid GridClientImpl::id() const {
    return getSharedData()->clientUuid();
}

/**
 * Gets a data projection for a default grid cache with {@code null} name.
 *
 * @return Data projection for grid cache with {@code null} name.
 * @throw GridClientException If client was closed.
 */
TGridClientDataPtr GridClientImpl::data() {
    return getOrCreateDataProjection("");
}

/**
 * Gets a data projection for grid cache with name <tt>cacheName</tt>. If
 * no data configuration with given name was provided at client startup, an
 * exception will be thrown.
 *
 * @param cacheName Grid cache name for which data projection should be obtained.
 * @return Data projection for grid cache with name <tt>cacheName</tt>.
 * @throw GridClientException If client was closed or no configuration with given name was provided.
 */
TGridClientDataPtr GridClientImpl::data(const std::string& cacheName) {
    return getOrCreateDataProjection(cacheName);
}

/**
 * Gets a default compute projection. Default compute projection will include all nodes
 * in remote grid. Selection of node that will be connected to perform operations will be
 * done according to {@link GridClientLoadBalancer} provided in client configuration or
 * according to affinity if projection call involves affinity key.
 * <p>
 * More restricted projection configurations may be created with {@link GridClientCompute} methods.
 *
 * @return Default compute projection.
 *
 * @see GridClientCompute
 */
TGridClientComputePtr GridClientImpl::compute() {
    if (mainComputePrj.get() == NULL) {
        TGridClientSharedDataPtr sd = getSharedData();

        GridClientComputeProjectionImpl* p = new GridClientComputeProjectionImpl(sd, *this, TGridClientNodePredicatePtr(),
                TGridClientLoadBalancerPtr(), threadPool);

        mainComputePrj.reset(p);
    }

    return mainComputePrj;
}

/**
 * Adds topology listener. Remote grid topology is refreshed every
 * {@link GridClientConfiguration#getTopologyRefreshFrequency()} milliseconds. If any node was added or removed,
 * a listener will be notified.
 *
 * @param lsnr Listener to add.
 */
void GridClientImpl::addTopologyListener(TGridClientTopologyListenerPtr lsnr) {
    boost::lock_guard<boost::mutex> g(topLsnrsMux);

    topLsnrs.push_back(lsnr);
}

/**
 * Removes previously added topology listener.
 *
 * @param lsnr Listener to remove.
 */
void GridClientImpl::removeTopologyListener(TGridClientTopologyListenerPtr lsnr) {
    boost::lock_guard<boost::mutex> g(topLsnrsMux);

    topLsnrs.erase(std::find(topLsnrs.begin(), topLsnrs.end(), lsnr));
}

/**
 * Gets an unmodifiable snapshot of topology listeners list.
 *
 * @return List of topology listeners.
 */
TGridClientTopologyListenerListPtr GridClientImpl::topologyListeners() const {
    boost::lock_guard<boost::mutex> g(topLsnrsMux);

    TGridClientTopologyListenerList *l = new TGridClientTopologyListenerList(topLsnrs);

    return TGridClientTopologyListenerListPtr(l);
}

/**
 * This method creates the data-projection if an user has not created
 * the projection by the particular cache name.
 * @param cacheName std::string - The name of the particular cache.
 */
TGridClientDataPtr GridClientImpl::getOrCreateDataProjection(std::string cacheName) {
    TGridClientDataPtr clientData;

    TDataPrjMap::const_iterator itPrj = mainDataPrjs.find(cacheName);

    if (itPrj != mainDataPrjs.end())
        clientData = itPrj->second;
    else {
        std::shared_ptr<GridClientDataProjectionImpl> prjImpl =
            std::shared_ptr<GridClientDataProjectionImpl>(
                new GridClientDataProjectionImpl(
                    getSharedData(),
                    *this,
                    cacheName,
                    TGridClientNodePredicatePtr((TGridClientNodePredicate*)NULL),
                    threadPool,
                    std::set<GridClientCacheFlag>()));
        clientData = prjImpl;

        mainDataPrjs.insert(std::make_pair(cacheName, prjImpl));
    }

    return clientData;
}

void GridClientImpl::stop(bool pWait) {
    topRefresher.reset(); // Destroy the topology refersher and thus stop the refresher thread.

    //invalidate all client data
    for(auto i = mainDataPrjs.begin(); i != mainDataPrjs.end(); i++)
        i->second->invalidate();

    // Invalidate compute projection.
    if (mainComputePrj.get() != NULL)
        mainComputePrj->invalidate();

    if (!pWait)
        sharedData->executor()->stop();

    // Shut down the thread pool.
    GG_LOG_DEBUG0("Stopping the thread pool.");
    threadPool->shutdown();
}

void GridClientImpl::onNodeIoFailed(const GridClientNode& n) {
    GG_LOG_DEBUG("Node IO failed: %s", n.getNodeId().uuid().c_str());

    refreshTopology();
}

void GridClientImpl::refreshTopology() {
    const GridClientConfiguration& clientCfg = sharedData->clientConfiguration();
    TGridClientSocketAddressList addrs = clientCfg.routers().size() > 0
            ? clientCfg.routers()
            : clientCfg.servers();

    if (addrs.empty()) {
        GG_LOG_DEBUG0("Skipping topology refresh (address list is empty).");

        return;
    }

    TGridClientCommandExecutorPtr exec = sharedData->executor();
    bool updated = false;

    GG_LOG_DEBUG0("Started refreshing the topology.");

    GridClientException last;

    for (auto it = addrs.begin(); !updated && it != addrs.end(); ++it) {
        try {
            GG_LOG_DEBUG("Refresh address: %s", it->host().c_str());

            GridTopologyRequestCommand topRqst;
            GridClientMessageTopologyResult rslt;
            TNodesSet nodes;

            // Fills the command by the default value.
            topRqst.setIncludeAttributes(false);
            topRqst.setIncludeMetrics(false);
            topRqst.setClientId(id().uuid());

            topRqst.setRequestId(topRqst.generateNewId());

            // Executes the topology command.
            exec->executeTopologyCmd(*it, topRqst, rslt);

            TNodesList nbns = rslt.getNodes();

            // Extract the actual list of nodes.
            nodes.insert(nbns.begin(), nbns.end());

            TNodesSet prevNodes = sharedData->topology()->nodes();

            // Update the topology.
            sharedData->topology()->update(nodes);

            fireTopologyEvents(nodes, prevNodes);

            GG_LOG_DEBUG("Topology size: %d", nodes.size());

            updated = true;
        }
        catch (GridClientException& e) {
        	last = e;
        }
    }

    if (!updated)
        GG_LOG_ERROR("Error refreshing the topology: %s", last.what());

    GG_LOG_DEBUG0("Finished refreshing the topology.");
}

void GridClientImpl::fireTopologyEvents(const TNodesSet& updNodes, const TNodesSet& prevNodes) {
    ClientNodeComparator nodeComp;

    TNodesSet newNodes;

    // Calculate new nodes.
    std::set_difference(updNodes.begin(), updNodes.end(), prevNodes.begin(), prevNodes.end(),
            std::inserter(newNodes, newNodes.begin()), nodeComp);

    // File onNodeAdded() events.
    for (auto i = newNodes.begin(); i != newNodes.end(); i++)
        fireNodeAdded(*i);

    TNodesSet leftNodes;

    // Calculate left nodes.
    std::set_difference(prevNodes.begin(), prevNodes.end(), updNodes.begin(), updNodes.end(),
            std::inserter(leftNodes, leftNodes.begin()), nodeComp);

    // Fire onNodeRemoved() events.
    for (auto i = leftNodes.begin(); i != leftNodes.end(); i++)
        fireNodeRemoved(*i);
}

void GridClientImpl::fireNodeAdded(const GridClientNode& node) {
    topLsnrsMux.lock();

    TGridClientTopologyListenerList locTopLsnrs = topLsnrs;

    topLsnrsMux.unlock();

    GG_LOG_DEBUG("Firing node added for node: %s", node.getNodeId().uuid().c_str());

    for (auto i = locTopLsnrs.begin(); i != locTopLsnrs.end(); i++) {
        TGridClientTopologyListenerPtr l = *i;

        try {
            l->onNodeAdded(node);
        }
        catch(std::exception& e) {
            GG_LOG_ERROR("Got exception from topology listener [what=%s]", e.what());
        }
        catch(...) {
            GG_LOG_ERROR0("Got unknown exception from topology listener.");
        }
    }
}

void GridClientImpl::fireNodeRemoved(const GridClientNode& node) {
    topLsnrsMux.lock();

    TGridClientTopologyListenerList locTopLsnrs = topLsnrs;

    topLsnrsMux.unlock();

    GG_LOG_DEBUG("Firing node left for node: %s", node.getNodeId().uuid().c_str());

    for (auto i = locTopLsnrs.begin(); i != locTopLsnrs.end(); i++) {
        TGridClientTopologyListenerPtr l = *i;

        try {
            l->onNodeRemoved(node);
        }
        catch(std::exception& e) {
            GG_LOG_ERROR("Got exception from topology listener [what=%s]", e.what());
        }
        catch(...) {
            GG_LOG_ERROR0("Got unknown exception from topology listener.");
        }
    }
}

void GridClientImpl::GridClientTopologyRefresher::onTimerEvent() {
    GG_LOG_DEBUG0("Timer event.");

    client.refreshTopology();
}

max_stars_repo_name: cybernetics/gridgain

max_issues_repo_name: cybernetics/gridgain

max_forks_repo_name: cybernetics/gridgain


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

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include "test_util.h"
#include "logger.h"

#include "ctx_internal.h"
#include "cluster_config.h"
#include "rpc_service.h"
#include "temp_path.h"

#include <boost/test/unit_test.hpp>

#include <vector>

using std::string;
using std::vector;
using std::unique_ptr;
using namespace throng;
using internal::node_client_t;

LOGGER("test.ctx");

BOOST_AUTO_TEST_SUITE(ctx_test)

BOOST_AUTO_TEST_CASE(connect) {
    throng::test::temp_dir storage;
    using internal::cluster_config_p;
    using internal::cluster_config;

    std::vector<node_id> nids { {1,1}, {1,2}, {1,3}, {2,1} };
    std::vector<std::unique_ptr<ctx>> ctxs;

    ctxs.push_back(ctx::new_ctx((storage.path() / "n1").string()));
    ctxs.push_back(ctx::new_ctx((storage.path() / "n2").string()));
    ctxs.push_back(ctx::new_ctx((storage.path() / "n3").string()));
    ctxs.push_back(ctx::new_ctx((storage.path() / "n4").string()));

    ctxs[0]->configure_local(nids[0], "127.0.0.1", 17171);
    ctxs[1]->configure_local(nids[1], "127.0.0.1", 17172);
    ctxs[2]->configure_local(nids[2], "127.0.0.1", 17173, false);
    ctxs[3]->configure_local(nids[3], "127.0.0.1", 17174);

    for (size_t i = 0; i < ctxs.size(); i++) {
        auto& c = ctxs[i];
        c->register_store("test");
        auto nc = node_client_t::new_store_client(*c, internal::NODE_STORE);
        message::node n;
        n.set_hostname("127.0.0.1");

        for (size_t j = 0; j < ctxs.size(); j++) {
            n.set_port(17171 + j);
            n.set_master_eligible(j != 2);

            n.clear_id();
            auto id = n.mutable_id();
            for (auto lid : ctxs[j]->get_local_node_id())
                id->add_id(lid);

            auto v = nc->get(n.id());
            nc->update(n.id(), v, n);
        }
    }

    std::shared_ptr<cluster_config> config0(new cluster_config());
    std::shared_ptr<cluster_config> config1(new cluster_config());

    cluster_config::neigh_p neigh_(new message::neighborhood());
    neigh_->mutable_prefix();
    auto master = neigh_->add_masters();
    for (auto i : nids[0])
        master->add_id(i);
    master = neigh_->add_masters();
    for (auto i : nids[3])
        master->add_id(i);

    cluster_config::neigh_p neigh_0(new message::neighborhood());
    auto prefix = neigh_0->mutable_prefix();
    prefix->add_id(1);
    master = neigh_0->add_masters();
    for (auto i : nids[0])
        master->add_id(i);
    master = neigh_0->add_masters();
    for (auto i : nids[1])
        master->add_id(i);

    cluster_config::neigh_p neigh_1(new message::neighborhood());
    prefix = neigh_1->mutable_prefix();
    prefix->add_id(2);
    master = neigh_1->add_masters();
    for (auto i : nids[3])
        master->add_id(i);

    config0->add_neighborhood(neigh_);
    config0->add_neighborhood(neigh_0);
    config1->add_neighborhood(neigh_);
    config1->add_neighborhood(neigh_1);

    dynamic_cast<internal::ctx_internal*>(ctxs[0].get())
        ->set_static_config(config0);
    dynamic_cast<internal::ctx_internal*>(ctxs[1].get())
        ->set_static_config(config0);
    dynamic_cast<internal::ctx_internal*>(ctxs[2].get())
        ->set_static_config(config0);
    dynamic_cast<internal::ctx_internal*>(ctxs[3].get())
        ->set_static_config(config1);

    for (auto& c : ctxs)
        c->start();

    auto ctx_check = [](ctx* c, node_id& nid) -> bool {
        return (dynamic_cast<internal::ctx_internal*>(c)
                ->get_rpc_service().is_ready(nid));
    };
    auto check_ready = [&ctxs, &nids, &ctx_check]() -> bool {
        if (!ctx_check(ctxs[0].get(), nids[1]) ||
            !ctx_check(ctxs[0].get(), nids[2]) ||
            !ctx_check(ctxs[0].get(), nids[3]) ||
            !ctx_check(ctxs[1].get(), nids[0]) ||
            !ctx_check(ctxs[1].get(), nids[2]) ||
            !ctx_check(ctxs[2].get(), nids[0]) ||
            !ctx_check(ctxs[2].get(), nids[1]) ||
            !ctx_check(ctxs[3].get(), nids[0]))
            return false;
        return true;
    };
    WAIT_FOR(check_ready(), 500);

    for (auto& c : ctxs)
        c->stop();
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: readams/throng

max_issues_repo_name: readams/throng

max_forks_repo_name: readams/throng


text:
/*
 * PolynomialSplineVectorSpaceCurve.hpp
 *
 *  Created on: Mar 6, 2015
 *      Author: Péter Fankhauser
 *   Institute: ETH Zurich, Autonomous Systems Lab
 */

#pragma once

#include <string>
#include <vector>
#include <Eigen/Core>
#include <glog/logging.h>

#include "curves/Curve.hpp"
#include "curves/VectorSpaceCurve.hpp"
#include "curves/PolynomialSplineContainer.hpp"

namespace curves {

template<typename SplineType, int N>
class PolynomialSplineVectorSpaceCurve : public VectorSpaceCurve<N>
{
 public:
  typedef VectorSpaceCurve<N> Parent;
  typedef typename Parent::ValueType ValueType;
  typedef typename Parent::DerivativeType DerivativeType;

  PolynomialSplineVectorSpaceCurve()
      : VectorSpaceCurve<N>(),
        minTime_(0)
  {
    containers_.resize(N);
  }

  virtual ~PolynomialSplineVectorSpaceCurve()
  {
  }

  virtual void print(const std::string& str = "") const
  {
  }

  virtual Time getMinTime() const
  {
    return minTime_;
  }

  virtual Time getMaxTime() const
  {
    return containers_.at(0).getContainerDuration();
  }

  virtual bool evaluate(ValueType& value, Time time) const
  {
    for (size_t i = 0; i < N; ++i) {
      value(i) = containers_.at(i).getPositionAtTime(time);
    }
    return true;
  }

  virtual bool evaluateDerivative(DerivativeType& value, Time time, unsigned derivativeOrder) const
  {

    for (size_t i = 0; i < N; ++i) {
      if (derivativeOrder == 1) {
        value(i) = containers_.at(i).getVelocityAtTime(time);
      }
      else if (derivativeOrder == 2) {
        value(i) = containers_.at(i).getAccelerationAtTime(time);
      }
      else {
        return false;
      }
    }
    return true;
  }

  virtual void extend(const std::vector<Time>& times, const std::vector<ValueType>& values,
                      std::vector<Key>* outKeys)
  {
    throw std::runtime_error("PolynomialSplineVectorSpaceCurve::extend is not yet implemented!");
  }

  virtual void fitCurve(const std::vector<Time>& times, const std::vector<ValueType>& values,
                        std::vector<Key>* outKeys = NULL)
  {
    minTime_ = times.front();
    for (size_t i = 0; i < N; ++i) {
      std::vector<double> scalarValues;
      scalarValues.reserve(times.size());
      for (size_t t = 0; t < times.size(); ++t) scalarValues.push_back(values.at(t)(i));
      containers_.at(i).setData(times, scalarValues, 0.0, 0.0, 0.0, 0.0);
    }
  }

  virtual void fitCurve(const std::vector<Time>& times,
                        const std::vector<ValueType>& values,
                        const DerivativeType& initialVelocity,
                        const DerivativeType& initialAcceleration,
                        const DerivativeType& finalVelocity,
                        const DerivativeType& finalAcceleration)
  {
    minTime_ = times.front();
    for (size_t i = 0; i < N; ++i) {
      std::vector<double> scalarValues;
      scalarValues.reserve(times.size());
      for (size_t t = 0; t < times.size(); ++t) scalarValues.push_back(values.at(t)(i));
      containers_.at(i).setData(times, scalarValues, initialVelocity(i), initialAcceleration(i),
                                finalVelocity(i), finalAcceleration(i));
    }
  }

  virtual void fitCurve(const std::vector<Time>& times, const std::vector<ValueType>& values,
                        const std::vector<DerivativeType>& firstDerivatives,
                        const std::vector<DerivativeType>& secondDerivatives,
                        std::vector<Key>* outKeys = NULL)
  {
    minTime_ = times.front();
    for (size_t i = 0; i < N; ++i) {
      std::vector<double> scalarValues, scalarFirstDerivates, scalarSecondDerivates;
      scalarValues.reserve(times.size());
      for (size_t t = 0; t < times.size(); ++t) {
        scalarValues.push_back(values.at(t)(i));
        scalarFirstDerivates.push_back(firstDerivatives.at(t)(i));
        scalarSecondDerivates.push_back(secondDerivatives.at(t)(i));
      }
      // TODO Copy all derivates, right now only first and last are supported.
      containers_.at(i).setData(times, scalarValues,
                                *(scalarFirstDerivates.begin()), *(scalarSecondDerivates.begin()),
                                *(scalarFirstDerivates.end() - 1), *(scalarSecondDerivates.end() - 1));
    }
  }

  virtual void fitCurve(const std::vector<SplineOptions>& values,
                        std::vector<Key>* outKeys = NULL)
  {
    // TODO
    throw std::runtime_error("PolynomialSplineVectorSpaceCurve::fitCurve is not yet implemented!");
  }

  virtual void clear()
  {
    for (size_t i = 0; i < N; ++i) {
      containers_.at(i).reset();
    }
  }

  virtual void transformCurve(const ValueType T)
  {
    CHECK(false) << "Not implemented";
  }

 private:
  std::vector<PolynomialSplineContainer> containers_;
  Time minTime_;
};

typedef PolynomialSplineVectorSpaceCurve<PolynomialSplineQuintic, 3> PolynomialSplineQuinticVector3Curve;

} // namespace

max_stars_repo_name: frontw/curves


text:
//==============================================================================
//         Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II
//         Copyright 2009 - 2011 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 BOOST_SIMD_TOOLBOX_ARITHMETIC_FUNCTIONS_SIMD_COMMON_IDIVFLOOR_HPP_INCLUDED
#define BOOST_SIMD_TOOLBOX_ARITHMETIC_FUNCTIONS_SIMD_COMMON_IDIVFLOOR_HPP_INCLUDED

#include <boost/simd/toolbox/arithmetic/functions/idivfloor.hpp>
#include <boost/simd/include/functions/simd/idivceil.hpp>
#include <boost/simd/include/functions/simd/toint.hpp>
#include <boost/simd/include/functions/simd/divides.hpp>
#include <boost/simd/include/functions/simd/floor.hpp>
#include <boost/simd/include/functions/simd/negate.hpp>

namespace boost { namespace simd { namespace ext
{
  BOOST_SIMD_FUNCTOR_IMPLEMENTATION( boost::simd::tag::idivfloor_, tag::cpu_
                            , (A0)(X)
                            , ((simd_<arithmetic_<A0>,X>))((simd_<arithmetic_<A0>,X>))
                            )
  {
    typedef A0 result_type;
    BOOST_SIMD_FUNCTOR_CALL_REPEAT(2)
    { return -idivceil(-a0,a1); }
  };

  BOOST_SIMD_FUNCTOR_IMPLEMENTATION( boost::simd::tag::idivfloor_, tag::cpu_
                            , (A0)(X)
                            , ((simd_<unsigned_<A0>,X>))((simd_<unsigned_<A0>,X>))
                            )
  {
    typedef A0 result_type;
    BOOST_SIMD_FUNCTOR_CALL_REPEAT(2)
    { return rdivide(a0,a1); }
  };

  BOOST_SIMD_FUNCTOR_IMPLEMENTATION( boost::simd::tag::idivfloor_, tag::cpu_
                            , (A0)(X)
                            , ((simd_<floating_<A0>,X>))((simd_<floating_<A0>,X>))
                            )
  {
    typedef typename dispatch::meta::as_integer<A0>::type result_type;
    BOOST_SIMD_FUNCTOR_CALL_REPEAT(2)
    { return toint(floor(a0/a1)); }
  };
} } }

#endif


text:
//
// Copyright (c) 2016-2018 CNRS
//

#ifndef __pinocchio_check_hpp__
#define __pinocchio_check_hpp__

#include "pinocchio/multibody/model.hpp"
#include "pinocchio/multibody/data.hpp"
#include <boost/fusion/container/list.hpp>
#include <boost/fusion/container/generation/make_list.hpp>

#ifndef PINOCCHIO_ALGO_CHECKER_LIST_MAX_LIST_SIZE
#define PINOCCHIO_ALGO_CHECKER_LIST_MAX_LIST_SIZE 5
#endif

namespace pinocchio
{

  /// CRTP class describing the API of the checkers
  template<typename AlgorithmCheckerDerived>
  struct AlgorithmCheckerBase
  {
    inline AlgorithmCheckerDerived&       derived()
    { return *static_cast<      AlgorithmCheckerDerived*>(this); }

    inline const AlgorithmCheckerDerived& derived() const
    { return *static_cast<const AlgorithmCheckerDerived*>(this); }

    template<typename Scalar, int Options, template<typename,int> class JointCollectionTpl>
    inline bool checkModel(const ModelTpl<Scalar,Options,JointCollectionTpl> & model) const
    { return derived().checkModel_impl(model); }
  };

#define DEFINE_ALGO_CHECKER(NAME)                                           \
  struct NAME##Checker : public AlgorithmCheckerBase<NAME##Checker>         \
  {                                                                         \
    template<typename Scalar, int Options, template<typename,int> class JointCollectionTpl>                                      \
    inline bool checkModel_impl(const ModelTpl<Scalar,Options,JointCollectionTpl> &) const;   \
  }

  /// Simple model checker, that assert that model.parents is indeed a tree.
  DEFINE_ALGO_CHECKER(Parent);

#if !defined(BOOST_FUSION_HAS_VARIADIC_LIST)
  /// Checker having a list of Checker as input argument
  template<BOOST_PP_ENUM_PARAMS_WITH_A_DEFAULT(PINOCCHIO_ALGO_CHECKER_LIST_MAX_LIST_SIZE,class D,boost::fusion::void_)>
  struct AlgorithmCheckerList: AlgorithmCheckerBase< AlgorithmCheckerList<BOOST_PP_ENUM_PARAMS(PINOCCHIO_ALGO_CHECKER_LIST_MAX_LIST_SIZE,D)> >
  {
    typedef typename boost::fusion::list<BOOST_PP_ENUM_PARAMS(PINOCCHIO_ALGO_CHECKER_LIST_MAX_LIST_SIZE,D)> ArgType;

    AlgorithmCheckerList(const ArgType & checkerList)
    : checkerList(checkerList) {}

    // Calls model.check for each checker in the fusion::list.
    // Each list element is supposed to implement the AlgorithmCheckerBase API.
    template<typename Scalar, int Options, template<typename,int> class JointCollectionTpl>
    bool checkModel_impl(const ModelTpl<Scalar,Options,JointCollectionTpl> & model) const;

    const ArgType & checkerList;
  };

#define MAKE_ALGO_CHECKER_LIST(z,n,_) \
  /**/ \
  template<BOOST_PP_ENUM_PARAMS(BOOST_PP_INC(n),class D)> \
  AlgorithmCheckerList<BOOST_PP_ENUM_PARAMS(BOOST_PP_INC(n),D)> makeAlgoCheckerList(BOOST_PP_ENUM_BINARY_PARAMS(BOOST_PP_INC(n) , D, const & arg)) \
  { return AlgorithmCheckerList<BOOST_PP_ENUM_PARAMS(BOOST_PP_INC(n),D)>(boost::fusion::make_list(BOOST_PP_ENUM_PARAMS(BOOST_PP_INC(n),arg))); } \

  BOOST_PP_REPEAT(PINOCCHIO_ALGO_CHECKER_LIST_MAX_LIST_SIZE, MAKE_ALGO_CHECKER_LIST, BOOST_PP_EMPTY)
#else
  template <class ...D>
  struct AlgorithmCheckerList: AlgorithmCheckerBase< AlgorithmCheckerList<D...> >
  {
    typedef typename boost::fusion::list<D...> ArgType;

    AlgorithmCheckerList(const ArgType & checkerList)
    : checkerList(checkerList) {}

    // Calls model.check for each checker in the fusion::list.
    // Each list element is supposed to implement the AlgorithmCheckerBase API.
    template<typename Scalar, int Options, template<typename,int> class JointCollectionTpl>
    bool checkModel_impl(const ModelTpl<Scalar,Options,JointCollectionTpl> & model) const;

    const ArgType & checkerList;
  };

  template <class ...T>
  AlgorithmCheckerList<T...> makeAlgoCheckerList(const T&... args)
  {
    return AlgorithmCheckerList<T...>(boost::fusion::make_list(args...));
  }

#endif

  /// Check the validity of data wrt to model, in particular if model has been modified.
  ///
  /// \param[in] model reference model
  /// \param[in] data corresponding data
  ///
  /// \returns True if data is valid wrt model.
  template<typename Scalar, int Options, template<typename,int> class JointCollectionTpl>
  inline bool checkData(const ModelTpl<Scalar,Options,JointCollectionTpl> & model,
                        const DataTpl<Scalar,Options,JointCollectionTpl> & data);

} // namespace pinocchio

  /* --- Details -------------------------------------------------------------------- */
#include "pinocchio/algorithm/check.hxx"

#endif // ifndef __pinocchio_check_hpp__

max_stars_repo_name: matthieuvigne/pinocchio

max_issues_repo_name: matthieuvigne/pinocchio

max_forks_repo_name: matthieuvigne/pinocchio