text:
/*
 * Copyright (c) 2014 CodiLime, Inc. All rights reserved.
 */

#include <boost/asio.hpp>
#include <boost/scoped_ptr.hpp>
#include <boost/random.hpp>

#include "bfd/bfd_udp_connection.h"
#include "bfd/bfd_connection.h"
#include "bfd/bfd_control_packet.h"
#include "bfd/bfd_common.h"
#include "bfd/bfd_server.h"

#include "base/logging.h"

namespace BFD {

UDPConnectionManager::UDPRecvServer::UDPRecvServer(UDPConnectionManager *parent,
                                       EventManager *evm,
                                       int recvPort)
        : UdpServer(evm), parent_(parent) {
    Initialize(recvPort);
}

void UDPConnectionManager::UDPRecvServer::RegisterCallback(
                                    RecvCallback callback) {
    this->callback_ = callback;
}

void UDPConnectionManager::UDPRecvServer::HandleReceive(
        const boost::asio::const_buffer &recv_buffer,
        boost::asio::ip::udp::endpoint remote_endpoint,
        std::size_t bytes_transferred,
        const boost::system::error_code &error) {
    if (callback_) {
        callback_.get()(remote_endpoint, recv_buffer, bytes_transferred, error);
        return;
    }

    boost::system::error_code err;
    parent_->HandleReceive(recv_buffer, GetLocalEndpoint(&err),
                           remote_endpoint, SessionIndex(), bytes_transferred,
                           error);
}

UDPConnectionManager::UDPCommunicator::UDPCommunicator(EventManager *evm,
                                                       int remotePort)
                                : UdpServer(evm), remotePort_(remotePort) {
    boost::random::uniform_int_distribution<> dist(kSendPortMin, kSendPortMax);
    for (int i = 0; i < 100 && GetServerState() != OK; ++i) {
        int localPort = dist(randomGen);
        LOG(DEBUG, "Bind UDPCommunicator to localport: " << localPort);
        Initialize(localPort);
        if (GetServerState() != OK) {
            Shutdown();
        }
    }

    if (GetServerState() != OK) {
        LOG(ERROR, "Unable to bind to port in range: " << kSendPortMin
                   << "-" << kSendPortMax);
    }
}

UDPConnectionManager::UDPConnectionManager(EventManager *evm, int recvPort,
                                           int remotePort)
          : udpRecv_(new BFD::UDPConnectionManager::UDPRecvServer(this, evm,
                     recvPort)),
            udpSend_(new BFD::UDPConnectionManager::UDPCommunicator(evm,
                     remotePort)), server_(NULL) {
    if (udpRecv_->GetServerState() != UDPRecvServer::OK)
        LOG(ERROR, "Unable to listen on port " << recvPort);
    else
        udpRecv_->StartReceive();
}

Server *UDPConnectionManager::GetServer() const {
    return server_;
}

void UDPConnectionManager::SetServer(Server *server) {
    server_ = server;
}

void UDPConnectionManager::RegisterCallback(RecvCallback callback) {
    udpRecv_->RegisterCallback(callback);
}

void UDPConnectionManager::SendPacket(boost::asio::ip::address remoteHost,
                                      const ControlPacket *packet) {
    boost::asio::mutable_buffer send =
        boost::asio::mutable_buffer(new uint8_t[kMinimalPacketLength],
                                    kMinimalPacketLength);
    int pktSize = EncodeControlPacket(packet,
                                      boost::asio::buffer_cast<uint8_t *>(send),
                                      kMinimalPacketLength);
    if (pktSize != kMinimalPacketLength) {
        LOG(ERROR, "Unable to encode packet");
        const uint8_t *p = boost::asio::buffer_cast<const uint8_t *>(send);
        delete[] p;
        return;
    }
    boost::asio::ip::udp::endpoint remote_endpoint(remoteHost,
                                                   udpSend_->remotePort());
    SendPacket(boost::asio::ip::udp::endpoint(), remote_endpoint, 0, send,
               pktSize);
}

void UDPConnectionManager::SendPacket(
        const boost::asio::ip::udp::endpoint &local_endpoint,
        const boost::asio::ip::udp::endpoint &remote_endpoint,
        const SessionIndex &index, const boost::asio::mutable_buffer &send,
        int pktSize) {
    udpSend_->StartSend(remote_endpoint, pktSize, send);
}

UDPConnectionManager::~UDPConnectionManager() {
    udpRecv_->Shutdown();
    udpSend_->Shutdown();
    UdpServerManager::DeleteServer(udpRecv_);
    UdpServerManager::DeleteServer(udpSend_);
}

void UDPConnectionManager::NotifyStateChange(const SessionKey &key,
                                             const bool &up) {
}

}  // namespace BFD

ext: cc

max_stars_repo_name: jnpr-pranav/contrail-controller

max_issues_repo_name: jnpr-pranav/contrail-controller

max_forks_repo_name: jnpr-pranav/contrail-controller


text:
// Copyright (C) 2019 Kirill Okhotnikov.
//
// Use, modification, and distribution is subject to the Boost Software
// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
//
// You are welcome to contact the author at:
//  kirill.okhotnikov@gmail.com
//

//#define SAFE_REDUCED_LIST
#include "types_list.hpp"

#define BOOST_TEST_MODULE test_assign
#include <boost/test/included/unit_test.hpp>

#include <cstdint>
#include <iostream>
#include <limits>
#include <stdexcept>
#include <safe/backends/native/cast_backend.hpp>
#include <safe/backends/builtin/cast_backend.hpp>
#include <safe/exceptions/std_overflow.hpp>

template <template <typename,typename> class Cast>
void check_value(const precision_type_t &pp) {
  using namespace boost;

  mpl::for_each<types_arithmetic_t>([pp](const auto u) -> void {
    typedef typename std::remove_cv<decltype(u)>::type U;
    if ( fits_in<U>(pp) && precision_saved<U>(pp, pp) ) {
      U ia = static_cast<U>(pp);
      mpl::for_each<types_integer_t>([pp, ia](const auto r) -> void {
        typedef typename std::remove_cv<decltype(r)>::type R;
        typedef typename std::remove_cv<decltype(ia)>::type U;
        if ( fits_in<R>(pp) && precision_saved<R>(pp, pp) ) {
          BOOST_CHECK_NO_THROW((Cast<R, U>::cast(ia)));
          precision_type_t pm = Cast<R, U>::cast(ia);
          BOOST_CHECK_EQUAL(pm, pp);
        } else {
          BOOST_CHECK_THROW((Cast<R,U>::cast(ia)), std::overflow_error);
        }
      });
    }
  });
}

template <template <typename,typename> class Cast>
void check_cast() {
  auto checks = values_to_check();
  for(const auto &v : checks)
    check_value<Cast>(v);
}

template <template <typename,typename> class Cast>
void simple_check() {
    BOOST_CHECK_THROW((Cast<unsigned char, signed char>::cast(-4)), std::overflow_error);
    BOOST_CHECK_THROW((Cast<unsigned char, int>::cast(300)), std::overflow_error);
    BOOST_CHECK_EQUAL((Cast<unsigned char, int>::cast(100)), 100);
    BOOST_CHECK_EQUAL((Cast<unsigned char, int>::cast(200)), 200);
    BOOST_CHECK_THROW((Cast<int, int64_t>::cast(2e10)), std::overflow_error);
    BOOST_CHECK_EQUAL((Cast<signed char, short>::cast(-4)), -4);
};

template <typename R, typename U>
using cast_n = safe::backend::native::cast_backend<R, U, safe::exception::std_safe_exception>;

template <typename R, typename U>
using cast_b = safe::backend::builtin::cast_backend<R, U, safe::exception::std_safe_exception>;

BOOST_AUTO_TEST_CASE( native_cast_name_simple )
{
  simple_check<cast_n>();
}

BOOST_AUTO_TEST_CASE( native_cast_name_extended )
{
  check_cast<cast_n>();
}

BOOST_AUTO_TEST_CASE( bultin_cast_name_simple )
{
  simple_check<cast_b>();
}

BOOST_AUTO_TEST_CASE( bultin_cast_name_extended )
{
  check_cast<cast_b>();
}

ext: cpp


text:
#pragma once

#include <boost/signals2/signal.hpp>
#include <boost/asio/detail/posix_fd_set_adapter.hpp>

#include <microhttpd.h>
#include <cstring>

#include <rapidjson/writer.h>
#include <rapidjson/stringbuffer.h>

#include <piga/devkit/Devkit.hpp>

#include <map>
#include <unordered_map>
#include <vector>
#include <mutex>

namespace piga
{
namespace devkit
{
class Devkit;
class WebUI;

class HTTPServer
{
public:
    typedef rapidjson::Writer<rapidjson::StringBuffer> JsonWriter;

    HTTPServer(Devkit *devkit, uint32_t port = 8080);
    ~HTTPServer();

    std::string parseRequest(const std::string &req, std::string *contentType, Devkit::DevkitAction *return_action);

    void setAllowedActionsForToken(const std::string &token, const Devkit::ActionsVector &actions);

    void exportNFS(JsonWriter &writer, const std::string &address);
    void removeNFSExport(JsonWriter &writer, const std::string &address);
    void reboot(JsonWriter &writer);
    void restartApp(JsonWriter &writer, const std::string &appName);

    void connectionEnded(struct MHD_Connection *connection, void **con_cls, enum MHD_RequestTerminationCode code);

    std::string web(const std::string &path, std::string *contentType, const std::string &token);

#if MHD_VERSION < 0x00095102
int
#else
int64_t
#endif
    chunkedResponseCallback(void *cls, uint64_t pos, char *buf, size_t max);

    static int answer_to_connection (void *cls, struct MHD_Connection *connection,
                                     const char *url,
                                     const char *method, const char *version,
                                     const char *upload_data,
                                     std::size_t *upload_data_size, void **con_cls);

    // Pushes a message on the internal log buffer, which can then be read.
    void logReaderCallback(const std::string &msg);
private:
    struct MHD_Daemon *m_daemon = nullptr;
    uint32_t m_port = 8080;

    std::unique_ptr<boost::asio::detail::posix_fd_set_adapter> m_readFdSet;
    std::unique_ptr<boost::asio::detail::posix_fd_set_adapter> m_writeFdSet;

    Devkit *m_devkit;

    std::map<std::string, Devkit::ActionsVector> m_tokens;

    std::unique_ptr<WebUI> m_webUI;

    static void connectionEndedCb(void *cls, struct MHD_Connection *connection, void **con_cls, enum MHD_RequestTerminationCode code);

    void setConnectionAction(struct MHD_Connection *conn, Devkit::DevkitAction action);
    Devkit::DevkitAction getConnectionAction(struct MHD_Connection *conn);
    void eraseConnectionFromActions(struct MHD_Connection *conn);
    std::vector<struct MHD_Connection*> getConnectionsOfAction(Devkit::DevkitAction action);

    std::mutex m_actionMapMutex;
    std::unordered_map<struct MHD_Connection*, Devkit::DevkitAction> m_actionMap;

    void removeLogReader();
    void addLogReader();
    std::string getLogMsgForConnection(struct MHD_Connection *conn);
    std::mutex m_logAccessMutex;
    std::size_t m_logAccessorCount = 0;
    std::vector<std::string> m_logBuffer;
    std::unordered_map<struct MHD_Connection*, std::size_t> m_logReaderPos;
    boost::signals2::connection m_logReaderConnection;
};
}
}

ext: hpp

max_stars_repo_name: Pigaco/daemon

max_issues_repo_name: Pigaco/daemon

max_forks_repo_name: Pigaco/daemon


text:
/*
 * Copyright (C) 2012-2014 Open Source Robotics Foundation
 *
 * 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 <boost/bind.hpp>

#include "gazebo/gui/GuiIface.hh"
#include "gazebo/gui/GuiEvents.hh"
#include "gazebo/rendering/Scene.hh"
#include "gazebo/rendering/Camera.hh"
#include "gazebo/rendering/DepthCamera.hh"
#include "gazebo/rendering/RenderEngine.hh"
#include "gazebo/rendering/UserCamera.hh"
#include "gazebo/rendering/GUIOverlay.hh"
#include "gazebo/rendering/Visual.hh"
#include "gazebo/gazebo.hh"

namespace gazebo
{
  class State
  {
    public: State(const std::string &_slide,
                  const math::Vector3 _offset,
                  double _pitch, double _yaw, double _duration)
            : slide(_slide), offset(_offset),
              pitch(_pitch), yaw(_yaw), duration(_duration) {}
    public: std::string slide;
    public: math::Vector3 offset;
    public: double pitch;
    public: double yaw;
    public: double duration;
  };

  class Presentation : public SystemPlugin
  {
    public: void Load()
    {
      this->node = transport::NodePtr(new transport::Node());
      this->node->Init();

      this->connections.push_back(
          gui::Events::ConnectKeyPress(
            boost::bind(&Presentation::KeyPress, this, _1)));

      this->states.push_back(new State("default::slide1",
            math::Vector3(0, 0, 3.6), M_PI*0.5, 0, 0.6));
      this->states.push_back(new State("default::slide1",
            math::Vector3(0, 0, 3.6), M_PI*0.5, 0, 0.6));
      this->states.push_back(new State("default::slide2",
            math::Vector3(0, 0, 0.03), M_PI*0.5, 0, 0.6));
      this->states.push_back(new State("default::slide3",
            math::Vector3(0, 0, 0.03), M_PI*0.5, -M_PI*0.5, 0.5));
      this->states.push_back(new State("default::slide4",
            math::Vector3(0, 0, 0.03), M_PI*0.5, -M_PI*0.5, 0.5));
      this->states.push_back(new State("default::slide5",
            math::Vector3(0, 0, 0.03), M_PI*0.5, -M_PI*0.5, 0.5));
      this->states.push_back(new State("default::slide6",
            math::Vector3(0, 0, 0.035), M_PI*0.5, -M_PI*0.5, 0.5));
      this->states.push_back(new State("default::slide7",
            math::Vector3(0, 0, 0.035), M_PI*0.5, -M_PI*0.5, 0.5));

      this->states.push_back(new State("default::slide8",
            math::Vector3(0, 0, 3.5), M_PI*0.5, 0, 0));

      this->states.push_back(new State("default::slide9",
            math::Vector3(0, 0, .037), M_PI*0.5, 0, 0.5));
      this->states.push_back(new State("default::slide10",
            math::Vector3(0, 0, .037), M_PI*0.5, 0, 0.5));

      this->states.push_back(new State("default::slide8",
            math::Vector3(0, 0, 3.5), M_PI*0.5, 0, 0.5));

      this->states.push_back(new State("default::slide11",
            math::Vector3(0, 0, 0.037), M_PI*0.5, 0, 0.5));

      this->states.push_back(new State("default::slide8",
            math::Vector3(0, 0, 3.5), M_PI*0.5, 0, 0.5));

      this->states.push_back(new State("default::slide12",
            math::Vector3(0, 0, 0.037), M_PI*0.5, 0, 0.5));

      this->states.push_back(new State("default::slide8",
            math::Vector3(0, 0, 3.5), M_PI*0.5, 0, 0.5));

      this->states.push_back(new State("default::slide13",
            math::Vector3(0, 0, 0.037), M_PI*0.5, 0, 0.5));

      this->states.push_back(new State("default::slide8",
            math::Vector3(0, 0, 3.5), M_PI*0.5, 0, 0.5));

      this->states.push_back(new State("default::slide14",
            math::Vector3(0, 0, 3.5), M_PI*0.5, M_PI*0.5, 0.5));

      this->states.push_back(new State("default::slide15",
            math::Vector3(0, 0, 3.5), M_PI*0.5, M_PI, 0.5));

      this->iter = this->states.begin();
    }
    private: void Init()
             {
             }

    private: void KeyPress(const std::string &_key)
             {
               rendering::UserCameraPtr userCam = gui::get_active_camera();

               if (_key == " ")
                 this->iter++;
               else if (_key == "b")
                 this->iter--;

               if (this->iter != this->states.end())
                 this->Update();
               else
                 this->iter = this->states.end()-1;
             }

    private: void Update()
             {
               rendering::UserCameraPtr userCam = gui::get_active_camera();
               rendering::Scene *scene = userCam->GetScene();
               rendering::VisualPtr visual =
                 scene->GetVisual((*this->iter)->slide);
               math::Pose pose = visual->GetWorldPose();
               math::Vector3 p = pose.pos +  (*this->iter)->offset;

               if ((*this->iter)->duration >0)
               {
                 userCam->MoveToPosition(p, (*this->iter)->pitch,
                                         (*this->iter)->yaw,
                                         (*this->iter)->duration);
               }
               else
               {
                 pose.pos = p;
                 pose.rot.SetFromEuler(
                     math::Vector3(0, (*this->iter)->pitch,
                                   (*this->iter)->yaw));
                 userCam->SetWorldPose(pose);
               }
             }

    private: transport::NodePtr node;
    private: std::vector<event::ConnectionPtr> connections;
    private: std::vector<State*> states;
    private: std::vector<State*>::iterator iter;
  };

  // Register this plugin with the simulator
  GZ_REGISTER_SYSTEM_PLUGIN(Presentation)
}

max_stars_repo_name: hyunoklee/Gazebo

max_issues_repo_name: hyunoklee/Gazebo

max_forks_repo_name: hyunoklee/Gazebo


text:
// Converts filternames.scf names into mmap file
//
// There are 2 output names data/names.mmap and data/names_begin.mmap
// Usage:
// 	scf2mmap -f path-to-filter-names.scf

// LIBC
#include <fcntl.h>
#include <time.h>

// thrift is too stupid to include headers it needs for 'htonl'
#include <arpa/inet.h>
// THRIFT
#include <thrift/protocol/TBinaryProtocol.h>
#include <thrift/protocol/TDenseProtocol.h>
#include <thrift/protocol/TJSONProtocol.h>
#include <thrift/transport/TTransportUtils.h>
#include <thrift/transport/TFDTransport.h>
#include <thrift/transport/TFileTransport.h>
	namespace atp = apache::thrift::protocol;
	namespace att = apache::thrift::transport;

// THRIFT -- FILTERNAMES
#include "filternames_types.h"
#include "filternames_constants.h"
	namespace fn = filternames;

// STD
#include <iostream>
	using std::cerr;
	using std::cout;
	using std::endl;

#include <algorithm>
	using std::copy;
#include <iterator>
	using std::back_inserter;
#include <unordered_map>
	using std::unordered_map;
#include <set>
	using std::set;
#include <string>
	using std::string;
#include <vector>
	using std::vector;
#include <fstream>

// BOOST
#include <boost/program_options.hpp>
	namespace po = boost::program_options;

// LVVLIB (http://github.com/lvv/lvvlib)
//#ifdef LVV
//#include <ro/ro.h>
//#include <scc/simple.h>
//#endif
#include "lvvlib/token.h"
#include "lvvlib/mmap.h"

int main(int argc, char **argv) {

	///////////////////////////////////////////////////////////////////////////////  OPTIONS

	string		filtername_path;

	po::options_description desc("Allowed options");
	desc.add_options()
		("help,h", "help message")
		("filternames,f", po::value<string>(&filtername_path), "filternames file")
	;

	// Parse command line options
	po::variables_map vm;
	po::store(po::parse_command_line(argc, argv, desc), vm);
	po::notify(vm);

	if (vm.count("help")) { cout << desc << "\n"; return 1; }

	////////////////////////////////////////////////////////////// THRIFT READS FILTERNAMES

	int scf_fh = open(filtername_path.c_str(), O_RDONLY);

					if(scf_fh==-1)  {
						cerr << "error: cann't open scf file -- '" << filtername_path << "'\n";
						exit(1);
					}

	boost::shared_ptr<att::TFDTransport>		innerTransportScf(new att::TFDTransport(scf_fh));
	boost::shared_ptr<att::TBufferedTransport>	transportScf(new att::TBufferedTransport(innerTransportScf));
	boost::shared_ptr<atp::TBinaryProtocol>		protocolScf(new atp::TBinaryProtocol(transportScf));
	transportScf->open();

	fn::FilterNames filter_names;
	filter_names.read(protocolScf.get());

	unordered_map<string, set<string>> target_text_map;

	#ifdef LVV
		// a hack to release some memory
		filter_names.target_id_to_names = std::map<std::string, std::vector<std::string>>();
	#endif

	////////////////////////////////////////////////////////////////////////////////// FILTER AND ADD TO NAMES

	vector<char>	names_data;		// cancantenated content of names
	vector<char>	name;                   // temp name
	vector<size_t>	names_begin{0};		// array of indexes in names_data which point to begining of a names.
						// a name i is from names_begin[i] to names_begin[i+1]

	size_t name_min=9999999999;
	size_t name_max=0;
	size_t good_names = 0;

	set<vector<char>> uniq_set;            	// used in check for uniqness
	long total_tokens = 0;

	// for all names in filter_names
	for(auto& pr : filter_names.name_to_target_ids) {
		auto s  = pr.first.data();                             		// name
		size_t sz = pr.first.size();                                    // is size

						#ifdef DISPLAY_NAMES
						cout << "\nscf name: \t(" << string(s,s+sz) << ")\n";
						#endif
		// split into tokens
		pos_t  tb, te = s;             					// token begin, end
		pos_t  e = s + sz;
		name.clear();
		long tokens = 0;
		while ((tb=get_tb(te,e)) != e) {
			te=get_te(tb,e);
			if (!name.empty())  name.push_back(token_separator);
			copy (tb, te, back_inserter(name));
			++tokens;
		}

		// filter out bad names
		constexpr long	max_name_length = 1000;
		constexpr long	min_name_length = 3;
		constexpr long	min_name_tokens = 1;

		if (
			    ( min_name_length <= name.size()  &&  name.size() <= max_name_length )
			&&  ( min_name_tokens <= tokens )
			&&  ( uniq_set.find(name) == uniq_set.end() )
		) {
			++good_names;
		} else {
			continue;
		}

		uniq_set.insert(name);
						#ifdef DISPLAY_NAMES
						cout << "added name: \t(" << string(name.begin(), name.end()) << ")\n";
						#endif
		// statistics
		name_min = std::min(name_min, name.size());
		name_max = std::max(name_max, name.size());
		total_tokens += tokens;

		// append name to names_data
		copy (name.begin(), name.end(), back_inserter(names_data));
		names_begin.push_back(names_data.size());
	}

	transportScf->close();

	cerr << "NAMES: "  << filter_names.name_to_target_ids.size()
	     << ";\n\t good:       "         << good_names
	     << ";\n\t min length: "         << name_min
	     << ";\n\t max length: "         << name_max
	     << ";\n\t avg length: "         << double(names_data.size())/(names_begin.size()-1)
	     << ";\n\t avg tokens: "         << double(total_tokens)/(names_begin.size()-1)
	     << ";\n\t total names length: " << names_data.size()
	     << endl;

	///////////////////////////////////////////////////////////////////////////////// WRITE MMAP

	cerr << "writing names memory map file ... ";

	mmap_write<char>  ("data/names.mmap",       &names_data[0],  names_data.size());
	mmap_write<size_t>("data/names_begin.mmap", &names_begin[0], names_begin.size());

	cerr << "done\n";
}

// vim: ts=8 sw=8

max_stars_repo_name: streamcorpus/streamcorpus-filter

max_issues_repo_name: streamcorpus/streamcorpus-filter

max_forks_repo_name: streamcorpus/streamcorpus-filter


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

// Copyright (c) 2019 Tinko Bartels, Berlin, Germany.

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

#ifndef BOOST_GEOMETRY_EXTENSIONS_TRIANGULATION_ALGORITHMS_DELAUNAY_TRIANGULATION_HPP
#define BOOST_GEOMETRY_EXTENSIONS_TRIANGULATION_ALGORITHMS_DELAUNAY_TRIANGULATION_HPP

#include <vector>
#include <utility>
#include <tuple>
#include <iterator>
#include <algorithm>

#include <boost/geometry/core/coordinate_dimension.hpp>
#include <boost/geometry/core/cs.hpp>
#include <boost/geometry/core/tag.hpp>
#include <boost/geometry/core/tags.hpp>

#include <boost/geometry/algorithms/make.hpp>
#include <boost/geometry/algorithms/comparable_distance.hpp>
#include <boost/geometry/extensions/triangulation/geometries/triangulation.hpp>
#include <boost/geometry/extensions/triangulation/strategies/cartesian/in_circle_robust.hpp>
#include <boost/geometry/extensions/triangulation/strategies/delaunay_triangulation.hpp>
#include <boost/geometry/extensions/triangulation/strategies/cartesian/accelerated_shull.hpp>
#include <boost/geometry/strategies/cartesian/side_by_triangle.hpp>

namespace boost { namespace geometry
{

template
<
    typename PointContainer,
    typename Triangulation,
    typename SideStrategy = strategy::side::side_by_triangle<>,
    typename InCircleStrategy = strategy::in_circle::in_circle_robust<>,
    typename ConstructionStrategy =
        typename strategy::delaunay_triangulation::services::default_strategy
            <
                typename tag<typename PointContainer::value_type>::type,
                typename cs_tag<typename PointContainer::value_type>::type,
                dimension<typename PointContainer::value_type>::value
            >::type
>
inline void delaunay_triangulation(PointContainer const & in,
                                   Triangulation& out,
                                   bool legalize = true)
{
    ConstructionStrategy::template apply
        <
            PointContainer,
            Triangulation,
            SideStrategy,
            InCircleStrategy
        >(in, out, legalize);
}

}} // namespace boost::geometry

#endif // BOOST_GEOMETRY_EXTENSIONS_TRIANGULATION_ALGORITHMS_DELAUNAY_TRIANGULATION_HPP


text:
//////////////////////////////////////////////////////////////////////////////
//  Boost.Assign v2                                                         //
//                                                                          //
//  Copyright (C) 2003-2004 Thorsten Ottosen                                //
//  Copyright (C) 2011 Erwann Rogard                                        //
//  Use, modification and distribution are subject to the                   //
//  Boost Software License, Version 1.0. (See accompanying file             //
//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)        //
//////////////////////////////////////////////////////////////////////////////
#include <cmath>
#include <deque>
#include <list>
#include <map>
#include <vector>
#include <boost/array.hpp>
#include <boost/assign/v2/deque.hpp>
#include <boost/assign/v2/option/data.hpp>
#include <boost/assign/v2/interpreter/csv/csv_basic.hpp>
#include <boost/assign/v2/include/csv_deque_basic.hpp>
#include <boost/assign/v2/include/csv_put_basic.hpp>
#include <boost/assign/v2/include/put.hpp>
#include <boost/assign/v2/include/deque.hpp>
#include <boost/assign/v2/support/config/check.hpp>

#include <boost/function.hpp>
#include <boost/lambda/bind.hpp>
#include <boost/lambda/lambda.hpp>
#include <boost/numeric/conversion/bounds.hpp>
#include <boost/range/algorithm/equal.hpp>
#include <boost/typeof/typeof.hpp>
#include <libs/assign/v2/test/option/data.h>

namespace test_assign_v2{
namespace xxx_option{
namespace xxx_data{

    void test()
    {
        namespace as2 = boost::assign::v2;
        {
            // (*fp) resolves error C2440 using MSVC
            //[test_data1
            std::vector<double> exponent;
            /*<-*/typedef double(*fp)(double);/*->*/
            typedef boost::function<double(double)> f_;

            BOOST_AUTO(
                _data,
                ( as2::_data = f_( /*<-*/fp(/*->*/ log10 /*<-*/)/*->*/ ) )
            );

            csv(
                as2::put( exponent ) % _data
                , 1.0, 10.0, 100.0, 1000.0, 10000.0
            );

            double eps = boost::numeric::bounds<double>::smallest();
            BOOST_ASSIGN_V2_CHECK( fabs( exponent.front() - 0.0 ) < eps );
            BOOST_ASSIGN_V2_CHECK( fabs( exponent.back() - 4.0 ) < eps );
            //]
        }
        {
            //[test_data2
            int k = 1;

            BOOST_AUTO(
                _data,
                (
                    as2::_data = (
                        boost::lambda::var( k ) *= boost::lambda::_1
                    )
                )
            );

            BOOST_ASSIGN_V2_CHECK(
                boost::range::equal(
                    csv(
                        as2::deque<int>( as2::_nil ) % _data,
                        1, 2, 3, 4, 5
                    ),
                    as2::csv_deque( 1, 2, 6, 24, 120 )
                )
            );
            //]
        }
        {
            //[test_data3
            typedef std::string month_; typedef int days_;
            typedef std::map<month_, days_> map_;
            typedef map_::value_type pair_;

            map_ map;
            as2::csv_put<as2::value_>(
                map,
                pair_( "jan", 31 ),
                pair_( "feb", 28 ),
                pair_( "mar", 31 )
            );

            BOOST_ASSIGN_V2_CHECK( map["jan"] == 31 );
            BOOST_ASSIGN_V2_CHECK( map["feb"] == 28 );
            BOOST_ASSIGN_V2_CHECK( map["mar"] == 31 );
            //]
        }
    }

}// xxx_data
}// xxx_option
}// test_assign_v2


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

#include "consensus/grandpa/impl/grandpa_impl.hpp"

#include <boost/asio/post.hpp>
#include <storage/database_error.hpp>

#include "consensus/grandpa/impl/vote_crypto_provider_impl.hpp"
#include "consensus/grandpa/impl/vote_tracker_impl.hpp"
#include "consensus/grandpa/impl/voting_round_error.hpp"
#include "consensus/grandpa/impl/voting_round_impl.hpp"
#include "consensus/grandpa/vote_graph/vote_graph_impl.hpp"
#include "scale/scale.hpp"
#include "storage/predefined_keys.hpp"

namespace kagome::consensus::grandpa {

  GrandpaImpl::GrandpaImpl(
      std::shared_ptr<application::AppStateManager> app_state_manager,
      std::shared_ptr<Environment> environment,
      std::shared_ptr<storage::BufferStorage> storage,
      std::shared_ptr<crypto::Ed25519Provider> crypto_provider,
      std::shared_ptr<runtime::GrandpaApi> grandpa_api,
      const crypto::Ed25519Keypair &keypair,
      std::shared_ptr<Clock> clock,
      std::shared_ptr<boost::asio::io_context> io_context,
      std::shared_ptr<authority::AuthorityManager> authority_manager,
      std::shared_ptr<consensus::Babe> babe)
      : app_state_manager_(std::move(app_state_manager)),
        environment_{std::move(environment)},
        storage_{std::move(storage)},
        crypto_provider_{std::move(crypto_provider)},
        grandpa_api_{std::move(grandpa_api)},
        keypair_{keypair},
        clock_{std::move(clock)},
        io_context_{std::move(io_context)},
        authority_manager_(std::move(authority_manager)),
        babe_(babe) {
    BOOST_ASSERT(app_state_manager_ != nullptr);
    BOOST_ASSERT(environment_ != nullptr);
    BOOST_ASSERT(storage_ != nullptr);
    BOOST_ASSERT(crypto_provider_ != nullptr);
    BOOST_ASSERT(grandpa_api_ != nullptr);
    BOOST_ASSERT(clock_ != nullptr);
    BOOST_ASSERT(io_context_ != nullptr);
    BOOST_ASSERT(authority_manager_ != nullptr);
    BOOST_ASSERT(babe_ != nullptr);

    app_state_manager_->takeControl(*this);
    catch_up_request_suppressed_until_ = clock_->now();
  }

  bool GrandpaImpl::prepare() {
    // Set themselves in environment
    environment_->setJustificationObserver(shared_from_this());

    // Lambda which is executed when voting round is completed.
    environment_->doOnCompleted(
        [wp = weak_from_this()](
            outcome::result<MovableRoundState> completed_round_res) {
          if (auto self = wp.lock()) {
            self->onCompletedRound(std::move(completed_round_res));
          }
        });
    return true;
  }

  bool GrandpaImpl::start() {
    // Obtain last completed round
    auto round_state_res = getLastCompletedRound();
    if (not round_state_res.has_value()) {
      logger_->critical(
          "Can't retrieve last round data: {}. Stopping grandpa execution",
          round_state_res.error().message());
      return false;
    }
    auto &round_state = round_state_res.value();

    logger_->debug("Grandpa will be started with round #{}",
                   round_state.round_number + 1);

    current_round_ = makeInitialRound(round_state);
    if (current_round_ == nullptr) {
      logger_->critical(
          "Next round hasn't been made. Stopping grandpa execution");
      return false;
    }

    BOOST_ASSERT(current_round_->finalizable());
    BOOST_ASSERT(current_round_->finalizedBlock() == round_state.finalized);

    // Lambda which is executed when voting round is completed.
    babe_->doOnSynchronized([wp = weak_from_this()] {
      if (auto self = wp.lock()) {
        // Planning play next round
        self->is_ready_ = true;
        self->current_round_->play();
      }
    });

    executeNextRound();

    return true;
  }

  void GrandpaImpl::stop() {}

  std::shared_ptr<VotingRound> GrandpaImpl::makeInitialRound(
      const MovableRoundState &round_state) {
    // Obtain grandpa voters
    auto voters_res = getVoters();
    if (not voters_res.has_value()) {
      logger_->critical("Can't retrieve voters: {}. Stopping grandpa execution",
                        voters_res.error().message());
      return {};
    }
    const auto &voters = voters_res.value();
    if (voters->empty()) {
      logger_->critical("Voters are empty. Stopping grandpa execution");
      return {};
    }

    auto vote_graph = std::make_shared<VoteGraphImpl>(
        round_state.last_finalized_block, environment_);

    GrandpaConfig config{.voters = voters,
                         .round_number = round_state.round_number,
                         .duration = round_time_factor_,
                         .peer_id = keypair_.public_key};

    auto vote_crypto_provider = std::make_shared<VoteCryptoProviderImpl>(
        keypair_, crypto_provider_, round_state.round_number, voters);

    auto new_round = std::make_shared<VotingRoundImpl>(
        shared_from_this(),
        std::move(config),
        environment_,
        std::move(vote_crypto_provider),
        std::make_shared<VoteTrackerImpl>(),  // Prevote tracker
        std::make_shared<VoteTrackerImpl>(),  // Precommit tracker
        std::move(vote_graph),
        clock_,
        io_context_,
        round_state);

    new_round->end();
    return new_round;
  }

  std::shared_ptr<VotingRound> GrandpaImpl::makeNextRound(
      const std::shared_ptr<VotingRound> &round) {
    logger_->debug("Making next round");

    BOOST_ASSERT(round->finalizedBlock().has_value());

    // Obtain grandpa voters
    auto voters_res = getVoters();
    if (not voters_res.has_value()) {
      logger_->critical("Can't retrieve voters: {}. Stopping grandpa execution",
                        voters_res.error().message());
      return {};
    }
    const auto &voters = voters_res.value();
    if (voters->empty()) {
      logger_->critical("Voters are empty. Stopping grandpa execution");
      return {};
    }

    const auto new_round_number = round->roundNumber() + 1;

    BlockInfo best_block = round->finalizedBlock().value();

    auto vote_graph = std::make_shared<VoteGraphImpl>(best_block, environment_);

    GrandpaConfig config{
        .voters = voters,
        .round_number = new_round_number,
        .duration = round_time_factor_,
        .peer_id = keypair_.public_key};

    auto vote_crypto_provider = std::make_shared<VoteCryptoProviderImpl>(
        keypair_, crypto_provider_, new_round_number, voters);

    auto new_round = std::make_shared<VotingRoundImpl>(
        shared_from_this(),
        std::move(config),
        environment_,
        std::move(vote_crypto_provider),
        std::make_shared<VoteTrackerImpl>(),  // Prevote tracker
        std::make_shared<VoteTrackerImpl>(),  // Precommit tracker
        std::move(vote_graph),
        clock_,
        io_context_,
        round);
    return new_round;
  }

  std::shared_ptr<VotingRound> GrandpaImpl::selectRound(
      RoundNumber round_number) {
    std::shared_ptr<VotingRound> target_round;
    if (current_round_ && current_round_->roundNumber() == round_number) {
      target_round = current_round_;
    } else if (previous_round_
               && previous_round_->roundNumber() == round_number) {
      target_round = previous_round_;
    }
    return target_round;
  }

  outcome::result<std::shared_ptr<VoterSet>> GrandpaImpl::getVoters() const {
    /*
     * TODO(kamilsa): PRE-356 Check if voters were updated:
     * We should check if voters received from runtime (through
     * grandpa->grandpa_authorities() runtime entry call) differ from the ones
     * that we obtained from the storage. If so, we should return voter set with
     * incremented voter set and consisting of new voters. Also round number
     * should be reset to 0
     */
    OUTCOME_TRY(voters_encoded, storage_->get(storage::kAuthoritySetKey));
    OUTCOME_TRY(voter_set, scale::decode<VoterSet>(voters_encoded));
    return std::make_shared<VoterSet>(voter_set);
  }

  outcome::result<MovableRoundState> GrandpaImpl::getLastCompletedRound()
      const {
    auto last_round_encoded_res = storage_->get(storage::kSetStateKey);

    // Saved data exists
    if (last_round_encoded_res.has_value()) {
      return scale::decode<MovableRoundState>(last_round_encoded_res.value());
    }

    // Fail at retrieve data
    if (last_round_encoded_res
        != outcome::failure(storage::DatabaseError::NOT_FOUND)) {
      return last_round_encoded_res.as_failure();
    }

    // No saved data - make from genesis
    auto genesis_hash_res = storage_->get(storage::kGenesisBlockHashLookupKey);
    if (not genesis_hash_res.has_value()) {
      logger_->critical("Can't retrieve genesis block hash: {}",
                        genesis_hash_res.error().message());
      return genesis_hash_res.as_failure();
    }

    primitives::BlockHash genesis_hash;
    std::copy(genesis_hash_res.value().begin(),
              genesis_hash_res.value().end(),
              genesis_hash.begin());

    return MovableRoundState{.round_number = 0,
                             .last_finalized_block = {0, genesis_hash},
                             .votes = {},
                             .finalized = {{0, genesis_hash}}};
  }

  void GrandpaImpl::executeNextRound() {
    previous_round_.swap(current_round_);
    previous_round_->end();
    current_round_ = makeNextRound(previous_round_);
    if (is_ready_) {
      current_round_->play();
    }
  }

  void GrandpaImpl::onCatchUpRequest(const libp2p::peer::PeerId &peer_id,
                                     const network::CatchUpRequest &msg) {
    if (not is_ready_) {
      return;
    }
    if (previous_round_ == nullptr) {
      logger_->debug(
          "Catch-up request (since round #{}) received from {} was rejected: "
          "previous round is dummy yet",
          msg.round_number,
          peer_id.toHex());
      return;
    }
    if (previous_round_->voterSetId() != msg.voter_set_id) {
      // Catching up of different set
      logger_->debug(
          "Catch-up request (since round #{}) received from {} was rejected: "
          "voter set is different",
          msg.round_number,
          peer_id.toHex());
      return;
    }
    if (previous_round_->roundNumber() < msg.round_number) {
      // Catching up in to the past
      logger_->debug(
          "Catch-up request (since round #{}) received from {} was rejected: "
          "catching up in to the past",
          msg.round_number,
          peer_id.toHex());
      return;
    }
    if (current_round_->roundNumber() + 2 <= msg.round_number) {
      if (catch_up_request_suppressed_until_ > clock_->now()) {
        catch_up_request_suppressed_until_ =
            clock_->now() + catch_up_request_suppression_duration_;
        current_round_->doCatchUpRequest(peer_id);
      }
      return;
    }
    if (not previous_round_->completable()) {
      logger_->debug(
          "Catch-up request (since round #{}) received from {} was rejected: "
          "round is not completable",
          msg.round_number,
          peer_id.toHex());
      return;
    }
    if (not previous_round_->finalizable()) {
      logger_->debug(
          "Catch-up request (since round #{}) received from {} was rejected: "
          "round is not finalizable",
          msg.round_number,
          peer_id.toHex());
      return;
    }

    logger_->debug("Catch-up request (since round #{}) received from {}",
                   msg.round_number,
                   peer_id.toHex());
    previous_round_->doCatchUpResponse(peer_id);
  }

  void GrandpaImpl::onCatchUpResponse(const libp2p::peer::PeerId &peer_id,
                                      const network::CatchUpResponse &msg) {
    if (not is_ready_) {
      return;
    }
    BOOST_ASSERT(current_round_ != nullptr);
    if (current_round_->roundNumber() >= msg.round_number) {
      // Catching up in to the past
      logger_->debug(
          "Catch-up response (till round #{}) received from {} was rejected: "
          "catching up in to the past",
          msg.round_number,
          peer_id.toHex());
      return;
    }
    if (current_round_->voterSetId() != msg.voter_set_id) {
      // Catching up of different set
      logger_->debug(
          "Catch-up response (till round #{}) received from {} was rejected: "
          "voter set is different",
          msg.round_number,
          peer_id.toHex());
      return;
    }

    logger_->debug("Catch-up response (till round #{}) received from {}",
                   msg.round_number,
                   peer_id.toHex());

    MovableRoundState round_state{
        .round_number = msg.round_number,
        .last_finalized_block = msg.best_final_candidate,
        .votes = {},
        .finalized = msg.best_final_candidate};
    std::transform(msg.prevote_justification.items.begin(),
                   msg.prevote_justification.items.end(),
                   std::back_inserter(round_state.votes),
                   [](auto &item) { return item; });
    std::transform(msg.precommit_justification.items.begin(),
                   msg.precommit_justification.items.end(),
                   std::back_inserter(round_state.votes),
                   [](auto &item) { return item; });

    auto round = makeInitialRound(round_state);
    if (round == nullptr) {
      // Can't make round
      return;
    }

    if (current_round_->bestPrevoteCandidate().block_number
        > round->bestFinalCandidate().block_number) {
      // GHOST-less Catch-up
      return;
    }

    if (not round->completable()) {
      // Catch-up round is not completable
      return;
    }

    previous_round_.swap(current_round_);
    previous_round_->end();
    current_round_ = std::move(round);

    executeNextRound();

    catch_up_request_suppressed_until_ = clock_->now();
  }

  void GrandpaImpl::onVoteMessage(const libp2p::peer::PeerId &peer_id,
                                  const VoteMessage &msg) {
    if (not is_ready_) {
      return;
    }

    std::shared_ptr<VotingRound> target_round = selectRound(msg.round_number);
    if (not target_round) {
      if (current_round_->roundNumber() + 2 <= msg.round_number) {
        if (catch_up_request_suppressed_until_ > clock_->now()) {
          catch_up_request_suppressed_until_ =
              clock_->now() + catch_up_request_suppression_duration_;
          current_round_->doCatchUpRequest(peer_id);
        }
      }
      return;
    }

    // get block info
    auto blockInfo = visit_in_place(msg.vote.message, [](const auto &vote) {
      return BlockInfo(vote.block_number, vote.block_hash);
    });

    // get authorities
    const auto &weighted_authorities_res =
        grandpa_api_->authorities(primitives::BlockId(blockInfo.block_number));
    if (!weighted_authorities_res.has_value()) {
      logger_->error("Can't get authorities");
      return;
    };
    auto &weighted_authorities = weighted_authorities_res.value();

    // find signer in authorities
    auto weighted_authority_it =
        std::find_if(weighted_authorities.begin(),
                     weighted_authorities.end(),
                     [&id = msg.vote.id](const auto &weighted_authority) {
                       return weighted_authority.id.id == id;
                     });

    if (weighted_authority_it == weighted_authorities.end()) {
      logger_->warn("Vote signed by unknown validator");
      return;
    };
    visit_in_place(
        msg.vote.message,
        [&target_round, &msg](const PrimaryPropose &) {
          target_round->onProposal(msg.vote);
        },
        [&target_round, &msg](const Prevote &) {
          target_round->onPrevote(msg.vote);
        },
        [&target_round, &msg](const Precommit &) {
          target_round->onPrecommit(msg.vote);
        });
  }

  void GrandpaImpl::onFinalize(const libp2p::peer::PeerId &peer_id,
                               const Fin &fin) {
    if (not is_ready_) {
      return;
    }

    if (fin.justification.round_number != fin.round_number) {
      logger_->warn(
          "Round does not correspond to the fin message it belongs to");
      return;
    }

    if (fin.justification.block_info != fin.vote) {
      logger_->warn(
          "Block does not correspond to the fin message it belongs to");
      return;
    }

    auto res =
        applyJustification(fin.justification.block_info, fin.justification);
    if (not res.has_value()) {
      logger_->warn("Fin message is not applied: {}", res.error().message());
      return;
    }
  }

  outcome::result<void> GrandpaImpl::applyJustification(
      const BlockInfo &block_info, const GrandpaJustification &justification) {
    if (auto target_round = selectRound(justification.round_number)) {
      return target_round->applyJustification(block_info, justification);
    }

    if (current_round_->roundNumber() > justification.round_number) {
      return VotingRoundError::JUSTIFICATION_FOR_ROUND_IN_PAST;
    }

    if (current_round_->bestPrevoteCandidate().block_number
        > block_info.block_number) {
      return VotingRoundError::JUSTIFICATION_FOR_BLOCK_IN_PAST;
    }

    MovableRoundState round_state{.round_number = justification.round_number,
                                  .last_finalized_block = block_info,
                                  .votes = {},
                                  .finalized = block_info};

    auto round = makeInitialRound(round_state);
    assert(round);

    logger_->debug("Rewind grandpa till round #{} by received justification",
                   justification.round_number);

    OUTCOME_TRY(round->applyJustification(block_info, justification));

    previous_round_.swap(current_round_);
    previous_round_->end();
    current_round_ = std::move(round);

    executeNextRound();

    return outcome::success();
  }

  void GrandpaImpl::onCompletedRound(
      outcome::result<MovableRoundState> round_state_res) {
    if (not round_state_res) {
      logger_->debug("Grandpa round was not finalized: {}",
                     round_state_res.error().message());
      return;
    }

    const auto &round_state = round_state_res.value();

    logger_->debug("Event OnCompleted for round #{}", round_state.round_number);

    if (auto put_res =
            storage_->put(storage::kSetStateKey,
                          common::Buffer(scale::encode(round_state).value()));
        not put_res) {
      logger_->error("New round state was not added to the storage");
      return;
    }

    BOOST_ASSERT(storage_->get(storage::kSetStateKey));
  }
}  // namespace kagome::consensus::grandpa

max_stars_repo_name: igor-egorov/kagome

max_issues_repo_name: igor-egorov/kagome

max_forks_repo_name: igor-egorov/kagome


text:
//          Copyright Gavin Band 2008 - 2012.
// Distributed under the Boost Software License, Version 1.0.
//    (See accompanying file LICENSE_1_0.txt or copy at
//          http://www.boost.org/LICENSE_1_0.txt)

#ifndef METRO_LIKELIHOOD_SMOOTH_FUNCTION_HPP
#define METRO_LIKELIHOOD_SMOOTH_FUNCTION_HPP

#include <memory>
#include <boost/noncopyable.hpp>
#include <Eigen/Core>
#include "metro/DataSubset.hpp"

namespace metro {
	// This class represents a smooth function, i.e. a function that is
	// twice differentiable.
	// SmoothFunctions are intended to be stateful - they are properly thought
	// of as a function evaluated at a specific point.  This design choice
	// was made because it is typically the case that a large amount of computation can be
	// shared between derivatives.

	// a great deal of comp
	// The intentino
	// This choice means that the accessor functions, named "get_value[...]",
	// are const and return references, while the
	struct SmoothFunction: public boost::noncopyable {
	public:
		typedef std::unique_ptr< SmoothFunction > UniquePtr ;
		typedef double Scalar ;
		typedef Eigen::VectorXd Vector ;
		typedef Eigen::MatrixXd Matrix ;
	public:
		virtual ~SmoothFunction() {}
		virtual int number_of_parameters() const = 0 ;
		virtual Vector const& parameters() const = 0 ;

		// Evaluate the function at a given parameter value
		virtual void evaluate_at( Vector const& parameters, int const numberOfDerivatives = 2 ) = 0 ;
		// Re-evaluate the function at a previously set parameter value, previously
		// set by a call to evaluate_at().
		// This allows to evaluate a specified number of derivatives.
		virtual void evaluate( int const numberOfDerivatives = 2 ) = 0 ;

		virtual Scalar get_value_of_function() const = 0 ;
		virtual Vector get_value_of_first_derivative() const = 0 ;
		virtual Matrix get_value_of_second_derivative() const = 0 ;
		virtual std::string get_summary() const = 0 ;
	} ;
}

#endif

max_stars_repo_name: gavinband/qctool

max_issues_repo_name: gavinband/qctool

max_forks_repo_name: gavinband/qctool


text:
// Copyright 2018 Krister Joas <krister@joas.jp>

// 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 <string>
#include <iostream>
#include <fstream>
#include <boost/filesystem.hpp>
#include <boost/process.hpp>
#include "m.hh"
#include "_m.hh"

using namespace std::literals::string_literals;
namespace fs = boost::filesystem;
namespace bp = boost::process;

namespace m {
const std::string& Object::extension(const Project& project) const
{
  if(!_extension.empty())
    return _extension;
  return project.extension();
}

const std::string& Object::src_path() const
{
  return _source_path;
}

void Library::fetch(const Project& project) const
{
  if(_external)
    project.fetch(name(), _external->url(), _external->hash());
}

BuilderBase& BuilderBase::lib(const std::string& name)
{
  delete _current;
  _current = new LibraryBuilder(_project, name);
  return *_current;
}

BuilderBase& BuilderBase::frameworks(const std::string& name, const std::string& path)
{
  delete _current;
  _current = new FrameworkBuilder(_project, name, path);
  return *_current;
}

BuilderBase& BuilderBase::lib(const std::string& name, const std::string& pattern)
{
  delete _current;
  _current = new TemplateBuilder(_project, name, pattern);
  return *_current;
}

BuilderBase& BuilderBase::bin(const std::string& name)
{
  delete _current;
  _current = new BinaryBuilder(_project, name);
  return *_current;
}

BuilderBase* BuilderBase::_current = nullptr;

ProjectBuilder& ProjectBuilder::create(const std::string& name, const std::string& top,
  const std::string& build)
{
  return *new ProjectBuilder(name, top, build);
}

class Git
{
  public:
    Git() : _git(bp::search_path("git")) {}
    int clone(const std::string& url, const fs::path& location)
    {
      return bp::system(_git, "clone", url, location);
    }
    int summary(const std::string& ref)
    {
      return bp::system(_git, "show", "--summary", ref, bp::std_out > bp::null);
    }
    int fetch(const std::string& from)
    {
      return bp::system(_git, "fetch", from);
    }
    const std::string get_hash(const std::string& ref)
    {
      std::future<std::string> os;
      bp::system(_git, "log", "--pretty=format:%H", "-1", ref, bp::std_out > os);
      return os.get();
    }
    int reset_hard(const std::string& ref)
    {
      return bp::system(_git, "reset", "--hard", ref);
    }
  private:
    fs::path _git;
};

void Project::fetch(const std::string& name, const std::string& url, const std::string& hash_or_tag) const
{
  fs::path location = _topdir;
  location /= ".externals";
  location /= name;
  Git git;
  if(!fs::exists(location))
  {
    std::cout << "Cloning " << url << std::endl;
    git.clone(url, location);
  }
  auto current_path = fs::current_path();
  fs::current_path(location);
  auto ec = git.summary(hash_or_tag);
  if(ec != 0)
  {
    std::cout << "Fetching " << location << std::endl;
    git.fetch("origin");
  }
  auto head = git.get_hash("HEAD");
  auto hash = git.get_hash(hash_or_tag);
  if(head != hash)
  {
    std::cout << "Reset " << location << std::endl;
    git.reset_hard(hash_or_tag);
  }
  fs::current_path(current_path);
}
}

int main(int argc, const char** argv)
{
  std::string topdir{"."};
  std::string builddir{"build"};
  std::string _m{"_m"};
  int start = 1;
  if(argc > 1)
  {
    fs::path top{argv[1]};
    top /= "_m";
    if(fs::is_regular_file(top))
    {
      topdir = argv[1];
      builddir = ".";
      _m = top.string();
      ++start;
    }
  }
  const std::vector<std::string> args{argv + start, argv + argc};
  try
  {
    m::Loader loader(topdir, builddir);
    m::Project p = loader.load_file(_m);
    std::ofstream out{"build.ninja"};
    if(!out)
      throw std::runtime_error("Can't open build.ninja for writing");
    p.generate(out);
    fs::path ninja = bp::search_path("ninja");
    if(ninja.empty())
      throw std::runtime_error("Can't find program 'ninja'");
    bp::system(ninja, args);
  }
  catch(const std::runtime_error& e)
  {
    std::cerr << e.what() << std::endl;
  }
  return 0;
}

max_stars_repo_name: kuriboshi/m

max_issues_repo_name: kuriboshi/m

max_forks_repo_name: kuriboshi/m


text:
#include "zivid_camera.hpp"
#include "CaptureGeneralConfigUtils.h"
#include "CaptureFrameConfigUtils.h"

#include "zivid_camera/CameraInfoModelName.h"
#include "zivid_camera/CameraInfoSerialNumber.h"

#include <sensor_msgs/point_cloud2_iterator.h>
#include <sensor_msgs/image_encodings.h>
#include <sensor_msgs/distortion_models.h>
#include <dynamic_reconfigure/config_tools.h>

#include <Zivid/HDR.h>
#include <Zivid/Firmware.h>
#include <Zivid/Version.h>

#include <boost/algorithm/string.hpp>

#include <sstream>

namespace
{
sensor_msgs::PointField createPointField(std::string name, uint32_t offset, uint8_t datatype, uint32_t count)
{
  sensor_msgs::PointField point_field;
  point_field.name = name;
  point_field.offset = offset;
  point_field.datatype = datatype;
  point_field.count = count;
  return point_field;
}

bool big_endian()
{
  union
  {
    uint32_t i;
    char c[4];
  } u = { 0x01020304 };
  return u.c[0] == 0x01;
}

template <class T>
void fillCommonMsgFields(T& msg, const std_msgs::Header& header, const Zivid::PointCloud& pc)
{
  msg.header = header;
  msg.height = pc.height();
  msg.width = pc.width();
  msg.is_bigendian = big_endian();
}

template <class T>
ros::ServiceServer advertiseService(ros::NodeHandle& nh, const std::string& name,
                                    boost::function<bool(typename T::Request&, typename T::Response&)> cb)
{
  ROS_INFO("Advertisting service '%s'", name.c_str());
  return nh.advertiseService(name, cb);
}

}  // namespace

zivid_camera::ZividCamera::ZividCamera(ros::NodeHandle& nh, ros::NodeHandle& priv)
  : nh_(nh)
  , priv_(priv)
  , current_capture_general_config_(decltype(current_capture_general_config_)::__getDefault__())
  , image_transport_(nh_)
  , header_seq_(0)
{
  ROS_INFO("Zivid ROS driver version %s", ZIVID_ROS_DRIVER_VERSION);

  ROS_INFO("Node's namespace is '%s'", nh_.getNamespace().c_str());
  if (ros::this_node::getNamespace() == "/")
  {
    // Require the user to specify the namespace that this node will run in.
    // See REP-135 http://www.ros.org/reps/rep-0135.html
    throw std::runtime_error("Zivid ROS driver started in the global namespace ('/')! This is unsupported. "
                             "Please specify namespace, fex. using the ROS_NAMESPACE environment variable.");
  }

  ROS_INFO("Built towards Zivid API version %s", ZIVID_VERSION);
  ROS_INFO("Running with Zivid API version %s", Zivid::Version::libraryVersion().c_str());
  if (Zivid::Version::libraryVersion() != ZIVID_VERSION)
  {
    throw std::runtime_error("Zivid library mismatch! The running Zivid Core version does not match the "
                             "version this ROS driver was built towards. Hint: Try to clean and re-build your project "
                             "from scratch.");
  }

  std::string serial_number;
  priv_.param<decltype(serial_number)>("serial_number", serial_number, "");

  int num_capture_frames;
  priv_.param<decltype(num_capture_frames)>("num_capture_frames", num_capture_frames, 10);

  priv_.param<decltype(frame_id_)>("frame_id", frame_id_, "zivid_optical_frame");

  std::string file_camera_path;
  priv_.param<decltype(file_camera_path)>("file_camera_path", file_camera_path, "");
  const bool file_camera_mode = !file_camera_path.empty();

  if (file_camera_mode)
  {
    ROS_INFO("Creating file camera from file '%s'", file_camera_path.c_str());
    camera_ = zivid_.createFileCamera(file_camera_path);
  }
  else
  {
    auto cameras = zivid_.cameras();
    ROS_INFO("%zu cameras found", cameras.size());
    if (cameras.empty())
    {
      throw std::runtime_error("No cameras found. Ensure that the camera is connected to the USB3 port on your PC.");
    }
    else if (serial_number.empty())
    {
      camera_ = [&]() {
        ROS_INFO("Selecting first available camera");
        for (auto& c : cameras)
        {
          if (c.state().isAvailable())
            return c;
        }
        throw std::runtime_error("No available cameras found. Is the camera in use by another process?");
      }();
    }
    else
    {
      if (serial_number.find(":") == 0)
      {
        serial_number = serial_number.substr(1);
      }
      camera_ = [&]() {
        ROS_INFO("Searching for camera with serial number '%s' ...", serial_number.c_str());
        for (auto& c : cameras)
        {
          if (c.serialNumber() == Zivid::SerialNumber(serial_number))
            return c;
        }
        throw std::runtime_error("No camera found with serial number '" + serial_number + "'");
      }();
    }

    if (!Zivid::Firmware::isUpToDate(camera_))
    {
      ROS_INFO("The camera firmware is not up-to-date, starting update");
      Zivid::Firmware::update(camera_, [](double progress, const std::string& state) {
        ROS_INFO("  [%.0f%%] %s", progress, state.c_str());
      });
      ROS_INFO("Firmware update completed");
    }
  }

  ROS_INFO("%s", camera_.toString().c_str());
  if (!file_camera_mode)
  {
    ROS_INFO("Connecting to camera ...");
    camera_.connect();
  }
  ROS_INFO("Connected to camera");

  const auto camera_settings = camera_.settings();
  setupCaptureGeneralConfigNode(camera_settings);

  ROS_INFO("Setting up %d capture_frame dynamic_reconfigure nodes", num_capture_frames);
  for (int i = 0; i < num_capture_frames; i++)
  {
    setupCaptureFrameConfigNode(i, camera_settings);
  }

  ROS_INFO("Advertising topics");
  priv_.param<decltype(use_latched_publisher_for_point_cloud_)>("use_latched_publisher_for_point_cloud", use_latched_publisher_for_point_cloud_, false);
  priv_.param<decltype(use_latched_publisher_for_color_image_)>("use_latched_publisher_for_color_image", use_latched_publisher_for_color_image_, false);
  priv_.param<decltype(use_latched_publisher_for_depth_image_)>("use_latched_publisher_for_depth_image", use_latched_publisher_for_depth_image_, false);
  priv_.param<decltype(publish_point_cloud_with_only_valid_points_)>("publish_point_cloud_with_only_valid_points", publish_point_cloud_with_only_valid_points_, false);
  point_cloud_publisher_ = nh_.advertise<sensor_msgs::PointCloud2>("depth/points", 1, use_latched_publisher_for_point_cloud_);
  color_image_publisher_ = image_transport_.advertiseCamera("color/image_color", 1, use_latched_publisher_for_color_image_);
  depth_image_publisher_ = image_transport_.advertiseCamera("depth/image_raw", 1, use_latched_publisher_for_depth_image_);

  ROS_INFO("Advertising services");

  capture_service_ = advertiseService<zivid_camera::Capture>(
      nh_, "capture", [this](auto& req, auto& res) { return captureServiceHandler(req, res); });

  camera_info_model_name_service_ =
      advertiseService<zivid_camera::CameraInfoModelName>(nh_, "camera_info/model_name", [this](auto&, auto& res) {
        res.model_name = camera_.modelName();
        return true;
      });

  camera_info_serial_number_service_ = advertiseService<zivid_camera::CameraInfoSerialNumber>(
      nh_, "camera_info/serial_number", [this](auto&, auto& res) {
        res.serial_number = camera_.serialNumber().toString();
        return true;
      });

  ROS_INFO("Zivid camera node is now ready!");
}

zivid_camera::ZividCamera::~ZividCamera() = default;

void zivid_camera::ZividCamera::setupCaptureGeneralConfigNode(const Zivid::Settings& defaultSettings)
{
  capture_general_dr_server_ = std::make_unique<dynamic_reconfigure::Server<zivid_camera::CaptureGeneralConfig>>(
      capture_general_dr_server_mutex_, ros::NodeHandle(nh_, "capture_general"));

  // Setup min, max, default and current config
  const auto min_config = getCaptureGeneralConfigMinFromZividSettings(defaultSettings);
  capture_general_dr_server_->setConfigMin(min_config);

  const auto max_config = getCaptureGeneralConfigMaxFromZividSettings(defaultSettings);
  capture_general_dr_server_->setConfigMax(max_config);

  const auto default_config = getCaptureGeneralConfigDefaultFromZividSettings(defaultSettings);
  capture_general_dr_server_->setConfigDefault(default_config);
  capture_general_dr_server_->updateConfig(default_config);

  // Setup the cb, this will invoke the cb, ensuring that the locally cached
  // config is updated.
  capture_general_dr_server_->setCallback(
      boost::bind(&zivid_camera::ZividCamera::onCaptureGeneralConfigChanged, this, _1, _2));
}

void zivid_camera::ZividCamera::setupCaptureFrameConfigNode(int nodeIdx, const Zivid::Settings& defaultSettings)
{
  auto frame_config = std::make_unique<DRFrameConfig>("capture_frame/frame_" + std::to_string(nodeIdx), nh_);

  // Setup min, max, default and current config
  const auto minConfig = getCaptureFrameConfigMinFromZividSettings(defaultSettings);
  frame_config->dr_server.setConfigMin(minConfig);

  const auto max_config = getCaptureFrameConfigMaxFromZividSettings(defaultSettings);
  frame_config->dr_server.setConfigMax(max_config);

  const auto default_config = getCaptureFrameConfigDefaultFromZividSettings(defaultSettings);
  frame_config->dr_server.setConfigDefault(default_config);
  frame_config->dr_server.updateConfig(default_config);

  // Setup the cb, this will invoke the cb, ensuring that frame_config.config is updated.
  frame_config->dr_server.setCallback(boost::bind(&zivid_camera::ZividCamera::onCaptureFrameConfigChanged, this, _1, _2,
                                                  std::ref(*frame_config.get())));

  frame_configs_.push_back(std::move(frame_config));
}

void zivid_camera::ZividCamera::onCaptureGeneralConfigChanged(zivid_camera::CaptureGeneralConfig& config, uint32_t)
{
  ROS_INFO("%s", __func__);
  current_capture_general_config_ = config;
}

void zivid_camera::ZividCamera::onCaptureFrameConfigChanged(zivid_camera::CaptureFrameConfig& config, uint32_t,
                                                            DRFrameConfig& frame_config)
{
  ROS_INFO("%s name='%s'", __func__, frame_config.name.c_str());
  frame_config.config = config;
}

bool zivid_camera::ZividCamera::captureServiceHandler(zivid_camera::Capture::Request&, zivid_camera::Capture::Response&)
{
  ROS_DEBUG("%s", __func__);

  const bool has_point_cloud_subs = point_cloud_publisher_.getNumSubscribers() > 0;
  const bool has_color_img_subs = color_image_publisher_.getNumSubscribers() > 0;
  const bool has_depth_img_subs = depth_image_publisher_.getNumSubscribers() > 0;

  if (has_point_cloud_subs || has_color_img_subs || has_depth_img_subs || use_latched_publisher_for_point_cloud_ || use_latched_publisher_for_color_image_ || use_latched_publisher_for_depth_image_) {
    std::vector<Zivid::Settings> settings;

    Zivid::Settings base_setting = camera_.settings();
    applyCaptureGeneralConfigToZividSettings(current_capture_general_config_, base_setting);

    for (const auto& frame_config : frame_configs_)
    {
      if (frame_config->config.enabled)
      {
        ROS_DEBUG("Config %s is enabled", frame_config->name.c_str());
        Zivid::Settings s{ base_setting };
        applyCaptureFrameConfigToZividSettings(frame_config->config, s);
        settings.push_back(s);
      }
    }

    if (settings.size() > 0)
    {
      ROS_INFO("Capturing with %zd frames", settings.size());
      std::vector<Zivid::Frame> frames;
      frames.reserve(settings.size());
      for (const auto& s : settings)
      {
        camera_.setSettings(s);
        ROS_DEBUG("Calling capture() with settings: %s", camera_.settings().toString().c_str());
        frames.emplace_back(camera_.capture());
      }

      auto frame = [&]() {
        if (frames.size() > 1)
        {
          ROS_DEBUG("Calling Zivid::HDR::combineFrames with %zd frames", frames.size());
          return Zivid::HDR::combineFrames(begin(frames), end(frames));
        }
        else
        {
          return frames[0];
        }
      }();
      publishFrame(std::move(frame));
      return true;
    }
    else
    {
      throw std::runtime_error("Capture called with 0 enabled frames!");
    }
  }
  else
  {
    ROS_INFO("Avoiding capture because there are no subscribers and the latched option was not specified");
    return true;
  }
  return false;
}

void zivid_camera::ZividCamera::publishFrame(Zivid::Frame&& frame)
{
  const bool has_point_cloud_subs = point_cloud_publisher_.getNumSubscribers() > 0;
  const bool has_color_img_subs = color_image_publisher_.getNumSubscribers() > 0;
  const bool has_depth_img_subs = depth_image_publisher_.getNumSubscribers() > 0;

  auto point_cloud = frame.getPointCloud();

  std_msgs::Header header;
  header.seq = header_seq_++;
  header.stamp = ros::Time::now();
  header.frame_id = frame_id_;

  if (has_point_cloud_subs || use_latched_publisher_for_point_cloud_)
  {
    sensor_msgs::PointCloud2ConstPtr point_cloud_msg = makePointCloud2(header, point_cloud);
    ROS_INFO_STREAM("Publishing point cloud with " << (point_cloud_msg->width * point_cloud_msg->height) << " points");
    point_cloud_publisher_.publish(point_cloud_msg);
  }

  if (has_color_img_subs || has_depth_img_subs || use_latched_publisher_for_color_image_ || use_latched_publisher_for_depth_image_)
  {
    auto camera_info = makeCameraInfo(header, point_cloud, camera_.intrinsics());

    if (has_color_img_subs || use_latched_publisher_for_color_image_)
    {
      ROS_INFO("Publishing color image");
      color_image_publisher_.publish(makeColorImage(header, point_cloud), camera_info);
    }

    if (has_depth_img_subs || use_latched_publisher_for_depth_image_)
    {
      ROS_INFO("Publishing depth image");
      depth_image_publisher_.publish(makeDepthImage(header, point_cloud), camera_info);
    }
  }
}

sensor_msgs::PointCloud2ConstPtr zivid_camera::ZividCamera::makePointCloud2(const std_msgs::Header& header,
                                                                            const Zivid::PointCloud& point_cloud)
{
  auto msg = boost::make_shared<sensor_msgs::PointCloud2>();
  fillCommonMsgFields(*msg, header, point_cloud);
  unsigned int number_of_point_fields = 5;
  msg->point_step = number_of_point_fields * sizeof(float);
  msg->is_dense = publish_point_cloud_with_only_valid_points_;
  msg->fields.reserve(number_of_point_fields);
  msg->fields.push_back(createPointField("x", 0, 7, 1));
  msg->fields.push_back(createPointField("y", 4, 7, 1));
  msg->fields.push_back(createPointField("z", 8, 7, 1));
  msg->fields.push_back(createPointField("c", 12, 7, 1));
  msg->fields.push_back(createPointField("rgb", 16, 7, 1));
  msg->data.resize(point_cloud.size() * msg->point_step);

  unsigned int number_of_added_points = 0;
  float* float_pointer = (float*)msg->data.data();
  for (std::size_t i = 0; i < point_cloud.size(); ++i)
  {
    const Zivid::Point& point = point_cloud(i);
    if (!publish_point_cloud_with_only_valid_points_ || (publish_point_cloud_with_only_valid_points_ && !point.isNaN()))
    {
      *(float_pointer++) = point.x * 0.001f; // mm to m
      *(float_pointer++) = point.y * 0.001f; // mm to m
      *(float_pointer++) = point.z * 0.001f; // mm to m
      *(float_pointer++) = point.contrast;
      *((uint32_t*)float_pointer++) = point.rgba;
      ++number_of_added_points;
    }
  }

  if (publish_point_cloud_with_only_valid_points_)
  {
    msg->width = number_of_added_points;
    msg->height = 1;
    msg->data.resize(msg->point_step * number_of_added_points);
  }

  msg->row_step = msg->point_step * msg->width;

  return msg;
}

sensor_msgs::ImageConstPtr zivid_camera::ZividCamera::makeColorImage(const std_msgs::Header& header,
                                                                     const Zivid::PointCloud& point_cloud)
{
  auto img = boost::make_shared<sensor_msgs::Image>();
  fillCommonMsgFields(*img, header, point_cloud);
  img->encoding = sensor_msgs::image_encodings::RGB8;
  img->step = 3 * point_cloud.width();
  img->data.resize(img->step * img->height);

#pragma omp parallel for
  for (std::size_t i = 0; i < point_cloud.size(); i++)
  {
    const auto point = point_cloud(i);
    img->data[3 * i] = point.red();
    img->data[3 * i + 1] = point.green();
    img->data[3 * i + 2] = point.blue();
  }
  return img;
}

sensor_msgs::ImageConstPtr zivid_camera::ZividCamera::makeDepthImage(const std_msgs::Header& header,
                                                                     const Zivid::PointCloud& point_cloud)
{
  auto img = boost::make_shared<sensor_msgs::Image>();
  fillCommonMsgFields(*img, header, point_cloud);
  img->encoding = sensor_msgs::image_encodings::TYPE_32FC1;
  img->step = 4 * point_cloud.width();
  img->data.resize(img->step * img->height);

#pragma omp parallel for
  for (std::size_t i = 0; i < point_cloud.size(); i++)
  {
    float* image_data = reinterpret_cast<float*>(&img->data[4 * i]);
    // Convert from mm to m
    *image_data = point_cloud(i).z * 0.001;
  }
  return img;
}

sensor_msgs::CameraInfoConstPtr zivid_camera::ZividCamera::makeCameraInfo(const std_msgs::Header& header,
                                                                          const Zivid::PointCloud& point_cloud,
                                                                          const Zivid::CameraIntrinsics& intrinsics)
{
  auto msg = boost::make_shared<sensor_msgs::CameraInfo>();
  msg->header = header;
  msg->width = point_cloud.width();
  msg->height = point_cloud.height();
  msg->distortion_model = sensor_msgs::distortion_models::PLUMB_BOB;

  // k1, k2, t1, t2, k3
  const auto distortion = intrinsics.distortion();
  msg->D.resize(5);
  msg->D[0] = distortion.k1().value();
  msg->D[1] = distortion.k2().value();
  msg->D[2] = distortion.p1().value();
  msg->D[3] = distortion.p2().value();
  msg->D[4] = distortion.k3().value();

  // Intrinsic camera matrix for the raw (distorted) images.
  //     [fx  0 cx]
  // K = [ 0 fy cy]
  //     [ 0  0  1]
  const auto camera_matrix = intrinsics.cameraMatrix();
  msg->K[0] = camera_matrix.fx().value();
  msg->K[2] = camera_matrix.cx().value();
  msg->K[4] = camera_matrix.fy().value();
  msg->K[5] = camera_matrix.cy().value();
  msg->K[8] = 1;

  // R (identity)
  msg->R[0] = 1;
  msg->R[4] = 1;
  msg->R[8] = 1;

  // Projection/camera matrix
  //     [fx'  0  cx' Tx]
  // P = [ 0  fy' cy' Ty]
  //     [ 0   0   1   0]
  msg->P[0] = camera_matrix.fx().value();
  msg->P[2] = camera_matrix.cx().value();
  msg->P[5] = camera_matrix.fy().value();
  msg->P[6] = camera_matrix.cy().value();
  msg->P[10] = 1;

  return msg;
}

max_stars_repo_name: carlosmccosta/effective-parakeet

max_issues_repo_name: carlosmccosta/effective-parakeet

max_forks_repo_name: carlosmccosta/effective-parakeet