text:
/* * Converts measured wheel velocities into an an odometry message for use in
 * sensor fusion.
 *
 * Not currently configured to publish transforms, as that is the job of sensor
 * fusion right now.
 *
 * Parameters:
 *   - ~parent_frame: the frame our robot exists in (string, default: "odom")
 *   - ~child_frame: the frame of the robot (string, default: "base_footprint")
 *   - ~wheel_span: the separation of the treads of the robot. (double,
 *   default)
 *   - ~rate: how quickly to publish hz. (double, default 10)
 * Subscribed topics:
 *   - /arduino :(tfr_msgs/ArduinoReading) The most current information coming
 *   in from the sensors.
 * Published topics:
 *   - /drivebase_odom : (nav_msgs/Odometry) the location of the
 *   base_footprint tracked by tread motion.
 * Services:
 *  - /set_drivebase_odometry : (tfr_msgs/SetOdometry) resets the basis of
 *  odometry to a new position
 * */
#include <ros/ros.h>
#include <boost/function.hpp>
#include <tfr_msgs/SetOdometry.h>
#include <tfr_msgs/PoseSrv.h>
#include <geometry_msgs/Quaternion.h>
#include <nav_msgs/Odometry.h>
#include <std_srvs/Empty.h>
#include <tf/transform_datatypes.h>
#include <tf2_ros/transform_broadcaster.h>
#include <geometry_msgs/TransformStamped.h>
#include <tf2/convert.h>
#include <tf2/LinearMath/Quaternion.h>
#include <tf2/LinearMath/Scalar.h>
#include "std_msgs/Float64.h"

class DrivebaseOdometryPublisher
{

    public:
    /********************************************
    *Constructor
    *Preconditions:
    *Postconditions:ROS masternode will have an updated registry of who is
    *       publishing and who is subscribing to what topics
    ********************************************/
    DrivebaseOdometryPublisher(ros::NodeHandle &n,
                const std::string& p_frame,
                const std::string& c_frame,
                const double& wheel_sep) :
            parent_frame{p_frame},
            child_frame{c_frame},
            wheel_span{wheel_sep},
            x{},
            y{},
            angle{},
            tf_broadcaster{}
    {
        //get most current sensor infromation
        boost::function<void(const std_msgs::Float64&)> leftTreadCallback = [this](const std_msgs::Float64& msg) {this->leftTreadSpeed = msg.data; };
        boost::function<void(const std_msgs::Float64&)> rightTreadCallback = [this](const std_msgs::Float64& msg) {this->rightTreadSpeed = msg.data; };

		leftTreadDistanceSub = n.subscribe<std_msgs::Float64>("/left_tread_distance", 15, leftTreadCallback);
        rightTreadDistanceSub = n.subscribe<std_msgs::Float64>("/right_tread_distance", 15, rightTreadCallback);

        //odometry_publisher: publish to the location of the base_footprint tracked by tread motion.
        odometry_publisher = n.advertise<nav_msgs::Odometry>("/drivebase_odom", 15);

        ///set_drivebase_odometry : resets the basis of odometry to a new position
        set_odometry = n.advertiseService("set_drivebase_odometry", &DrivebaseOdometryPublisher::setOdometry, this);
        reset_odometry = n.advertiseService("reset_drivebase_odometry", &DrivebaseOdometryPublisher::resetOdometry, this);
        angle.x = 0;
        angle.y = 0;
        angle.z = 0;
        angle.w = 1;
    }

    ~DrivebaseOdometryPublisher() = default;
    DrivebaseOdometryPublisher(const DrivebaseOdometryPublisher&) = delete;
    DrivebaseOdometryPublisher& operator=(const DrivebaseOdometryPublisher&) = delete;
    DrivebaseOdometryPublisher(DrivebaseOdometryPublisher&&) = delete;
    DrivebaseOdometryPublisher& operator=(DrivebaseOdometryPublisher&) = delete;

    /*****************************************************************************************
    * processOdometry: Main business logic for the node, takes in readings from the arduino,
    *       and publishes them across the network.
    * Preconditions: is subscribed to recieve information from the sensors (tfr_msgs/ArduinoReading)
    * Postconditions: Readings from the arduino are published across the network
    *****************************************************************************************/
    void processOdometry()
    {
        //first we process the data
        auto t_1 = ros::Time::now();
        double d_t = (t_1 - t_0).toSec();

        //if this is the first message we skip it to initialize time
        //properly
        if (!t_0.isValid())
        {
            t_0 = ros::Time::now();
            return;
        }

        //basic differential kinematics to get combined velocities
        double v_ang = (rightTreadSpeed-leftTreadSpeed)/wheel_span;
        double v_lin = (rightTreadSpeed+leftTreadSpeed)/2;

        //break into xy components and increment
        double d_angle = v_ang * d_t;
        rotateQuaternionByYaw(angle, d_angle);

        // yaw (z-axis rotation)
        auto yaw = quaternionToYaw(angle);
        double v_x = v_lin*cos(yaw);
        double v_y = v_lin*sin(yaw);

        double d_x = v_x * d_t;
        x += d_x;

        double d_y = v_y * d_t;
        y += d_y;

        t_0 = t_1;

        //let's package up the message
        nav_msgs::Odometry msg;
        msg.header.stamp = ros::Time::now();
        msg.header.frame_id = parent_frame;
        msg.child_frame_id = child_frame;

        msg.pose.pose.position.x = x;
        msg.pose.pose.position.y = y;
        msg.pose.pose.position.z = 0;
        msg.pose.pose.orientation = angle;
        msg.pose.covariance = { 1e-1,    0,    0,    0,    0,    0,
            0, 1e-1,    0,    0,    0,    0,
            0,    0, 1e-1,    0,    0,    0,
            0,    0,    0, 1e-1,    0,    0,
            0,    0,    0,    0, 1e-1,    0,
            0,    0,    0,    0,    0, 1e-1 };

        msg.twist.twist.linear.x = v_x;
        msg.twist.twist.linear.y = v_y;
        msg.twist.twist.linear.z = 0;
        msg.twist.twist.angular.x = 0;
        msg.twist.twist.angular.y = 0;
        msg.twist.twist.angular.z = v_ang;
        msg.twist.covariance = { 5e-2,    0,    0,    0,    0,    0,
            0, 5e-2,    0,    0,    0,    0,
            0,    0, 5e-2,    0,    0,    0,
            0,    0,    0, 5e-2,    0,    0,
            0,    0,    0,    0, 5e-2,    0,
            0,    0,    0,    0,    0, 5e-2 };
        //publish the message
        odometry_publisher.publish(msg);
    }

    private:

        ros::Subscriber leftTreadDistanceSub, rightTreadDistanceSub; //the encoder data sub
        ros::Publisher odometry_publisher; //the pub for our processed data
        ros::ServiceServer set_odometry;
        ros::ServiceServer reset_odometry;
        tf2_ros::TransformBroadcaster tf_broadcaster;
        const std::string& parent_frame; //the parent frame of the robot
        const std::string& child_frame; //the child frame of the robot
        const double& wheel_span;
        double leftTreadSpeed, rightTreadSpeed;
        double x; //the x coordinate of the robot (meters)
        double y; //the y coordinate of the robot (meters)
        geometry_msgs::Quaternion angle;
        const double MAX_XY_DELTA = 0.25;
        const double MAX_THETA_DELTA = 0.065;
        ros::Time t_0;

    /******************************************************************************************************
    * setOdometry: Set odometry from fiducial markers, provides smoothing
    * Preconditions: can advertise to set_drivebase_odometry topic, can provide service to
    *               /set_drivebase_odometry : (tfr_msgs/SetOdometry)
    * Postconditions: angle is updated with its new value, true is returned after the angle has been updated
    *********************************************************************************************************/
    bool setOdometry(tfr_msgs::SetOdometry::Request& request,
            tfr_msgs::SetOdometry::Response& response)
    {

        auto dx = request.pose.position.x - x;
        if (std::abs(dx) >= MAX_XY_DELTA)
            dx = (dx >= 0) ? MAX_XY_DELTA : -MAX_XY_DELTA;
        x += dx;

        auto dy = request.pose.position.y - y;
        if (std::abs(dy) > MAX_XY_DELTA)
            dy = (dy >= 0) ? MAX_XY_DELTA : -MAX_XY_DELTA;
        y += dy;

        auto new_q = getTfQuaternion(request.pose.orientation);
        auto old_q = getTfQuaternion(angle);
        auto delta = new_q * old_q.inverse();
        if (std::abs(delta.getZ()) > MAX_THETA_DELTA)
        {
            auto sign = ( delta.getZ() * delta.getW() >= 0)? 1 : -1;
            tf2::Quaternion rotation{0.0, 0.0, 0.065 * sign, 0.998};
            auto new_value = old_q * rotation;
            angle = getStdQuaternion(new_value);
        }
        else
            angle = request.pose.orientation;
        return true;
    }

    /******************************************************************************************************
    * setOdometry: Set odometry from fiducial markers, provides no smoothing
    * Preconditions: can advertise to set_drivebase_odometry topic, can provide service to
    *               /set_drivebase_odometry : (tfr_msgs/SetOdometry)
    * Postconditions: outputs message stating that odometry has been reset, angel has been reset based on position,
    *               true is returned after angle has been updated
    *********************************************************************************************************/
    bool resetOdometry(tfr_msgs::SetOdometry::Request& request,
            tfr_msgs::SetOdometry::Response& response)
    {
        ROS_INFO("Drivebase Odometry Publisher: resetting drivebase odometry");

        x = request.pose.position.x;
        y = request.pose.position.y;
        angle = request.pose.orientation;
        return true;
    }

    /***************************************************************************
    * tf2::Quaternion getTfQuaternion: create a quaternion based on orientation
    * Preconditions: can determin orientiation
    * Postconditions: a quaternion value is returned
    ****************************************************************************/
    tf2::Quaternion getTfQuaternion(geometry_msgs::Quaternion& q)
    {
        tf2::Quaternion q_0{q.x, q.y, q.z, q.w};
        return q_0;
    }

    /*************************************************************************************************
    * geometry_msgs::Quaternion getStdQuaternion: create a quaternion based on a different quaternion
    * Preconditions: quaternion parameter is initalized
    * Postconditions: a quaternion value is returned
    ***************************************************************************************************/
    geometry_msgs::Quaternion getStdQuaternion(tf2::Quaternion& q_0)
    {
        geometry_msgs::Quaternion q;
        q.x = q_0.getX();
        q.y = q_0.getY();
        q.z = q_0.getZ();
        q.w = q_0.getW();
        return q;
    }

    /*************************************************************************
     * quaternionToYaw: converts a quaterion value to a yaw (z-axis rotation)
     * Preconditions: quaternion parameter is initalized
     * Postconditions: yaw value is returned
     *************************************************************************/
    double quaternionToYaw(geometry_msgs::Quaternion& q)
    {
        // yaw (z-axis rotation)
        double siny = +2.0 * (q.w * q.z + q.x * q.y);
        double cosy = +1.0 - 2.0 * (q.y*q.y + q.z*q.z);
        double result = atan2(siny, cosy);
        return result;
    }

    /*************************************************************************
     * rotateQuaternionByYaw: rotates a quaternion value by a yaw (z-axis rotation)
     * Preconditions: quaternion and yaw parameters are initalized
     * Postconditions: quaternion paramater is updated with the new values
     *************************************************************************/
    void rotateQuaternionByYaw(geometry_msgs::Quaternion& q, double yaw)
    {
        tf2::Quaternion q_0{q.x, q.y, q.z, q.w};
        tf2::Quaternion q_1{};
        q_1.setRPY(0, 0, yaw);
        q_0 *= q_1;
        q.x = q_0.getX();
        q.y = q_0.getY();
        q.z = q_0.getZ();
        q.w = q_0.getW();
    }
};

int main(int argc, char **argv)
{
    ros::init(argc, argv, "drivebase_odometry_publisher");

    //NodeHandle is the main access point to communications with the ROS system.
    ros::NodeHandle n;
    std::string parent_frame, child_frame;
    double wheel_span; //wheel_span: the separation of the treads of the robot.
    double rate; //rate: how quickly to publish hz.
    ros::param::param<std::string>("~parent_frame", parent_frame, "odom");
    ros::param::param<std::string>("~child_frame", child_frame, "base_footprint");
    ros::param::param<double>("~wheel_span", wheel_span, 0.645);
    ros::param::param<double>("~rate", rate, 10.0);
    DrivebaseOdometryPublisher publisher{n, parent_frame, child_frame, wheel_span};
    ros::Rate loop_rate(rate);
    while(ros::ok())
    {
        publisher.processOdometry(); //arduino readings are published across the network
        ros::spinOnce();
        loop_rate.sleep();

    }
    return 0;
}


text:
#include <cetty/zurg/slave/Heartbeat.h>

#include <stdlib.h>
#include <sys/utsname.h>
#include <boost/date_time/posix_time/ptime.hpp>

#include <cetty/util/Process.h>
#include <cetty/util/SmallFile.h>
#include <cetty/channel/EventLoop.h>
#include <cetty/config/ConfigCenter.h>
#include <cetty/logging/LoggerHelper.h>
#include <cetty/protobuf/service/service.pb.h>

#include <cetty/zurg/Util.h>
#include <cetty/zurg/master/master_service.pb.h>

namespace cetty {
namespace zurg {
namespace slave {

using namespace cetty::util;
using namespace cetty::zurg;
using namespace cetty::protobuf::service;
using namespace cetty::zurg::master;

void ignoreCallback(const Empty*) {

}

// unique_ptr is better
typedef boost::shared_ptr<SmallFile> SmallFilePtr;

class ProcFs : boost::noncopyable {
public:
    typedef std::map<StringPiece, SmallFilePtr> FileMap;

    // char* to save construction of string.
    int readTo(const char* filename, std::string* out) {
        FileMap::iterator it = files_.find(filename);

        if (it == files_.end()) {
            SmallFilePtr ptr(new SmallFile(filename));
            it = files_.insert(std::make_pair(filename, ptr)).first;
        }

        assert(it != files_.end());
        int size = 0;
        int err = it->second->readToBuffer(&size);
        LOG_TRACE << filename << " " << err << " " << size;

        if (size > 0) {
            out->assign(it->second->buffer(), size);
        }

        return err;
    }

private:
    FileMap files_;
};

void strip_cpuinfo(std::string* cpuinfo) {
    // FIXME:
}

void fill_uname(SlaveHeartbeat* hb) {
    struct utsname buf;

    if (::uname(&buf) == 0) {
        SlaveHeartbeat::Uname* p = hb->mutable_uname();
        p->set_sys_name(buf.sysname);
        p->set_node_name(buf.nodename);
        p->set_release(buf.release);
        p->set_version(buf.version);
        p->set_machine(buf.machine);
        p->set_domain_name(buf.domainname);
    }
    else {
        LOG_ERROR << "uname";
    }
}

void strip_diskstats(std::string* diskstats) {
    std::string result;
    result.reserve(diskstats->size());
    StringPiece zeros(" 0 0 0 0 0 0 0 0 0 0 0\n");

    const char* p = diskstats->c_str();
    const char* nl = NULL;

    while ((nl = ::strchr(p, '\n')) != NULL) {
        int pos = static_cast<int>(nl - p + 1);
        StringPiece line(p, pos);

        if (line.size() > zeros.size()) {
            StringPiece end(line.data() + line.size()-zeros.size(), zeros.size());

            if (end != zeros) {
                result.append(line.data(), line.size());
            }
        }

        p += pos;
    }

    assert(p == &*diskstats->end());
    diskstats->swap(result);
}

struct AreBothSpaces {
    bool operator()(char x, char y) const {
        return x == ' ' && y == ' ';
    }
};

void strip_meminfo(std::string* meminfo) {
    std::string::iterator it =
        std::unique(meminfo->begin(), meminfo->end(), AreBothSpaces());
    meminfo->erase(it, meminfo->end());
}

void strip_stat(std::string* proc_stat) {
    const char* intr = ::strstr(proc_stat->c_str(), "\nintr ");

    if (intr != NULL) {
        const char* nl = ::strchr(intr + 1, '\n');
        assert(nl != NULL);

        StringPiece line(intr+1, static_cast<int>(nl-intr-1));
        const char* p = nl;

        while (p[-1] == '0' && p[-2] == ' ') {
            p -= 2;
        }

        ++p;
        proc_stat->erase(p - proc_stat->c_str(), nl-p);
    }
}

Heartbeat::Heartbeat(const EventLoopPtr& loop,
                     MasterService_Stub* stub)
    : loop_(loop),
      name_(std::string()),
      port_(0),
      stub_(stub),
      procFs_(new ProcFs),
      beating_(false) {
    //ConfigCenter::instance().configure(&config_);
    init();
}

Heartbeat::~Heartbeat() {

}

void Heartbeat::init() {
    // todo init data about config if some data is not inited
    //name_ = config_.name;

    //if (config_.listenPort <= 0) {
    //    LOG_ERROR << "Slave listen port not greater than 0.";
    //    exit(0);
    //}

    //port_ = config_.listenPort;

    //if (config_.heartbeatInterval <= 0) { config_.heartbeatInterval = 3000; }
}

void Heartbeat::start() {
    beating_ = true;
    loop_->runEvery(heartbeatInterval_, boost::bind(&Heartbeat::onTimer, this));
}

void Heartbeat::stop() {
    beating_ = false;
}

void Heartbeat::onTimer() {
    if (beating_) {
        beat(false);
    }
}

#define FILL_HB(PROC_FILE, FIELD)               \
    if (procFs_->readTo(PROC_FILE, hb.mutable_##FIELD()) != 0)     \
        hb.clear_##FIELD();

void Heartbeat::beat(bool showStatic) {
    LOG_DEBUG << (showStatic ? "full" : "");
    SlaveHeartbeat hb;
    hb.set_slave_name(name_);

    if (showStatic) {
        hb.set_host_name(hostname().c_str());

        if (port_ > 0) {
            hb.set_listen_port(port_);
        }

        hb.set_slave_pid(cetty::util::Process::id());
        hb.set_start_time(getMicroSecs(g_startTime));
        // hb.set_slave_version(slave_version);
        FILL_HB("/proc/cpuinfo", cpu_info);
        FILL_HB("/proc/version", version);
        FILL_HB("/etc/mtab", etc_mtab);
        strip_cpuinfo(hb.mutable_cpu_info());
        // sysctl
        fill_uname(&hb);
    }

    hb.set_send_time(now());

    FILL_HB("/proc/meminfo", mem_info);
    FILL_HB("/proc/stat", proc_stat);
    FILL_HB("/proc/loadavg", load_avg);
    FILL_HB("/proc/diskstats", disk_stats);
    FILL_HB("/proc/net/dev", net_dev);
    FILL_HB("/proc/net/tcp", net_tcp);
    strip_diskstats(hb.mutable_disk_stats());
    strip_meminfo(hb.mutable_mem_info());
    strip_stat(hb.mutable_proc_stat());

    // todo fix error
    SlaveHeartbeatServiceFuturePtr hbsf = new SlaveHeartbeatServiceFuture();
    stub_->slaveHeartbeat(&hb, hbsf);
}

}
}
}

ext: cpp


text:
/*

Copyright (c) 2010-2021, Arvid Norberg
Copyright (c) 2015-2018, 2020-2021, Alden Torres
Copyright (c) 2017, Steven Siloti
Copyright (c) 2020, Paul-Louis Ageneau
All rights reserved.

You may use, distribute and modify this code under the terms of the BSD license,
see LICENSE file.
*/

#ifndef TORRENT_UTP_STREAM_HPP_INCLUDED
#define TORRENT_UTP_STREAM_HPP_INCLUDED

#include "libtorrent/aux_/udp_socket.hpp"
#include "libtorrent/aux_/io_bytes.hpp"
#include "libtorrent/aux_/packet_buffer.hpp"
#include "libtorrent/error_code.hpp"
#include "libtorrent/time.hpp"
#include "libtorrent/close_reason.hpp"
#include "libtorrent/aux_/timestamp_history.hpp"
#include "libtorrent/aux_/sliding_average.hpp"
#include "libtorrent/address.hpp"
#include "libtorrent/aux_/invariant_check.hpp"
#include "libtorrent/aux_/storage_utils.hpp" // for iovec_t

#include <functional>

#ifndef BOOST_NO_EXCEPTIONS
#include "libtorrent/aux_/disable_warnings_push.hpp"
#include <boost/system/system_error.hpp>
#include "libtorrent/aux_/disable_warnings_pop.hpp"
#endif

namespace libtorrent::aux {

#ifndef TORRENT_UTP_LOG_ENABLE
	#define TORRENT_UTP_LOG 0
	#define TORRENT_VERBOSE_UTP_LOG 0
#else
	#define TORRENT_UTP_LOG 1
	#define TORRENT_VERBOSE_UTP_LOG 1
#endif

#if TORRENT_UTP_LOG
	TORRENT_FORMAT(1, 2)
	void utp_log(char const* fmt, ...);
	TORRENT_EXPORT bool is_utp_stream_logging();

	// This function should be used at the very beginning and very end of your program.
	TORRENT_EXPORT void set_utp_stream_logging(bool enable);
#endif

	TORRENT_EXTRA_EXPORT bool compare_less_wrap(std::uint32_t lhs
		, std::uint32_t rhs, std::uint32_t mask);

	struct utp_socket_manager;

	// internal: the point of the bif_endian_int is two-fold
	// one purpose is to not have any alignment requirements
	// so that any buffer received from the network can be cast
	// to it and read as an integer of various sizes without
	// triggering a bus error. The other purpose is to convert
	// from network byte order to host byte order when read and
	// written, to offer a convenient interface to both interpreting
	// and writing network packets
	template <class T> struct big_endian_int
	{
		big_endian_int& operator=(T v) &
		{
			char* p = m_storage;
			aux::write_impl<T>(v, p);
			return *this;
		}
		operator T() const
		{
			const char* p = m_storage;
			return aux::read_impl(p, aux::type<T>());
		}
	private:
		char m_storage[sizeof(T)];
	};

	using be_uint64 = big_endian_int<std::uint64_t>;
	using be_uint32 = big_endian_int<std::uint32_t>;
	using be_uint16 = big_endian_int<std::uint16_t>;
	using be_int64 = big_endian_int<std::int64_t>;
	using be_int32 = big_endian_int<std::int32_t>;
	using be_int16 = big_endian_int<std::int16_t>;

/*
	uTP header from BEP 29

	0       4       8               16              24              32
	+-------+-------+---------------+---------------+---------------+
	| type  | ver   | extension     | connection_id                 |
	+-------+-------+---------------+---------------+---------------+
	| timestamp_microseconds                                        |
	+---------------+---------------+---------------+---------------+
	| timestamp_difference_microseconds                             |
	+---------------+---------------+---------------+---------------+
	| wnd_size                                                      |
	+---------------+---------------+---------------+---------------+
	| seq_nr                        | ack_nr                        |
	+---------------+---------------+---------------+---------------+

*/

// internal: the different kinds of uTP packets
enum utp_socket_state_t : std::uint8_t
{ ST_DATA, ST_FIN, ST_STATE, ST_RESET, ST_SYN, NUM_TYPES };

// internal: extension headers. 2 is skipped because there is a deprecated
// extension with that number in the wild
enum utp_extensions_t : std::uint8_t
{ utp_no_extension = 0, utp_sack = 1, utp_close_reason = 3 };

struct utp_header
{
	std::uint8_t type_ver;
	std::uint8_t extension;
	be_uint16 connection_id;
	be_uint32 timestamp_microseconds;
	be_uint32 timestamp_difference_microseconds;
	be_uint32 wnd_size;
	be_uint16 seq_nr;
	be_uint16 ack_nr;

	int get_type() const { return type_ver >> 4; }
	int get_version() const { return type_ver & 0xf; }
};

struct utp_socket_impl;
struct utp_socket_interface;
struct utp_stream;

// this is the user-level stream interface to utp sockets.
// the reason why it's split up in a utp_stream class and
// an implementation class is because the socket state has
// to be able to out-live the user level socket. For instance
// when sending data on a stream and then closing it, the
// state holding the send buffer has to be kept around until
// it has been flushed, which may be longer than the client
// will keep the utp_stream object around for.
// for more details, see utp_socket_impl, which is analogous
// to the kernel state for a socket. It's defined in utp_stream.cpp
struct TORRENT_EXTRA_EXPORT utp_stream
{
	using lowest_layer_type = utp_stream ;
	using endpoint_type = tcp::socket::endpoint_type;
	using protocol_type = tcp::socket::protocol_type;

	using executor_type = tcp::socket::executor_type;
	executor_type get_executor() { return m_io_service.get_executor(); }

	explicit utp_stream(io_context& io_context);
	~utp_stream();
	utp_stream& operator=(utp_stream const&) = delete;
	utp_stream(utp_stream const&) = delete;
	utp_stream& operator=(utp_stream&&) noexcept = delete;
	utp_stream(utp_stream&&) noexcept;

	lowest_layer_type& lowest_layer() { return *this; }
	lowest_layer_type const& lowest_layer() const { return *this; }

	// used for incoming connections
	void set_impl(utp_socket_impl*);
	utp_socket_impl* get_impl();

#ifndef BOOST_NO_EXCEPTIONS
	template <class IO_Control_Command>
	void io_control(IO_Control_Command&) {}
#endif

	template <class IO_Control_Command>
	void io_control(IO_Control_Command&, error_code&) {}

#ifndef BOOST_NO_EXCEPTIONS
	void non_blocking(bool) {}
#endif

	void non_blocking(bool, error_code&) {}

#ifndef BOOST_NO_EXCEPTIONS
	void bind(endpoint_type const& /*endpoint*/) {}
#endif

	void bind(endpoint_type const&, error_code&);

#ifndef BOOST_NO_EXCEPTIONS
	template <class SettableSocketOption>
	void set_option(SettableSocketOption const&) {}
#endif

	template <class SettableSocketOption>
	void set_option(SettableSocketOption const&, error_code&) { }

#ifndef BOOST_NO_EXCEPTIONS
	template <class GettableSocketOption>
	void get_option(GettableSocketOption&) {}
#endif

	template <class GettableSocketOption>
	void get_option(GettableSocketOption&, error_code&) {}

	void cancel(error_code&)
	{
		cancel_handlers(boost::asio::error::operation_aborted);
	}

	void close();
	void close(error_code const&) { close(); }

	void set_close_reason(close_reason_t code);
	close_reason_t get_close_reason() const;

	bool is_open() const { return m_open; }

	int read_buffer_size() const;
	static void on_read(utp_stream* self, std::size_t bytes_transferred
		, error_code const& ec, bool shutdown);
	static void on_write(utp_stream* self, std::size_t bytes_transferred
		, error_code const& ec, bool shutdown);
	static void on_connect(utp_stream* self, error_code const& ec, bool shutdown);
	static void on_close_reason(utp_stream* self, close_reason_t reason);

	void add_read_buffer(void* buf, int len);
	void issue_read();
	void add_write_buffer(void const* buf, int len);
	void issue_write();
	std::size_t read_some(bool clear_buffers);
	std::size_t write_some(bool clear_buffers);

	int send_delay() const;
	int recv_delay() const;

	void do_connect(tcp::endpoint const& ep);

	endpoint_type local_endpoint() const
	{
		error_code ec;
		return local_endpoint(ec);
	}

	endpoint_type local_endpoint(error_code& ec) const;

	endpoint_type remote_endpoint() const
	{
		error_code ec;
		return remote_endpoint(ec);
	}

	endpoint_type remote_endpoint(error_code& ec) const;

	std::size_t available() const;
	std::size_t available(error_code& /*ec*/) const { return available(); }

	template <class Handler>
	void async_connect(endpoint_type const& endpoint, Handler handler)
	{
		if (m_impl == nullptr)
		{
			post(m_io_service, std::bind<void>(std::move(handler), boost::asio::error::not_connected));
			return;
		}

		m_connect_handler = std::move(handler);
		do_connect(endpoint);
	}

	template <class Mutable_Buffers, class Handler>
	void async_read_some(Mutable_Buffers const& buffers, Handler handler)
	{
		if (m_impl == nullptr)
		{
			post(m_io_service, std::bind<void>(std::move(handler), boost::asio::error::not_connected, std::size_t(0)));
			return;
		}

		TORRENT_ASSERT(!m_read_handler);
		if (m_read_handler)
		{
			post(m_io_service, std::bind<void>(std::move(handler), boost::asio::error::operation_not_supported, std::size_t(0)));
			return;
		}
		std::size_t bytes_added = 0;
		for (auto i = buffer_sequence_begin(buffers)
			, end(buffer_sequence_end(buffers)); i != end; ++i)
		{
			if (i->size() == 0) continue;
			add_read_buffer(i->data(), int(i->size()));
			bytes_added += i->size();
		}
		if (bytes_added == 0)
		{
			// if we're reading 0 bytes, post handler immediately
			// asio's SSL layer depends on this behavior
			post(m_io_service, std::bind<void>(std::move(handler), error_code(), std::size_t(0)));
			return;
		}

		m_read_handler = std::move(handler);
		issue_read();
	}

	template <class Protocol>
	void open(Protocol const&, error_code&)
	{ m_open = true; }

	template <class Protocol>
	void open(Protocol const&)
	{ m_open = true; }

	template <class Mutable_Buffers>
	std::size_t read_some(Mutable_Buffers const& buffers, error_code& ec)
	{
		TORRENT_ASSERT(!m_read_handler);
		if (m_impl == nullptr)
		{
			ec = boost::asio::error::not_connected;
			return 0;
		}

		if (read_buffer_size() == 0)
		{
			ec = boost::asio::error::would_block;
			return 0;
		}
#if TORRENT_USE_ASSERTS
		size_t buf_size = 0;
#endif

		for (auto i = buffer_sequence_begin(buffers)
			, end(buffer_sequence_end(buffers)); i != end; ++i)
		{
			add_read_buffer(i->data(), int(i->size()));
#if TORRENT_USE_ASSERTS
			buf_size += i->size();
#endif
		}
		std::size_t ret = read_some(true);
		TORRENT_ASSERT(ret <= buf_size);
		TORRENT_ASSERT(ret > 0);
		return ret;
	}

	template <class Const_Buffers>
	std::size_t write_some(Const_Buffers const& buffers, error_code& ec)
	{
		TORRENT_ASSERT(!m_write_handler);
		if (m_impl == nullptr)
		{
			ec = boost::asio::error::not_connected;
			return 0;
		}

		size_t buf_size = 0;

		for (auto i = buffer_sequence_begin(buffers)
			, end(buffer_sequence_end(buffers)); i != end; ++i)
		{
			if (i->size() == 0) continue;
			add_write_buffer(i->data(), int(i->size()));
			buf_size += i->size();
		}
		std::size_t ret = write_some(true);
		TORRENT_ASSERT(ret <= buf_size);
		if(ret == 0 && buf_size > 0)
		{
			ec = boost::asio::error::would_block;
			return 0;
		}
		return ret;
	}

#ifndef BOOST_NO_EXCEPTIONS
	template <class Mutable_Buffers>
	std::size_t read_some(Mutable_Buffers const& buffers)
	{
		error_code ec;
		std::size_t ret = read_some(buffers, ec);
		if (ec)
			boost::throw_exception(boost::system::system_error(ec));
		return ret;
	}

	template <class Const_Buffers>
	std::size_t write_some(Const_Buffers const& buffers)
	{
		error_code ec;
		std::size_t ret = write_some(buffers, ec);
		if (ec)
			boost::throw_exception(boost::system::system_error(ec));
		return ret;
	}
#endif

	template <class Const_Buffers, class Handler>
	void async_write_some(Const_Buffers const& buffers, Handler handler)
	{
		if (m_impl == nullptr)
		{
			post(m_io_service, std::bind<void>(std::move(handler)
				, boost::asio::error::not_connected, std::size_t(0)));
			return;
		}

		TORRENT_ASSERT(!m_write_handler);
		if (m_write_handler)
		{
			post(m_io_service, std::bind<void>(std::move(handler)
				, boost::asio::error::operation_not_supported, std::size_t(0)));
			return;
		}

		std::size_t bytes_added = 0;
		for (auto i = buffer_sequence_begin(buffers)
			, end(buffer_sequence_end(buffers)); i != end; ++i)
		{
			if (i->size() == 0) continue;
			add_write_buffer(i->data(), int(i->size()));
			bytes_added += i->size();
		}
		if (bytes_added == 0)
		{
			// if we're writing 0 bytes, post handler immediately
			// asio's SSL layer depends on this behavior
			post(m_io_service, std::bind<void>(std::move(handler), error_code(), std::size_t(0)));
			return;
		}
		m_write_handler = std::move(handler);
		issue_write();
	}

#if BOOST_VERSION >= 106600
	// Compatiblity with the async_wait method introduced in boost 1.66

	enum wait_type { wait_read, wait_write, wait_error };

	template <class Handler>
	void async_wait(wait_type type, Handler handler) {
		switch(type)
		{
		case wait_read:
			async_read_some(boost::asio::null_buffers()
					, [handler](error_code ec, size_t) { handler(std::move(ec)); });
			break;

		case wait_write:
			async_write_some(boost::asio::null_buffers()
					, [handler](error_code ec, size_t) { handler(std::move(ec)); });
			break;

		case wait_error:
			post(m_io_service, std::bind<void>(std::move(handler)
					, boost::asio::error::operation_not_supported));
            break;
		}
	}
#endif

private:

	void cancel_handlers(error_code const&);

	std::function<void(error_code const&)> m_connect_handler;
	std::function<void(error_code const&, std::size_t)> m_read_handler;
	std::function<void(error_code const&, std::size_t)> m_write_handler;

	io_context& m_io_service;
	utp_socket_impl* m_impl;

	close_reason_t m_incoming_close_reason = close_reason_t::none;

	// this field requires another 8 bytes (including padding)
	bool m_open;
};

// since the uTP socket state may be needed after the
// utp_stream is closed, it's kept in a separate struct
// whose lifetime is not tied to the lifetime of utp_stream

// the utp socket is closely modelled after the asio async
// operations and handler model. For writing to the socket,
// the client provides a list of buffers (for gather/writev
// style of I/O) and whenever the socket can write another
// packet to the stream, it picks up data from these buffers.
// When all of the data has been written, or enough time has
// passed since we first started writing, the write handler
// is called and the write buffer is reset. This means that
// we're not writing anything at all while waiting for the
// client to re-issue a write request.

// reading is a little bit more complicated, since we must
// be able to receive data even when the user doesn't have
// an outstanding read operation on the socket. When the user
// does however, we want to receive data directly into the
// user's buffer instead of first copying it into our receive
// buffer. This is why the receive case is more complicated.
// There are two receive buffers. One provided by the user,
// which when present is always used. The other one is used
// when the user doesn't have an outstanding read request,
// and hence hasn't provided any buffer space to receive into.

// the user provided read buffer is called "m_read_buffer" and
// its size is "m_read_buffer_size". The buffer we spill over
// into when the user provided buffer is full or when there
// is none, is "m_receive_buffer" and "m_receive_buffer_size"
// respectively.

// in order to know when to trigger the read and write handlers
// there are two counters, m_read and m_written, which count
// the number of bytes we've stuffed into the user provided
// read buffer or written to the stream from the write buffer.
// These are used to trigger the handlers if we're written a
// large number of bytes. It's also triggered if we're filled
// the whole read buffer, or written the entire write buffer.
// The last way the handlers can be triggered is if we're read
// or written some, and enough time has elapsed since then.

// when we receive data into m_receive_buffer (i.e. the buffer
// used when there's no user provided one) is stored as a
// number of heap allocated packets. This is just because it's
// simple to reuse the data structured and it provides all the
// functionality needed for this buffer.

struct utp_socket_impl
{
#if TORRENT_USE_INVARIANT_CHECKS
	friend struct ::libtorrent::invariant_access;
#endif

	utp_socket_impl(std::uint16_t recv_id, std::uint16_t send_id
		, utp_stream* userdata, utp_socket_manager& sm);

	~utp_socket_impl();

	void tick(time_point now);
	void init_mtu(int mtu);
	bool incoming_packet(span<char const> buf
		, udp::endpoint const& ep, time_point receive_time);
	void writable();

	bool should_delete() const;
	tcp::endpoint remote_endpoint(error_code& ec) const;
	std::size_t available() const;
	// returns true if there were handlers cancelled
	// if it returns false, we can detach immediately
	bool destroy();
	void set_close_reason(close_reason_t code);
	void detach();
	void send_syn();
	void send_fin();

	void subscribe_drained();
	void defer_ack();
	void remove_sack_header(packet* p);

	enum packet_flags_t { pkt_ack = 1, pkt_fin = 2 };
	bool send_pkt(int flags = 0);
	bool resend_packet(packet* p, bool fast_resend = false);
	void send_reset(utp_header const* ph);
	std::pair<std::uint32_t, int> parse_sack(std::uint16_t packet_ack, std::uint8_t const* ptr
		, int size, time_point now);
	void parse_close_reason(std::uint8_t const* ptr, int size);
	void write_payload(std::uint8_t* ptr, int size);
	void maybe_inc_acked_seq_nr();
	std::uint32_t ack_packet(packet_ptr p, time_point receive_time
		, std::uint16_t seq_nr);
	void write_sack(std::uint8_t* buf, int size) const;
	void incoming(std::uint8_t const* buf, int size, packet_ptr p, time_point now);
	void do_ledbat(int acked_bytes, int delay, int in_flight);
	int packet_timeout() const;
	bool test_socket_state();
	void maybe_trigger_receive_callback();
	void maybe_trigger_send_callback();
	bool cancel_handlers(error_code const& ec, bool shutdown);
	bool consume_incoming_data(
		utp_header const* ph, std::uint8_t const* ptr, int payload_size, time_point now);
	void update_mtu_limits();
	void experienced_loss(std::uint32_t seq_nr, time_point now);

	void send_ack();
	void socket_drained();

	void set_userdata(utp_stream* s) { m_userdata = s; }
	void abort();
	udp::endpoint remote_endpoint() const;

	std::uint16_t receive_id() const { return m_recv_id; }
	bool match(udp::endpoint const& ep, std::uint16_t id) const;

	// non-copyable
	utp_socket_impl(utp_socket_impl const&) = delete;
	utp_socket_impl const& operator=(utp_socket_impl const&) = delete;

	// The underlying UDP socket this uTP socket is bound to
	// TODO: it would be nice to make this private
	std::weak_ptr<utp_socket_interface> m_sock;

	void add_write_buffer(void const* buf, int len);
	void add_read_buffer(void* buf, int len);

	int send_delay() const { return m_send_delay; }
	int recv_delay() const { return m_recv_delay; }

	void issue_read();
	void issue_write();

	void do_connect(tcp::endpoint const& ep);

	std::size_t read_some(bool const clear_buffers);
	std::size_t write_some(bool const clear_buffers); // Warning: non-blocking
	int receive_buffer_size() const { return m_receive_buffer_size; }

	bool null_buffers() const { return m_null_buffers; }

private:

	// it's important that these match the enums in performance_counters for
	// num_utp_idle etc.
	enum class state_t {
		// not yet connected
		none,
		// sent a syn packet, not received any acks
		syn_sent,
		// syn-ack received and in normal operation
		// of sending and receiving data
		connected,
		// fin sent, but all packets up to the fin packet
		// have not yet been acked. We might still be waiting
		// for a FIN from the other end
		fin_sent,

		// ====== states beyond this point =====
		// === are considered closing states ===
		// === and will cause the socket to ====
		// ============ be deleted =============

		// the socket has been gracefully disconnected
		// and is waiting for the client to make a
		// socket call so that we can communicate this
		// fact and actually delete all the state, or
		// there is an error on this socket and we're
		// waiting to communicate this to the client in
		// a callback. The error in either case is stored
		// in m_error. If the socket has gracefully shut
		// down, the error is error::eof.
		error_wait,

		// there are no more references to this socket
		// and we can delete it
		deleting
	};

	packet_ptr acquire_packet(int const allocate);
	void release_packet(packet_ptr p);

	void set_state(state_t s);
	state_t state() const { return static_cast<state_t>(m_state); }

#if TORRENT_USE_INVARIANT_CHECKS
	void check_receive_buffers() const;
	void check_invariant() const;
#endif

	utp_socket_manager& m_sm;

	// userdata pointer passed along
	// with any callback. This is initialized to nullptr
	// then set to point to the utp_stream when
	// hooked up, and then reset to 0 once the utp_stream
	// detaches. This is used to know whether or not
	// the socket impl is still attached to a utp_stream
	// object. When it isn't, we'll never be able to
	// signal anything back to the client, and in case
	// of errors, we just have to delete ourselves
	// i.e. transition to the state_t::deleting state
	utp_stream* m_userdata;

	// if there's currently an async read or write
	// operation in progress, these buffers are initialized
	// and used, otherwise any bytes received are stuck in
	// m_receive_buffer until another read is made
	// as we flush from the write buffer, individual iovecs
	// are updated to only refer to unflushed portions of the
	// buffers. Buffers that empty are erased from the vector.
	std::vector<span<char const>> m_write_buffer;

	// if this is non nullptr, it's a packet. This packet was held off because
	// of NAGLE. We couldn't send it immediately. It's left
	// here to accrue more bytes before we send it.
	packet_ptr m_nagle_packet;

	// the user provided read buffer. If this has a size greater
	// than 0, we'll always prefer using it over putting received
	// data in the m_receive_buffer. As data is stored in the
	// read buffer, the iovec_t elements are adjusted to only
	// refer to the unwritten portions of the buffers, and the
	// ones that fill up are erased from the vector
	std::vector<iovec_t> m_read_buffer;

	// packets we've received without a read operation
	// active. Store them here until the client triggers
	// an async_read_some
	std::vector<packet_ptr> m_receive_buffer;

	// this is the error on this socket. If m_state is
	// set to state_t::error_wait, this error should be
	// forwarded to the client as soon as we have a new
	// async operation initiated
	error_code m_error;

	// these indicate whether or not there is an outstanding read/write or
	// connect operation. i.e. is there upper layer subscribed to these events.
	bool m_read_handler = false;
	bool m_write_handler = false;
	bool m_connect_handler = false;

	// the address of the remote endpoint
	address m_remote_address;

	// the send and receive buffers
	// maps packet sequence numbers
	packet_buffer m_inbuf;
	packet_buffer m_outbuf;

	// the time when the last packet we sent times out. Including re-sends.
	// if we ever end up not having sent anything in one second (
	// or one mean rtt + 2 average deviations, whichever is greater)
	// we set our cwnd to 1 MSS. This condition can happen either because
	// a packet has timed out and needs to be resent or because our
	// cwnd is set to less than one MSS during congestion control.
	// it can also happen if the other end sends an advertised window
	// size less than one MSS.
	time_point m_timeout;

	// the last time we stepped the timestamp history
	time_point m_last_history_step = clock_type::now();

	// the next time we allow a lost packet to halve cwnd. We only do this once every
	// 100 ms
	time_point m_next_loss;

	// the max number of bytes in-flight. This is a fixed point
	// value, to get the true number of bytes, shift right 16 bits
	// the value is always >= 0, but the calculations performed on
	// it in do_ledbat() are signed.
	std::int64_t m_cwnd = TORRENT_ETHERNET_MTU << 16;

	timestamp_history m_delay_hist;
	timestamp_history m_their_delay_hist;

	// the slow-start threshold. This is the congestion window size (m_cwnd)
	// in bytes the last time we left slow-start mode. This is used as a
	// threshold to leave slow-start earlier next time, to avoid packet-loss
	std::int32_t m_ssthres = 0;

	// the number of bytes we have buffered in m_inbuf
	std::int32_t m_buffered_incoming_bytes = 0;

	// the timestamp diff in the last packet received
	// this is what we'll send back
	std::uint32_t m_reply_micro = 0;

	// this is the advertised receive window the other end sent
	// we'll never have more un-acked bytes in flight
	// if this ever gets set to zero, we'll try one packet every
	// second until the window opens up again
	std::uint32_t m_adv_wnd = TORRENT_ETHERNET_MTU;

	// the number of un-acked bytes we have sent
	std::int32_t m_bytes_in_flight = 0;

	// the number of bytes read into the user provided
	// buffer. If this grows too big, we'll trigger the
	// read handler.
	std::int32_t m_read = 0;

	// the sum of the lengths of all iovec in m_write_buffer
	std::int32_t m_write_buffer_size = 0;

	// the number of bytes already written to packets
	// from m_write_buffer
	std::int32_t m_written = 0;

	// the sum of all packets stored in m_receive_buffer
	std::int32_t m_receive_buffer_size = 0;

	// the sum of all buffers in m_read_buffer
	std::int32_t m_read_buffer_size = 0;

	// max number of bytes to allocate for receive buffer
	std::int32_t m_receive_buffer_capacity = 1024 * 1024;

	// this holds the 3 last delay measurements,
	// these are the actual corrected delay measurements.
	// the lowest of the 3 last ones is used in the congestion
	// controller. This is to not completely close the cwnd
	// by a single outlier.
	std::array<std::uint32_t, 3> m_delay_sample_hist;

	// counters
	std::uint32_t m_in_packets = 0;
	std::uint32_t m_out_packets = 0;

	// the last send delay sample
	std::int32_t m_send_delay = 0;
	// the last receive delay sample
	std::int32_t m_recv_delay = 0;

	// average RTT
	sliding_average<int, 16> m_rtt;

	// if this is != 0, it means the upper layer provided a reason for why
	// the connection is being closed. The reason is indicated by this
	// non-zero value which is included in a packet header extension
	close_reason_t m_close_reason = close_reason_t::none;

	// port of destination endpoint
	std::uint16_t m_port = 0;

	std::uint16_t m_send_id;
	std::uint16_t m_recv_id;

	// this is the ack we're sending back. We have
	// received all packets up to this sequence number
	std::uint16_t m_ack_nr = 0;

	// the sequence number of the next packet
	// we'll send
	std::uint16_t m_seq_nr = 0;

	// this is the sequence number of the packet that
	// everything has been ACKed up to. Everything we've
	// sent up to this point has been received by the other
	// end.
	std::uint16_t m_acked_seq_nr = 0;

	// each packet gets one chance of "fast resend". i.e.
	// if we have multiple duplicate acks, we may send a
	// packet immediately, if m_fast_resend_seq_nr is set
	// to that packet's sequence number
	std::uint16_t m_fast_resend_seq_nr = 0;

	// this is the sequence number of the FIN packet
	// we've received. This sequence number is only
	// valid if m_eof is true. We should not accept
	// any packets beyond this sequence number from the
	// other end
	std::uint16_t m_eof_seq_nr = 0;

	// this is the lowest sequence number that, when lost,
	// will cause the window size to be cut in half
	std::uint16_t m_loss_seq_nr = 0;

	// the max number of bytes we can send in a packet
	// including the header
	std::uint16_t m_mtu = TORRENT_ETHERNET_MTU - TORRENT_IPV4_HEADER - TORRENT_UDP_HEADER - 8 - 24 - 36;

	// the floor is the largest packet that we have
	// been able to get through without fragmentation
	std::uint16_t m_mtu_floor = TORRENT_INET_MIN_MTU - TORRENT_IPV4_HEADER - TORRENT_UDP_HEADER;

	// the ceiling is the largest packet that we might
	// be able to get through without fragmentation.
	// i.e. ceiling +1 is very likely to not get through
	// or we have in fact experienced a drop or ICMP
	// message indicating that it is
	std::uint16_t m_mtu_ceiling = TORRENT_ETHERNET_MTU - TORRENT_IPV4_HEADER - TORRENT_UDP_HEADER;

	// the sequence number of the probe in-flight
	// this is 0 if there is no probe in flight
	std::uint16_t m_mtu_seq = 0;

	// this is a counter of how many times the current m_acked_seq_nr
	// has been ACKed. If it's ACKed more than 3 times, we assume the
	// packet with the next sequence number has been lost, and we trigger
	// a re-send. Obviously an ACK only counts as a duplicate as long as
	// we have outstanding packets following it.
	std::uint8_t m_duplicate_acks = 0;

	// the number of packet timeouts we've seen in a row
	// this affects the packet timeout time
	std::uint8_t m_num_timeouts = 0;

	// this is the cursor into m_delay_sample_hist
	std::uint8_t m_delay_sample_idx:2;

	// the state the socket is in
	std::uint8_t m_state:3;

	// this is set to true when we receive a fin
	bool m_eof:1;

	// is this socket state attached to a user space socket?
	bool m_attached:1;

	// this is true if nagle is enabled (which it is by default)
	bool m_nagle:1;

	// this is true while the socket is in slow start mode. It's
	// only in slow-start during the start-up phase. Slow start
	// (contrary to what its name suggest) means that we're growing
	// the congestion window (cwnd) exponentially rather than linearly.
	// this is done at startup of a socket in order to find its
	// link capacity faster. This behaves similar to TCP slow start
	bool m_slow_start:1;

	// this is true as long as we have as many packets in
	// flight as allowed by the congestion window (cwnd)
	bool m_cwnd_full:1;

	// this is set to one if the current read operation
	// has a null_buffer. i.e. we're not reading into a user-provided
	// buffer, we're just signalling when there's something
	// to read from our internal receive buffer
	bool m_null_buffers:1;

	// this is set to true when this socket has added itself to
	// the utp socket manager's list of deferred acks. Once the
	// burst of incoming UDP packets is all drained, the utp socket
	// manager will send acks for all sockets on this list.
	bool m_deferred_ack:1;

	// this is true if this socket has subscribed to be notified
	// when this receive round is done
	bool m_subscribe_drained:1;

	// if this socket tries to send a packet via the utp socket
	// manager, and it fails with EWOULDBLOCK, the socket
	// is stalled and this is set. It's also added to a list
	// of sockets in the utp_socket_manager to be notified of
	// the socket being writable again
	bool m_stalled:1;

	// this is false by default and set to true once we've received a non-SYN
	// packet for this connection with a correct ack_nr, confirming that the
	// other end is not spoofing its source IP
	bool m_confirmed:1;
};

}

#endif

ext: hpp


text:
// Copyright 2019 Lawrence Livermore National Security, LLC and other Metall Project Developers.
// See the top-level COPYRIGHT file for details.
//
// SPDX-License-Identifier: (Apache-2.0 OR MIT)

#include <iostream>
#include <string>
#include <cstddef>

#include <boost/interprocess/managed_mapped_file.hpp>
#include <boost/interprocess/allocators/allocator.hpp>

#include <metall/detail/time.hpp>
#include "../data_structure/multithread_adjacency_list.hpp"
#include "bench_driver.hpp"

using namespace adjacency_list_bench;

using key_type = uint64_t;
using value_type = uint64_t;

namespace bip = boost::interprocess;
using allocator_type = bip::allocator<std::byte, bip::managed_mapped_file::segment_manager>;
using adjacency_list_type =  data_structure::multithread_adjacency_list<key_type, value_type, allocator_type>;

namespace mdtl = metall::mtlldetail;

int main(int argc, char *argv[]) {
  bench_options option;
  if (!parse_options(argc, argv, &option)) {
    std::abort();
  }
  if (option.datastore_path_list.empty()) {
    std::cerr << "Datastore path is required" << std::endl;
    std::abort();
  }

  {

    // bip::file_mapping::remove(option.segment_file_name.c_str());

    bip::managed_mapped_file mfile(bip::create_only, option.datastore_path_list[0].c_str(), option.segment_size);
    auto adj_list = mfile.construct<adjacency_list_type>(option.adj_list_key_name.c_str())(mfile.get_allocator<std::byte>());
    run_bench(option, adj_list);

    const auto start = mdtl::elapsed_time_sec();
    mfile.flush(); // NOTE: this method calls msync() with MS_ASYNC
    const auto elapsed_time = mdtl::elapsed_time_sec(start);
    std::cout << "Async sync_time (s)\t" << elapsed_time << std::endl;

    std::cout << "Segment usage (GB)\t"
              << static_cast<double>(mfile.get_size() - mfile.get_free_memory()) / (1ULL << 30)
              << std::endl;
  }

  return 0;
}

max_stars_repo_name: dice-group/metall

max_issues_repo_name: dice-group/metall

max_forks_repo_name: dice-group/metall


text:
/*
 * Copyright 2000-2014 NeuStar, Inc. All rights reserved.
 * NeuStar, the Neustar logo and related names and logos are registered
 * trademarks, service marks or tradenames of NeuStar, Inc. All other
 * product names, company names, marks, logos and symbols may be trademarks
 * of their respective owners.
 */

/*
 * graphite_reporter.cpp
 *
 *  Created on: Jun 12, 2014
 *      Author: vpoliboy
 */

#include <boost/foreach.hpp>
#include <boost/lexical_cast.hpp>
#include <glog/logging.h>
#include "cppmetrics/core/utils.h"
#include "cppmetrics/graphite/graphite_reporter.h"

namespace cppmetrics {
namespace graphite {

GraphiteReporter::GraphiteReporter(core::MetricRegistryPtr registry,
        GraphiteSenderPtr sender,
        std::string prefix,
        boost::chrono::milliseconds rate_unit) :
        ScheduledReporter(registry, rate_unit), sender_(sender), prefix_(prefix) {

}

GraphiteReporter::~GraphiteReporter() {
    // TODO Auto-generated destructor stub
}

template<typename T>
std::string GraphiteReporter::format(T o) {
    return boost::lexical_cast<std::string>(o);
}

void GraphiteReporter::report(core::CounterMap counter_map,
        core::HistogramMap histogram_map,
        core::MeteredMap meter_map,
        core::TimerMap timer_map,
        core::GaugeMap gauge_map) {

    boost::uint64_t timestamp = core::get_seconds_from_epoch();

    try {
        sender_->connect();

        BOOST_FOREACH(const core::CounterMap::value_type& kv, counter_map) {
            reportCounter(kv.first, kv.second, timestamp);
        }

        BOOST_FOREACH(const core::HistogramMap::value_type& kv, histogram_map) {
            reportHistogram(kv.first, kv.second, timestamp);
        }

        BOOST_FOREACH(const core::MeteredMap::value_type& kv, meter_map) {
            reportMeter(kv.first, kv.second, timestamp);
        }

        BOOST_FOREACH(const core::TimerMap::value_type& kv, timer_map) {
            reportTimer(kv.first, kv.second, timestamp);
        }

        BOOST_FOREACH(const core::GaugeMap::value_type& kv, gauge_map) {
            reportGauge(kv.first, kv.second, timestamp);
        }
        sender_->close();
    }
    catch (const std::exception& e) {
        LOG(ERROR)<< "Exception in graphite reporting: " << e.what();
        sender_->close();
    }
}

void GraphiteReporter::reportTimer(const std::string& name,
        core::TimerPtr timer,
        boost::uint64_t timestamp) {
    core::SnapshotPtr snapshot = timer->getSnapshot();

    sender_->send(prefix(name, "getMax"),
            format(convertDurationUnit(snapshot->getMax())), timestamp);
    sender_->send(prefix(name, "mean"),
            format(convertDurationUnit(snapshot->getMean())), timestamp);
    sender_->send(prefix(name, "min"),
            format(convertDurationUnit(snapshot->getMin())), timestamp);
    sender_->send(prefix(name, "stddev"),
            format(convertDurationUnit(snapshot->getStdDev())), timestamp);
    sender_->send(prefix(name, "p50"),
            format(convertDurationUnit(snapshot->getMedian())), timestamp);
    sender_->send(prefix(name, "p75"),
            format(convertDurationUnit(snapshot->get75thPercentile())),
            timestamp);
    sender_->send(prefix(name, "p95"),
            format(convertDurationUnit(snapshot->get95thPercentile())),
            timestamp);
    sender_->send(prefix(name, "p98"),
            format(convertDurationUnit(snapshot->get98thPercentile())),
            timestamp);
    sender_->send(prefix(name, "p99"),
            format(convertDurationUnit(snapshot->get99thPercentile())),
            timestamp);
    sender_->send(prefix(name, "p999"),
            format(convertDurationUnit(snapshot->get999thPercentile())),
            timestamp);

    reportMeter(name, boost::static_pointer_cast<core::Metered>(timer),
            timestamp);
}

void GraphiteReporter::reportMeter(const std::string& name,
        core::MeteredPtr meter,
        boost::uint64_t timestamp) {

    sender_->send(prefix(name, "count"), format(meter->getCount()), timestamp);
    sender_->send(prefix(name, "m1_rate"),
            format(convertRateUnit(meter->getOneMinuteRate())), timestamp);
    sender_->send(prefix(name, "m5_rate"),
            format(convertRateUnit(meter->getFiveMinuteRate())), timestamp);
    sender_->send(prefix(name, "m15_rate"),
            format(convertRateUnit(meter->getFifteenMinuteRate())), timestamp);
    sender_->send(prefix(name, "mean_rate"),
            format(convertRateUnit(meter->getMeanRate())), timestamp);
}

void GraphiteReporter::reportHistogram(const std::string& name,
        core::HistogramPtr histogram,
        boost::uint64_t timestamp) {
    core::SnapshotPtr snapshot = histogram->getSnapshot();

    sender_->send(prefix(name, "count"), format(histogram->getCount()),
            timestamp);
    sender_->send(prefix(name, "getMax"), format(snapshot->getMax()),
            timestamp);
    sender_->send(prefix(name, "mean"), format(snapshot->getMean()), timestamp);
    sender_->send(prefix(name, "min"), format(snapshot->getMin()), timestamp);
    sender_->send(prefix(name, "stddev"), format(snapshot->getStdDev()),
            timestamp);
    sender_->send(prefix(name, "p50"), format(snapshot->getMedian()),
            timestamp);
    sender_->send(prefix(name, "p75"), format(snapshot->get75thPercentile()),
            timestamp);
    sender_->send(prefix(name, "p95"), format(snapshot->get95thPercentile()),
            timestamp);
    sender_->send(prefix(name, "p98"), format(snapshot->get98thPercentile()),
            timestamp);
    sender_->send(prefix(name, "p99"), format(snapshot->get99thPercentile()),
            timestamp);
    sender_->send(prefix(name, "p999"), format(snapshot->get999thPercentile()),
            timestamp);
}

void GraphiteReporter::reportCounter(const std::string& name,
        core::CounterPtr counter,
        boost::uint64_t timestamp) {
    sender_->send(prefix(name, "count"), format(counter->getCount()),
            timestamp);
}

void GraphiteReporter::reportGauge(const std::string& name,
        core::GaugePtr gauge,
        boost::uint64_t timestamp) {
    const std::string value = format(gauge->getValue());
    sender_->send(prefix(name), value, timestamp);
}

std::string GraphiteReporter::prefix(const std::string& name,
        const char* extra) {
    std::string result(prefix_ + '.' + name);
    return extra ? (result + '.' + extra) : result;
}

} /* namespace graphite */
} /* namespace cppmetrics */

max_stars_repo_name: jdscott-infinetix/cppmetrics

max_issues_repo_name: jdscott-infinetix/cppmetrics

max_forks_repo_name: jdscott-infinetix/cppmetrics


text:
#include "SGFParser.h"
#include <stack>
#include <boost/lexical_cast.hpp>

//============================================================
SGFParser::SGFParser()
{
}
//============================================================

void SGFParser::ParseGame(std::ifstream& in_file, GoGame* l_go_game)
{
    // get length of file:
    in_file.seekg (0, in_file.end);
    int length = in_file.tellg();
    in_file.seekg (0, in_file.beg);

    //Loading file into buffer
    char l_buffer[length];
    in_file.read(l_buffer, length);
    std::string last_property;

    std::stack<GoGameNode*> l_node_check_points;

    bool game_started = false;
    bool reading_property = false;
    bool reading_value = false;
    bool escape_mode = false;

    std::string l_property;
    std::string l_value;

    for(int i =0; i<length;++i)
    {

        //Starting the game
        if(l_buffer[i] == '(' && !reading_value)
        {
            GoGameNode* l_node = l_go_game->GetGameTree().GetCurrentNode();
            //std::cout << "! checkpointing "<< l_node << std::endl;

            l_node_check_points.push( l_node);

            if(!game_started)
            {
                reading_property = true;
                game_started = true;
            }

        }
        else if (!game_started)
        {
            continue;

        }
        else if ( l_buffer[i] == ')' &&!reading_value )
        {
            GoGameNode* l_node = l_node_check_points.top();
            //@TODO: SHOULD GET BACK TO NODE l_node in GoGame (BACK_TO_NODE)
            //std::cout << "Back to node " << l_node << std::endl;
            l_node_check_points.pop();

            if(l_node_check_points.empty())
            {
                //END GAME
                //Just Read one game per SGF for now.
                break;
            }
        }
        else if(reading_property)
        {
            if(l_buffer[i] == '[')
            {
                reading_value = true;
                reading_property = false;

            }else
            {
                if(l_buffer[i] != '\n' && l_buffer[i] != '\r' && l_buffer[i] != ';')
                    l_property+=l_buffer[i];
            }
        }
        else if(reading_value)
        {
            if(l_buffer[i]== '\\' && !escape_mode)
            {
                escape_mode = true;
            }
            else if(l_buffer[i] == ']' && !escape_mode)
            {
                //Finished reading value
                reading_value = false;

                //If it is empty continue with the last property (AB AW cases)
                if(l_property.empty())
                {
                    l_property = last_property;

                }else //Backup the last property used.
                {
                    last_property = l_property;
                }

                //Process property and value
                Process(l_property, l_value, l_go_game);

                //Back to reading property
                reading_property = true;
            }
            else
            {
                l_value += l_buffer[i];

                if(escape_mode)
                {
                    escape_mode = false;
                }
            }
        }
    }

}
//============================================================
void SGFParser::Process(std::string& property, std::string& value, GoGame* l_go_game)
{
//    std::cout << property << " << " << value << std::endl;

    GoGameInfo& game_info = l_go_game->GetGameInfo();
    char move_row;
    char move_column;

    assert(!property.empty());
    if((property == "B")||(property == "AB"))//Black Plays
    {
        move_column = value[0];
        move_row = value[1];

        int column = ( (int)move_column - (int)'a');
        int row = ( (int)move_row - (int)'a');
        l_go_game->PlayMove(column,row, BLACK);

    }
    else if ((property == "W")||(property == "AW"))//White Plays
    {

        move_column = value[0];
        move_row = value[1];

        int column = ( (int)move_column - (int)'a');
        int row = ( (int)move_row - (int)'a');

        l_go_game->PlayMove(column,row, WHITE);

    }
    else if(property == "PB")//Name of black player
    {
        game_info.m_black_player = value;

    }else if(property == "PW")//Name of White player
    {
        game_info.m_white_player = value;

    }else if(property == "KM")//Komi
    {
        double komi;
        try
        {
            komi = boost::lexical_cast<double>(value) * 10;
        }
        catch (boost::bad_lexical_cast const&)
        {
            komi = 0;
        }
        game_info.m_komi10 = komi;

    }else if(property == "BR")//black rating
    {
        game_info.m_black_rating = value;

    }else if(property == "WR")//white rating
    {
        game_info.m_white_rating = value;
    }
    else if(property == "RE")//result
    {
        game_info.m_game_result = value;
    }
    else if(property == "DT")//date
    {
        game_info.m_date = value;
    }

    property.clear();
    value.clear();
}


text: #include <boost/mpl/aux_/preprocessed/dmc/lambda_no_ctps.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
//---------------------------------------------------------------------------//
//        ____  _____________  __    __  __ _           _____ ___   _        //
//       / __ \/ ____/ ___/\ \/ /   |  \/  (_)__ _ _ __|_   _/ __| /_\       //
//      / / / / __/  \__ \  \  /    | |\/| | / _| '_/ _ \| || (__ / _ \      //
//     / /_/ / /___ ___/ /  / /     |_|  |_|_\__|_| \___/|_| \___/_/ \_\     //
//    /_____/_____//____/  /_/      T  E  C  H  N  O  L  O  G  Y   L A B     //
//                                                                           //
//---------------------------------------------------------------------------//

// Copyright (c) 2021 Deutsches Elektronen-Synchrotron DESY

#pragma once

#include <vector>

#include <boost/asio.hpp>
#include <boost/asio/posix/stream_descriptor.hpp>
#include <boost/log/trivial.hpp>
#include <boost/core/noncopyable.hpp>

#include "UDmaBuf.hpp"
#include "UioAxiDmaIf.hpp"
#include "UioMemSgdma.hpp"

namespace blt = boost::log::trivial;

namespace udmaio {

class DataHandlerAbstract : private boost::noncopyable {

    boost::log::sources::severity_logger_mt<blt::severity_level> _slg;
    UioAxiDmaIf &_dma;
    UioMemSgdma &_desc;
    DmaBufferAbstract &_mem;

    boost::asio::io_service _svc;
    boost::asio::posix::stream_descriptor _sd;

    void _start_read();
    void _handle_input(const boost::system::error_code& ec);

  public:
    explicit DataHandlerAbstract(UioAxiDmaIf &dma, UioMemSgdma &desc, DmaBufferAbstract &mem);
    virtual ~DataHandlerAbstract();

    virtual void stop();

    void operator()();

    virtual void process_data(std::vector<uint8_t> bytes) = 0;
};

} // namespace udmaio

max_stars_repo_name: MicroTCA-Tech-Lab/libudmaio

max_issues_repo_name: MicroTCA-Tech-Lab/libudmaio

max_forks_repo_name: MicroTCA-Tech-Lab/libudmaio


text:
// Copyright 2019 Max Planck Gesellschaft and New York University
// Authors: Vincent Berenz, Maximilien Naveau

#pragma once

#include "shared_memory/lock.hpp"

#include <boost/interprocess/sync/named_condition.hpp>

namespace shared_memory
{
typedef boost::interprocess::named_condition SHMCondition;

class ConditionVariable
{
public:
    /**
     * @brief A condition variable shared over the memory
     * The condition variable is cleaned from the memory
     * on destruction if clean_memory_on_destruction
     * is set to true
     */
    ConditionVariable(const std::string object_id,
                      bool clean_memory_on_destruction);

    ~ConditionVariable();

    /**
     * @brief notify_all is notifying all condition variables with the same
     * mutex
     */
    void notify_all();

    /**
     * @brief notify_one notifies one condition variable with the same mutex
     */
    void notify_one();

    /**
     * @brief timed_wait wait a notify during a certain certain time and then
     * wake up
     * @param wait_duration in microsecond
     * @return true: the condition variable has been notified, false otherwize
     */
    bool timed_wait(Lock &lock, long wait_nano_seconds);

    /**
     * @brief wait waits until another thread notifies this object
     */
    void wait(Lock &lock);

public:
    static void clean(const std::string object_id);

private:
    /**
     * @brief condition_id_ is the condition variable name in the shared memory
     */
    std::string condition_id_;

    /**
     * @brief if true (the default), clean the shared memory of the
     * hosted mutex and condition.
     */
    bool clean_memory_on_destruction_;

    /**
     * @brief condition_variable_ is the boost condition variable that is used
     */
    SHMCondition *condition_variable_;

    /**
     * @brief mutex_id_ is the mutex name in the shared memory
     */
    std::string mutex_id_;
};

}  // namespace shared_memory


text:
#ifndef JIMBO_RESOURCE_THREAD_THREADPOOL_HPP
#define JIMBO_RESOURCE_THREAD_THREADPOOL_HPP

/////////////////////////////////////////////////////////
// threadpool.hxx
//
// Ben Storey
//
// A very simple thread pool around boost::asio.
//
/////////////////////////////////////////////////////////

// We use boost thread instead of std::thread because it supports thread_group

#include <boost/asio.hpp>
#include <boost/thread.hpp>
#include <boost/noncopyable.hpp>
#include <memory>

#include "log/logging.hpp"

namespace jimbo
{

    class ThreadPool : boost::noncopyable
    {
    public:

        ThreadPool(): running_(false) {}
        virtual ~ThreadPool() { shutdown(); }

        void initialise(int numThreads)
        {
            // This work object uses its constructor to notify the io_service that work is starting..
            // If this isn't created then the run() function may not work properly
            work_.reset(new boost::asio::io_service::work(service_));

            for (int i = 0; i < numThreads; i++)
            {
                LOG("Creating Thread(" + std::to_string(i + 1) + ")");
                auto thread = boost::bind(&boost::asio::io_service::run, &service_);
                group_.add_thread(new boost::thread(thread));
            }

            running_ = true;
        }

        // Shuts down the pool and all threads. Any future tasks will be ignored.
        void shutdown()
        {
            if (!running_) return;

            service_.stop();
            group_.join_all();

            running_ = false;
        }

        bool isRunning() const
        {
            return running_;
        }

    protected:

        // We let subclasses post tasks to the service_ directly
        boost::asio::io_service service_;

    private:

        std::unique_ptr<boost::asio::io_service::work> work_;
        boost::thread_group group_;

        bool running_;
    };
}

#endif // JIMBO_RESOURCE_THREAD_THREADPOOL_HPP

ext: hxx

max_stars_repo_name: BenStorey/Jimbo

max_issues_repo_name: BenStorey/Jimbo

max_forks_repo_name: BenStorey/Jimbo


text:
/*
   Copyright 2018 Simon Vogl <svogl@voxel.at>
                  Angel Merino-Sastre <amerino@voxel.at>

   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.
*/
#if OCV_VERSION_MAJOR >= 3
#  include <opencv2/imgproc.hpp>
#  include <opencv2/highgui.hpp>
#else
#  include <opencv2/imgproc/imgproc.hpp>
#  include <opencv2/highgui/highgui.hpp>
#endif

#include <boost/log/trivial.hpp>
#include <boost/any.hpp>

#include <boost/date_time/posix_time/posix_time_types.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>

#include "toffy/viewers/colorize.hpp"

using namespace toffy;
using namespace cv;
using namespace std;

std::size_t Colorize::filter_counter = 1;
const std::string Colorize::id_name = "colorize";

Colorize::Colorize(): Filter(Colorize::id_name,filter_counter),
		      scale(1.f), max(1.5), min(0.01), in_img("depth"),out_img("colored"), colormap("jet")
{
    filter_counter++;
}

Colorize::~Colorize(){
}

void Colorize::updateConfig(const boost::property_tree::ptree &pt)
{
    BOOST_LOG_TRIVIAL(debug) << __FUNCTION__ <<  " " << id();

    using namespace boost::property_tree;

    Filter::updateConfig(pt);

    scale = pt.get<double>("options.scale",scale);
    max = pt.get<double>("options.max",max);
    min = pt.get<double>("options.min",min);

    colormap = pt.get<string>("options.colormap",colormap);

    in_img = pt.get<string>("inputs.img",in_img);
    out_img = pt.get<string>("outputs.img",out_img);

    if ( colormap == "jet" ) {
	colormap_value = COLORMAP_JET;
    } else if ( colormap == "hot" ) {
	colormap_value = COLORMAP_HOT;
    } else if ( colormap == "hsv" ) {
	colormap_value = COLORMAP_HSV;
    } else if ( colormap == "rainbow" ) {
	colormap_value = COLORMAP_RAINBOW;
    } else {
	colormap_value = COLORMAP_JET;
    }
}

boost::property_tree::ptree Colorize::getConfig() const {
    boost::property_tree::ptree pt;

    pt = Filter::getConfig();

    pt.put("options.scale", scale);
    pt.put("options.max", max);
    pt.put("options.min", min);

    pt.put("options.colormap", colormap);

    pt.put("inputs.img", in_img);
    pt.put("outputs.img", out_img);

    return pt;
}

bool Colorize::filter(const Frame &in, Frame& out)
{
    matPtr img, colored;

    using namespace boost::posix_time;

    ptime start = microsec_clock::local_time();
    boost::posix_time::time_duration diff;

    BOOST_LOG_TRIVIAL(debug) << __FUNCTION__ << " " << id();

    ///// INPUT

    if ( ! in.hasKey(in_img)) {
	BOOST_LOG_TRIVIAL(warning) << 	"Could not find input " << in_img <<
	", filter  " << id() <<" not applied.";
	return false;
    }
    img = in.getMatPtr(in_img);

    Mat& inp = *img;
    if (!inp.data) {
      BOOST_LOG_TRIVIAL(warning) <<
	"missing image " << in_img <<
	", filter  " << id() <<" not applied.";
      return false;
    }

    if (! out.hasKey(out_img)) {
	colored.reset(new Mat(Size(img->rows*scale, img->cols*scale), CV_8UC3));
    } else {
	colored = out.getMatPtr(out_img);
    }

    //// PROCESSING

    // convert input to grayscale
    // apply colormap
    // set invalid pixels to black
    // scale if needed
    // store result in outupt.

    diff = boost::posix_time::microsec_clock::local_time() - start;
    BOOST_LOG_TRIVIAL(debug) << "Colorize got: " << diff.total_microseconds();

    //show.convertTo(show,CV_8U,255.0/(1000-0),-255.0*0/(1000-0));
    if (max == min) {
	minMaxIdx(inp, &min, &max);
    }
    inp.convertTo(gray,CV_8U,255.0/(max-min),-255.0*min/(max-min));

    diff = boost::posix_time::microsec_clock::local_time() - start;
    BOOST_LOG_TRIVIAL(debug) << "Colorize gray2rgb: " << diff.total_microseconds();

    // color conversion...:
    applyColorMap(gray, col, colormap_value);

    bounds = (inp < min) | ( inp > max) | ( inp != inp );
    col.setTo(Scalar(0,0,0), bounds);

    if( scale != 1.f ) {
      int method = scale < 1 ? INTER_AREA : INTER_LINEAR;
      resize(col, *colored, Size(), scale, scale, method);

      diff = boost::posix_time::microsec_clock::local_time() - start;
      BOOST_LOG_TRIVIAL(debug) << "Colorize resize: " << diff.total_microseconds();

    } else {
	*colored = col;
    }

    //imshow(name() + " " + out_img, col);

    diff = boost::posix_time::microsec_clock::local_time() - start;
    BOOST_LOG_TRIVIAL(debug) << "Colorize fin: " << diff.total_microseconds();

    //// OUTPUT
    out.addData(out_img, colored);

    return true;
}

max_stars_repo_name: voxel-dot-at/toffy

max_issues_repo_name: voxel-dot-at/toffy

max_forks_repo_name: voxel-dot-at/toffy


text:
#ifndef STAN_MATH_PRIM_SCAL_PROB_BINOMIAL_LOGIT_LPMF_HPP
#define STAN_MATH_PRIM_SCAL_PROB_BINOMIAL_LOGIT_LPMF_HPP

#include <stan/math/prim/scal/meta/is_constant_struct.hpp>
#include <stan/math/prim/scal/meta/partials_return_type.hpp>
#include <stan/math/prim/scal/meta/operands_and_partials.hpp>
#include <stan/math/prim/scal/err/check_consistent_sizes.hpp>
#include <stan/math/prim/scal/err/check_bounded.hpp>
#include <stan/math/prim/scal/err/check_finite.hpp>
#include <stan/math/prim/scal/err/check_greater_or_equal.hpp>
#include <stan/math/prim/scal/err/check_less_or_equal.hpp>
#include <stan/math/prim/scal/err/check_nonnegative.hpp>
#include <stan/math/prim/scal/fun/size_zero.hpp>
#include <stan/math/prim/scal/fun/constants.hpp>
#include <stan/math/prim/scal/fun/inv_logit.hpp>
#include <stan/math/prim/scal/fun/log1m.hpp>
#include <stan/math/prim/scal/fun/log_inv_logit.hpp>
#include <stan/math/prim/scal/fun/multiply_log.hpp>
#include <stan/math/prim/scal/fun/value_of.hpp>
#include <stan/math/prim/scal/fun/binomial_coefficient_log.hpp>
#include <stan/math/prim/scal/fun/lbeta.hpp>
#include <stan/math/prim/scal/meta/VectorBuilder.hpp>
#include <stan/math/prim/scal/meta/include_summand.hpp>
#include <stan/math/prim/scal/meta/scalar_seq_view.hpp>
#include <stan/math/prim/scal/fun/inc_beta.hpp>
#include <boost/random/binomial_distribution.hpp>
#include <boost/random/variate_generator.hpp>

namespace stan {
namespace math {

/**
 * Binomial log PMF in logit parametrization. Binomial(n|n, inv_logit(alpha))
 *
 * If given vectors of matching lengths, returns
 * the log sum of probabilities.
 *
 * @param n successes variable
 * @param N population size parameter
 * @param alpha logit transformed probability parameter
 *
 * @return log probability or log sum of probabilities
 *
 * @throw std::domain_error if N is negative or probability parameter is invalid
 * @throw std::invalid_argument if vector sizes do not match
 */
template <bool propto, typename T_n, typename T_N, typename T_prob>
typename return_type<T_prob>::type binomial_logit_lpmf(const T_n& n,
                                                       const T_N& N,
                                                       const T_prob& alpha) {
  typedef typename stan::partials_return_type<T_n, T_N, T_prob>::type
      T_partials_return;

  static const char* function = "binomial_logit_lpmf";

  if (size_zero(n, N, alpha))
    return 0.0;

  T_partials_return logp = 0;
  check_bounded(function, "Successes variable", n, 0, N);
  check_nonnegative(function, "Population size parameter", N);
  check_finite(function, "Probability parameter", alpha);
  check_consistent_sizes(function, "Successes variable", n,
                         "Population size parameter", N,
                         "Probability parameter", alpha);

  if (!include_summand<propto, T_prob>::value)
    return 0.0;

  scalar_seq_view<T_n> n_vec(n);
  scalar_seq_view<T_N> N_vec(N);
  scalar_seq_view<T_prob> alpha_vec(alpha);
  size_t size = max_size(n, N, alpha);

  operands_and_partials<T_prob> ops_partials(alpha);

  if (include_summand<propto>::value) {
    for (size_t i = 0; i < size; ++i)
      logp += binomial_coefficient_log(N_vec[i], n_vec[i]);
  }

  VectorBuilder<true, T_partials_return, T_prob> log_inv_logit_alpha(
      length(alpha));
  for (size_t i = 0; i < length(alpha); ++i)
    log_inv_logit_alpha[i] = log_inv_logit(value_of(alpha_vec[i]));

  VectorBuilder<true, T_partials_return, T_prob> log_inv_logit_neg_alpha(
      length(alpha));
  for (size_t i = 0; i < length(alpha); ++i)
    log_inv_logit_neg_alpha[i] = log_inv_logit(-value_of(alpha_vec[i]));

  for (size_t i = 0; i < size; ++i)
    logp += n_vec[i] * log_inv_logit_alpha[i]
            + (N_vec[i] - n_vec[i]) * log_inv_logit_neg_alpha[i];

  if (length(alpha) == 1) {
    T_partials_return temp1 = 0;
    T_partials_return temp2 = 0;
    for (size_t i = 0; i < size; ++i) {
      temp1 += n_vec[i];
      temp2 += N_vec[i] - n_vec[i];
    }
    if (!is_constant_struct<T_prob>::value) {
      ops_partials.edge1_.partials_[0]
          += temp1 * inv_logit(-value_of(alpha_vec[0]))
             - temp2 * inv_logit(value_of(alpha_vec[0]));
    }
  } else {
    if (!is_constant_struct<T_prob>::value) {
      for (size_t i = 0; i < size; ++i)
        ops_partials.edge1_.partials_[i]
            += n_vec[i] * inv_logit(-value_of(alpha_vec[i]))
               - (N_vec[i] - n_vec[i]) * inv_logit(value_of(alpha_vec[i]));
    }
  }

  return ops_partials.build(logp);
}

template <typename T_n, typename T_N, typename T_prob>
inline typename return_type<T_prob>::type binomial_logit_lpmf(
    const T_n& n, const T_N& N, const T_prob& alpha) {
  return binomial_logit_lpmf<false>(n, N, alpha);
}

}  // namespace math
}  // namespace stan
#endif

max_stars_repo_name: jrmie/math

max_issues_repo_name: jrmie/math

max_forks_repo_name: jrmie/math


text:
//==================================================================================================
/*!
  @file

  @copyright 2016 NumScale SAS

  Distributed under the Boost Software License, Version 1.0.
  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
//==================================================================================================
#ifndef BOOST_SIMD_CONSTANT_EULER_HPP_INCLUDED
#define BOOST_SIMD_CONSTANT_EULER_HPP_INCLUDED

/*!
  @ingroup group-constant
  @defgroup constant-Euler Euler (function template)

  Generates an approximation of the Euler-Mascheroni constant.

  @headerref{<boost/simd/constant/euler.hpp>}

  @par Description

  1.  @code
      template<typename T> T Euler();
      @endcode

  2.  @code
      template<typename T> T Euler( boost::simd::as_<T> const& target );
      @endcode

  Generates a value of type @c T evaluating to the Euler-Mascheroni constant defined as:
  \f$\gamma = \lim_{n \rightarrow \infty } \left( 1+ \frac{1}{2} + ... + \frac{1}{n} - \ln(n) \right)\f$.

  @par Parameters

  | Name                | Description                                                         |
  |--------------------:|:--------------------------------------------------------------------|
  | **target**          | a [placeholder](@ref type-as) value encapsulating the constant type |

  @par Return Value
  A value of type @c T that evaluates to `T(0.57721566490153286060651209008240243104215933593992359)`

  @par Requirements
  - **T** models IEEEValue
**/

#include <boost/simd/constant/scalar/euler.hpp>
#include <boost/simd/constant/simd/euler.hpp>

#endif

max_stars_repo_name: SylvainCorlay/pythran

max_issues_repo_name: SylvainCorlay/pythran

max_forks_repo_name: SylvainCorlay/pythran


text:
#include <Columns/ColumnNullable.h>
#include <Columns/ColumnString.h>
#include <Columns/ColumnTuple.h>
#include <Columns/ColumnsNumber.h>
#include <Columns/IColumn.h>
#include <DataTypes/DataTypeTuple.h>
#include <DataTypes/DataTypesNumber.h>
#include <Functions/FunctionFactory.h>
#include <Functions/FunctionHelpers.h>
#include <Functions/IFunction.h>
#include <Functions/castTypeToEither.h>
#include <Interpreters/castColumn.h>
#include <boost/math/distributions/normal.hpp>
#include <Common/typeid_cast.h>

namespace DB
{

namespace ErrorCodes
{
    extern const int ILLEGAL_TYPE_OF_ARGUMENT;
    extern const int BAD_ARGUMENTS;
}

class FunctionTwoSampleProportionsZTest : public IFunction
{
public:
    static constexpr auto POOLED = "pooled";
    static constexpr auto UNPOOLED = "unpooled";

    static constexpr auto name = "proportionsZTest";

    static FunctionPtr create(ContextPtr) { return std::make_shared<FunctionTwoSampleProportionsZTest>(); }

    String getName() const override { return name; }

    size_t getNumberOfArguments() const override { return 6; }
    ColumnNumbers getArgumentsThatAreAlwaysConstant() const override { return {5}; }

    bool useDefaultImplementationForNulls() const override { return false; }
    bool useDefaultImplementationForConstants() const override { return true; }
    bool isSuitableForShortCircuitArgumentsExecution(const DataTypesWithConstInfo & /*arguments*/) const override { return false; }

    static DataTypePtr getReturnType()
    {
        auto float_data_type = std::make_shared<DataTypeNumber<Float64>>();
        DataTypes types(4, float_data_type);

        Strings names{"z_statistic", "p_value", "confidence_interval_low", "confidence_interval_high"};

        return std::make_shared<DataTypeTuple>(std::move(types), std::move(names));
    }

    DataTypePtr getReturnTypeImpl(const ColumnsWithTypeAndName & arguments) const override
    {
        for (size_t i = 0; i < 4; ++i)
        {
            if (!isUnsignedInteger(arguments[i].type))
            {
                throw Exception(
                    ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT,
                    "The {}th Argument of function {} must be an unsigned integer.",
                    i + 1,
                    getName());
            }
        }

        if (!isFloat(arguments[4].type))
        {
            throw Exception{ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT,
                "The fifth argument {} of function {} should be a float,",
                arguments[4].type->getName(),
                getName()};
        }

        /// There is an additional check for constancy in ExecuteImpl
        if (!isString(arguments[5].type) || !arguments[5].column)
        {
            throw Exception{ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT,
                "The sixth argument {} of function {} should be a constant string",
                arguments[5].type->getName(),
                getName()};
        }

        return getReturnType();
    }

    ColumnPtr executeImpl(const ColumnsWithTypeAndName & const_arguments, const DataTypePtr &, size_t input_rows_count) const override
    {
        auto arguments = const_arguments;
        /// Only last argument have to be constant
        for (size_t i = 0; i < 5; ++i)
            arguments[i].column = arguments[i].column->convertToFullColumnIfConst();

        static const auto uint64_data_type = std::make_shared<DataTypeNumber<UInt64>>();

        auto column_successes_x = castColumnAccurate(arguments[0], uint64_data_type);
        const auto & data_successes_x = checkAndGetColumn<ColumnVector<UInt64>>(column_successes_x.get())->getData();

        auto column_successes_y = castColumnAccurate(arguments[1], uint64_data_type);
        const auto & data_successes_y = checkAndGetColumn<ColumnVector<UInt64>>(column_successes_y.get())->getData();

        auto column_trials_x = castColumnAccurate(arguments[2], uint64_data_type);
        const auto & data_trials_x = checkAndGetColumn<ColumnVector<UInt64>>(column_trials_x.get())->getData();

        auto column_trials_y = castColumnAccurate(arguments[3], uint64_data_type);
        const auto & data_trials_y = checkAndGetColumn<ColumnVector<UInt64>>(column_trials_y.get())->getData();

        static const auto float64_data_type = std::make_shared<DataTypeNumber<Float64>>();

        auto column_confidence_level = castColumnAccurate(arguments[4], float64_data_type);
        const auto & data_confidence_level = checkAndGetColumn<ColumnVector<Float64>>(column_confidence_level.get())->getData();

        String usevar = checkAndGetColumnConst<ColumnString>(arguments[5].column.get())->getValue<String>();

        if (usevar != UNPOOLED && usevar != POOLED)
            throw Exception{ErrorCodes::BAD_ARGUMENTS,
                "The sixth argument {} of function {} must be equal to `pooled` or `unpooled`",
                arguments[5].type->getName(),
                getName()};

        const bool is_unpooled = (usevar == UNPOOLED);

        auto res_z_statistic = ColumnFloat64::create();
        auto & data_z_statistic = res_z_statistic->getData();
        data_z_statistic.reserve(input_rows_count);

        auto res_p_value = ColumnFloat64::create();
        auto & data_p_value = res_p_value->getData();
        data_p_value.reserve(input_rows_count);

        auto res_ci_lower = ColumnFloat64::create();
        auto & data_ci_lower = res_ci_lower->getData();
        data_ci_lower.reserve(input_rows_count);

        auto res_ci_upper = ColumnFloat64::create();
        auto & data_ci_upper = res_ci_upper->getData();
        data_ci_upper.reserve(input_rows_count);

        auto insert_values_into_result = [&data_z_statistic, &data_p_value, &data_ci_lower, &data_ci_upper](
                                             Float64 z_stat, Float64 p_value, Float64 lower, Float64 upper)
        {
            data_z_statistic.emplace_back(z_stat);
            data_p_value.emplace_back(p_value);
            data_ci_lower.emplace_back(lower);
            data_ci_upper.emplace_back(upper);
        };

        static constexpr Float64 nan = std::numeric_limits<Float64>::quiet_NaN();

        boost::math::normal_distribution<> nd(0.0, 1.0);

        for (size_t row_num = 0; row_num < input_rows_count; ++row_num)
        {
            const UInt64 successes_x = data_successes_x[row_num];
            const UInt64 successes_y = data_successes_y[row_num];
            const UInt64 trials_x = data_trials_x[row_num];
            const UInt64 trials_y = data_trials_y[row_num];
            const Float64 confidence_level = data_confidence_level[row_num];

            const Float64 props_x = static_cast<Float64>(successes_x) / trials_x;
            const Float64 props_y = static_cast<Float64>(successes_y) / trials_y;
            const Float64 diff = props_x - props_y;
            const UInt64 trials_total = trials_x + trials_y;

            if (successes_x == 0 || successes_y == 0 || successes_x > trials_x || successes_y > trials_y || trials_total == 0
                || !std::isfinite(confidence_level) || confidence_level < 0.0 || confidence_level > 1.0)
            {
                insert_values_into_result(nan, nan, nan, nan);
                continue;
            }

            Float64 se = std::sqrt(props_x * (1.0 - props_x) / trials_x + props_y * (1.0 - props_y) / trials_y);

            /// z-statistics
            /// z = \frac{ \bar{p_{1}} - \bar{p_{2}} }{ \sqrt{ \frac{ \bar{p_{1}} \left ( 1 - \bar{p_{1}} \right ) }{ n_{1} } \frac{ \bar{p_{2}} \left ( 1 - \bar{p_{2}} \right ) }{ n_{2} } } }
            Float64 zstat;
            if (is_unpooled)
            {
                zstat = (props_x - props_y) / se;
            }
            else
            {
                UInt64 successes_total = successes_x + successes_y;
                Float64 p_pooled = static_cast<Float64>(successes_total) / trials_total;
                Float64 trials_fact = 1.0 / trials_x + 1.0 / trials_y;
                zstat = diff / std::sqrt(p_pooled * (1.0 - p_pooled) * trials_fact);
            }

            if (!std::isfinite(zstat))
            {
                insert_values_into_result(nan, nan, nan, nan);
                continue;
            }

            // pvalue
            Float64 pvalue = 0;
            Float64 one_side = 1 - boost::math::cdf(nd, std::abs(zstat));
            pvalue = one_side * 2;

            // Confidence intervals
            Float64 d = props_x - props_y;
            Float64 z = -boost::math::quantile(nd, (1.0 - confidence_level) / 2.0);
            Float64 dist = z * se;
            Float64 ci_low = d - dist;
            Float64 ci_high = d + dist;

            insert_values_into_result(zstat, pvalue, ci_low, ci_high);
        }

        return ColumnTuple::create(
            Columns{std::move(res_z_statistic), std::move(res_p_value), std::move(res_ci_lower), std::move(res_ci_upper)});
    }
};

void registerFunctionZTest(FunctionFactory & factory)
{
    factory.registerFunction<FunctionTwoSampleProportionsZTest>();
}

}


text:
#include <boost/msm/active_state_switching_policies.hpp>
#include <boost/msm/common.hpp>
#include <boost/msm/event_traits.hpp>
#include <boost/msm/msm_grammar.hpp>
#include <boost/msm/proto_config.hpp>
#include <boost/msm/row_tags.hpp>

int
main ()
{
  return 0;
}


text:
#include "Icontroller.hpp"
#include <iostream>
#include <Eigen/Eigen>
#include "include/Sensor.h"
#include "include/SensorArray.h"
#include "math.h"
#include "lqr.cpp"
#include "m5op.h"
#include <stdio.h>      /* printf, scanf, puts, NULL */
#include <stdlib.h>     /* srand, rand */
#include <time.h>       /* time */
#include <unistd.h>
#include <ios>
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void mem_usage(double& vm_usage, double& resident_set) {
   vm_usage = 0.0;
   resident_set = 0.0;
   ifstream stat_stream("/proc/self/stat",ios_base::in); //get info from proc directory
   //create some variables to get info
   string pid, comm, state, ppid, pgrp, session, tty_nr;
   string tpgid, flags, minflt, cminflt, majflt, cmajflt;
   string utime, stime, cutime, cstime, priority, nice;
   string O, itrealvalue, starttime;
   unsigned long vsize;
   long rss;
   stat_stream >> pid >> comm >> state >> ppid >> pgrp >> session >> tty_nr
   >> tpgid >> flags >> minflt >> cminflt >> majflt >> cmajflt
   >> utime >> stime >> cutime >> cstime >> priority >> nice
   >> O >> itrealvalue >> starttime >> vsize >> rss; // don't care   about the rest
   stat_stream.close();
   long page_size_kb = sysconf(_SC_PAGE_SIZE) / 1024; // for x86-64 is configured to use 2MB pages
   vm_usage = vsize / 1024.0;
   resident_set = rss * page_size_kb;
}

int main()
	{
	double vm, rss;
   mem_usage(vm, rss);
   cout << "Virtual Memory: " << vm << "\nResident set size: " << rss << endl;
	simulator_msgs::SensorArray arraymsg;
	std::vector<double> out;
	std::vector<double> xref;
	std::vector<double> error;
	std::vector<double> x;
	int k=0;

//		m5_dump_stats(0,0);
//		m5_reset_stats(0,0);
//		Foo* foo1 = new Foo ();
//		std::cout << "test if main works" << std::endl;;
		teste* control = new teste();

//		m5_dump_stats(0,0);
//		m5_reset_stats(0,0);

		control->config();

//		m5_dump_stats(0,0);
//		simulator_msgs::Sensor msgstates;
//		arraymsg.header;
//		msgstates = arraymsg.values.at(0);

		while(k<20){

		//m5_reset_stats(0,0);
		out=control->execute(arraymsg);
		mem_usage(vm, rss);
  		cout << "Virtual Memory: " << vm << "\nResident set size: " << rss << endl;
		//m5_dump_stats(0,0);

		k++;
		}
	mem_usage(vm, rss);
   cout << "Virtual Memory: " << vm << "\nResident set size: " << rss << endl;
		return 0;
	}


text:
#ifndef obj_hpp
#define obj_hpp

#include <string>
#include <oh/libraryobject.hpp>
#include <oh/valueobject.hpp>
#include <boost/shared_ptr.hpp>

#include <ql/quotes/simplequote.hpp>
#include <ql/math/comparison.hpp>

namespace QuantLibAddin {

    bool close(double x, double y);

    class SimpleQuote :
        public ObjectHandler::LibraryObject<QuantLib::SimpleQuote> {
        public:
            SimpleQuote(
                const boost::shared_ptr<ObjectHandler::ValueObject>& properties,
                double value,
                bool permanent)
            : ObjectHandler::LibraryObject<QuantLib::SimpleQuote>(properties, permanent) {
                libraryObject_ = boost::shared_ptr<QuantLib::SimpleQuote>(new QuantLib::SimpleQuote(value));
            }
    };

}

#endif

max_stars_repo_name: frannuca/quantlib

max_issues_repo_name: frannuca/quantlib

max_forks_repo_name: frannuca/quantlib