text:
//
// pinger.cpp
// ~~~~~~~~
//
// Copyright (c) 2003-2014 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//

#include "inet_hal.h"
#include "core_msg.h"
#include <istream>
#include <ostream>
#include <boost/array.hpp>
#include <boost/bind.hpp>

#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-variable"
#ifdef __clang__
#pragma GCC diagnostic ignored "-Wunused-local-typedef"
#endif
#include "boost_asio_wrap.h"
#pragma GCC diagnostic pop

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

#include <boost/asio/ip/icmp.hpp>

using boost::asio::ip::icmp;
using boost::asio::deadline_timer;
namespace posix_time = boost::posix_time;

class ipv4_header
{
public:
  ipv4_header() { std::fill(rep_, rep_ + sizeof(rep_), 0); }

  unsigned char version() const { return (rep_[0] >> 4) & 0xF; }
  unsigned short header_length() const { return (rep_[0] & 0xF) * 4; }
  unsigned char type_of_service() const { return rep_[1]; }
  unsigned short total_length() const { return decode(2, 3); }
  unsigned short identification() const { return decode(4, 5); }
  bool dont_fragment() const { return (rep_[6] & 0x40) != 0; }
  bool more_fragments() const { return (rep_[6] & 0x20) != 0; }
  unsigned short fragment_offset() const { return decode(6, 7) & 0x1FFF; }
  unsigned int time_to_live() const { return rep_[8]; }
  unsigned char protocol() const { return rep_[9]; }
  unsigned short header_checksum() const { return decode(10, 11); }

  boost::asio::ip::address_v4 source_address() const
  {
    boost::asio::ip::address_v4::bytes_type bytes
      = { { rep_[12], rep_[13], rep_[14], rep_[15] } };
    return boost::asio::ip::address_v4(bytes);
  }

  boost::asio::ip::address_v4 destination_address() const
  {
    boost::asio::ip::address_v4::bytes_type bytes
      = { { rep_[16], rep_[17], rep_[18], rep_[19] } };
    return boost::asio::ip::address_v4(bytes);
  }

  friend std::istream& operator>>(std::istream& is, ipv4_header& header)
  {
    is.read(reinterpret_cast<char*>(header.rep_), 20);
    if (header.version() != 4)
      is.setstate(std::ios::failbit);
    std::streamsize options_length = header.header_length() - 20;
    if (options_length < 0 || options_length > 40)
      is.setstate(std::ios::failbit);
    else
      is.read(reinterpret_cast<char*>(header.rep_) + 20, options_length);
    return is;
  }

private:
  unsigned short decode(int a, int b) const
    { return (rep_[a] << 8) + rep_[b]; }

  unsigned char rep_[60];
};

class icmp_header
{
public:
  enum { echo_reply = 0, destination_unreachable = 3, source_quench = 4,
    redirect = 5, echo_request = 8, time_exceeded = 11, parameter_problem = 12,
    timestamp_request = 13, timestamp_reply = 14, info_request = 15,
    info_reply = 16, address_request = 17, address_reply = 18 };

  icmp_header() { std::fill(rep_, rep_ + sizeof(rep_), 0); }

  unsigned char type() const { return rep_[0]; }
  unsigned char code() const { return rep_[1]; }
  unsigned short checksum() const { return decode(2, 3); }
  unsigned short identifier() const { return decode(4, 5); }
  unsigned short sequence_number() const { return decode(6, 7); }

  void type(unsigned char n) { rep_[0] = n; }
  void code(unsigned char n) { rep_[1] = n; }
  void checksum(unsigned short n) { encode(2, 3, n); }
  void identifier(unsigned short n) { encode(4, 5, n); }
  void sequence_number(unsigned short n) { encode(6, 7, n); }

  friend std::istream& operator>>(std::istream& is, icmp_header& header)
    { return is.read(reinterpret_cast<char*>(header.rep_), 8); }

  friend std::ostream& operator<<(std::ostream& os, const icmp_header& header)
    { return os.write(reinterpret_cast<const char*>(header.rep_), 8); }

private:
  unsigned short decode(int a, int b) const
    { return (rep_[a] << 8) + rep_[b]; }

  void encode(int a, int b, unsigned short n)
  {
    rep_[a] = static_cast<unsigned char>(n >> 8);
    rep_[b] = static_cast<unsigned char>(n & 0xFF);
  }

  unsigned char rep_[8];
};

template <typename Iterator>
void compute_checksum(icmp_header& header,
    Iterator body_begin, Iterator body_end)
{
  unsigned int sum = (header.type() << 8) + header.code()
    + header.identifier() + header.sequence_number();

  Iterator body_iter = body_begin;
  while (body_iter != body_end)
  {
    sum += (static_cast<unsigned char>(*body_iter++) << 8);
    if (body_iter != body_end)
      sum += static_cast<unsigned char>(*body_iter++);
  }

  sum = (sum >> 16) + (sum & 0xFFFF);
  sum += (sum >> 16);
  header.checksum(static_cast<unsigned short>(~sum));
}

class Pinger
{
public:
  Pinger(boost::asio::io_service& io_service, const uint8_t* destinationIP, uint8_t tries)
    : resolver_(io_service), socket_(io_service, icmp::v4()),
      timer_(io_service), sequence_number_(0), num_replies_(0)
  {
    boost::asio::ip::address_v4::bytes_type address = { { destinationIP[3], destinationIP[2], destinationIP[1], destinationIP[0] } };
    destination_ = icmp::endpoint(boost::asio::ip::address_v4(address),0);
    start_send();
    start_receive();
  }

    int replies() { return num_replies_; }

private:
  void start_send()
  {
    std::string body("\"Hello!\" from Asio ping.");

    // Create an ICMP header for an echo request.
    icmp_header echo_request;
    echo_request.type(icmp_header::echo_request);
    echo_request.code(0);
    echo_request.identifier(get_identifier());
    echo_request.sequence_number(++sequence_number_);
    compute_checksum(echo_request, body.begin(), body.end());

    // Encode the request packet.
    boost::asio::streambuf request_buffer;
    std::ostream os(&request_buffer);
    os << echo_request << body;

    // Send the request.
    time_sent_ = posix_time::microsec_clock::universal_time();
    socket_.send_to(request_buffer.data(), destination_);

    // Wait up to five seconds for a reply.
    num_replies_ = 0;
    timer_.expires_at(time_sent_ + posix_time::seconds(5));
    timer_.async_wait(boost::bind(&Pinger::handle_timeout, this));
  }

  void handle_timeout()
  {
    // Requests must be sent no less than one second apart.
    timer_.expires_at(time_sent_ + posix_time::seconds(1));
    timer_.async_wait(boost::bind(&Pinger::start_send, this));
  }

  void start_receive()
  {
    // Discard any data already in the buffer.
    reply_buffer_.consume(reply_buffer_.size());

    // Wait for a reply. We prepare the buffer to receive up to 64KB.
    socket_.async_receive(reply_buffer_.prepare(65536),
        boost::bind(&Pinger::handle_receive, this, _2));
  }

  void handle_receive(std::size_t length)
  {
    // The actual number of bytes received is committed to the buffer so that we
    // can extract it using a std::istream object.
    reply_buffer_.commit(length);

    // Decode the reply packet.
    std::istream is(&reply_buffer_);
    ipv4_header ipv4_hdr;
    icmp_header icmp_hdr;
    is >> ipv4_hdr >> icmp_hdr;

    // We can receive all ICMP packets received by the host, so we need to
    // filter out only the echo replies that match the our identifier and
    // expected sequence number.
    if (is && icmp_hdr.type() == icmp_header::echo_reply
          && icmp_hdr.identifier() == get_identifier()
          && icmp_hdr.sequence_number() == sequence_number_)
    {
      // If this is the first reply, interrupt the five second timeout.
      if (num_replies_++ == 0)
        timer_.cancel();
    }

    start_receive();
  }

  static unsigned short get_identifier()
  {
#if defined(BOOST_ASIO_WINDOWS)
    return static_cast<unsigned short>(::GetCurrentProcessId());
#else
    return static_cast<unsigned short>(::getpid());
#endif
  }

  icmp::resolver resolver_;
  icmp::endpoint destination_;
  icmp::socket socket_;
  deadline_timer timer_;
  unsigned short sequence_number_;
  posix_time::ptime time_sent_;
  boost::asio::streambuf reply_buffer_;
  std::size_t num_replies_;
};

int inet_ping(const HAL_IPAddress* address, uint8_t nTries)
{
    MSG("pinging");
    int count = 0;
    try {
        boost::asio::io_service io_service;
        Pinger p(io_service, (const uint8_t*)&address->ipv4, nTries);
        io_service.run();
        count = p.replies();
    }
    catch (std::exception& e)
    {
    }
    return count;
}

max_stars_repo_name: sedurCode/nodOSC

max_issues_repo_name: sedurCode/nodOSC

max_forks_repo_name: sedurCode/nodOSC


text:
#pragma once

#include <Eigen/Dense>

namespace pd::ecs::cmp::tabbedWindow
{
	// ---------------------------------------------------------------------------------------------------------
	class MovementActive
	{
	public:
		Eigen::Vector2i cursorInTabSpacePosition = { 0, 0 };
	};

	// ---------------------------------------------------------------------------------------------------------
	class MovementRequest
	{
	public:
		Eigen::Vector2i newWindowPos;
	};
}

ext: hpp

max_stars_repo_name: PolyEngineTeam/PolyDock

max_issues_repo_name: Qt-Widgets/PolyDock

max_forks_repo_name: Qt-Widgets/PolyDock


text: #include <boost/hana/at_key.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
//
// Copyright (c) 2018-2019 Christian Mazakas (christian dot mazakas at gmail dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt
// or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// Official repository: https://github.com/LeonineKing1199/foxy
//

#ifndef FOXY_CLIENT_SESSION_HPP_
#define FOXY_CLIENT_SESSION_HPP_

#include <foxy/session.hpp>
#include <foxy/type_traits.hpp>
#include <foxy/utility.hpp>
#include <foxy/detail/timed_op_wrapper_v3.hpp>

#include <boost/system/error_code.hpp>

#include <boost/asio/async_result.hpp>
#include <boost/asio/associated_executor.hpp>
#include <boost/asio/associated_allocator.hpp>
#include <boost/asio/executor_work_guard.hpp>

#include <boost/asio/post.hpp>
#include <boost/asio/executor.hpp>
#include <boost/asio/coroutine.hpp>

#include <boost/asio/connect.hpp>

#include <boost/beast/http/read.hpp>
#include <boost/beast/http/write.hpp>
#include <boost/beast/core/bind_handler.hpp>

#include <boost/optional/optional.hpp>

#include <boost/smart_ptr/make_shared.hpp>
#include <boost/smart_ptr/allocate_unique.hpp>

#include <boost/container/container_fwd.hpp>

#include <boost/utility/string_view.hpp>

#include <chrono>
#include <string>
#include <utility>
#include <memory>
#include <functional>

namespace foxy
{
template <class DynamicBuffer>
struct basic_client_session : public basic_session<boost::asio::ip::tcp::socket, DynamicBuffer>
{
public:
  basic_client_session()                            = delete;
  basic_client_session(basic_client_session const&) = delete;
  basic_client_session(basic_client_session&&)      = default;

  template <class... BufferArgs>
  basic_client_session(boost::asio::executor executor, session_opts opts, BufferArgs&&... bargs)
    : basic_session<boost::asio::ip::tcp::socket, DynamicBuffer>(executor,
                                                                 std::move(opts),
                                                                 std::forward<BufferArgs>(bargs)...)
  {
  }

  template <class ConnectHandler>
  auto
  async_connect(std::string host, std::string service, ConnectHandler&& handler) & ->
    typename boost::asio::async_result<std::decay_t<ConnectHandler>,
                                       void(boost::system::error_code)>::return_type;

  template <class Request, class ResponseParser, class RequestHandler>
  auto
  async_request(Request const& request, ResponseParser& parser, RequestHandler&& handler) & ->
    typename boost::asio::async_result<std::decay_t<RequestHandler>,
                                       void(boost::system::error_code)>::return_type;

  template <class ShutdownHandler>
  auto
  async_shutdown(ShutdownHandler&& handler) & ->
    typename boost::asio::async_result<std::decay_t<ShutdownHandler>,
                                       void(boost::system::error_code)>::return_type;
};

using client_session = basic_client_session<boost::beast::flat_buffer>;

namespace pmr
{
template <class T>
using client_session = basic_client_session<
  boost::beast::basic_flat_buffer<boost::container::pmr::polymorphic_allocator<T>>>;
}

} // namespace foxy

#include <foxy/impl/client_session/async_connect.impl.hpp>
#include <foxy/impl/client_session/async_request.impl.hpp>
#include <foxy/impl/client_session/async_shutdown.impl.hpp>

#endif // FOXY_CLIENT_SESSION_HPP_

max_stars_repo_name: Olipro/foxy

max_issues_repo_name: Olipro/foxy

max_forks_repo_name: Olipro/foxy


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

// Copyright (c) 2007-2014 Barend Gehrels, Amsterdam, the Netherlands.
// Copyright (c) 2013-2014 Adam Wulkiewicz, Lodz, Poland.

// This file was modified by Oracle on 2014, 2016, 2017.
// Modifications copyright (c) 2014-2017, Oracle and/or its affiliates.

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

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

#ifndef BOOST_GEOMETRY_STRATEGIES_CARTESIAN_INTERSECTION_HPP
#define BOOST_GEOMETRY_STRATEGIES_CARTESIAN_INTERSECTION_HPP

#include <algorithm>

#include <boost/geometry/core/exception.hpp>

#include <boost/geometry/geometries/concepts/point_concept.hpp>
#include <boost/geometry/geometries/concepts/segment_concept.hpp>

#include <boost/geometry/arithmetic/determinant.hpp>
#include <boost/geometry/algorithms/detail/assign_values.hpp>
#include <boost/geometry/algorithms/detail/assign_indexed_point.hpp>
#include <boost/geometry/algorithms/detail/equals/point_point.hpp>
#include <boost/geometry/algorithms/detail/recalculate.hpp>

#include <boost/geometry/util/math.hpp>
#include <boost/geometry/util/promote_integral.hpp>
#include <boost/geometry/util/select_calculation_type.hpp>

#include <boost/geometry/strategies/cartesian/area_surveyor.hpp>
#include <boost/geometry/strategies/cartesian/distance_pythagoras.hpp>
#include <boost/geometry/strategies/cartesian/envelope_segment.hpp>
#include <boost/geometry/strategies/cartesian/point_in_poly_winding.hpp>
#include <boost/geometry/strategies/cartesian/side_by_triangle.hpp>
#include <boost/geometry/strategies/covered_by.hpp>
#include <boost/geometry/strategies/intersection.hpp>
#include <boost/geometry/strategies/intersection_result.hpp>
#include <boost/geometry/strategies/side.hpp>
#include <boost/geometry/strategies/side_info.hpp>
#include <boost/geometry/strategies/within.hpp>

#include <boost/geometry/policies/robustness/robust_point_type.hpp>
#include <boost/geometry/policies/robustness/segment_ratio_type.hpp>

#if defined(BOOST_GEOMETRY_DEBUG_ROBUSTNESS)
#  include <boost/geometry/io/wkt/write.hpp>
#endif

namespace boost { namespace geometry
{

namespace strategy { namespace intersection
{

/*!
    \see http://mathworld.wolfram.com/Line-LineIntersection.html
 */
template
<
    typename CalculationType = void
>
struct cartesian_segments
{
    typedef side::side_by_triangle<CalculationType> side_strategy_type;

    static inline side_strategy_type get_side_strategy()
    {
        return side_strategy_type();
    }

    template <typename Geometry1, typename Geometry2>
    struct point_in_geometry_strategy
    {
        typedef strategy::within::cartesian_winding
            <
                typename point_type<Geometry1>::type,
                typename point_type<Geometry2>::type,
                CalculationType
            > type;
    };

    template <typename Geometry1, typename Geometry2>
    static inline typename point_in_geometry_strategy<Geometry1, Geometry2>::type
        get_point_in_geometry_strategy()
    {
        typedef typename point_in_geometry_strategy
            <
                Geometry1, Geometry2
            >::type strategy_type;
        return strategy_type();
    }

    template <typename Geometry>
    struct area_strategy
    {
        typedef area::surveyor
            <
                typename point_type<Geometry>::type,
                CalculationType
            > type;
    };

    template <typename Geometry>
    static inline typename area_strategy<Geometry>::type get_area_strategy()
    {
        typedef typename area_strategy<Geometry>::type strategy_type;
        return strategy_type();
    }

    template <typename Geometry>
    struct distance_strategy
    {
        typedef distance::pythagoras
            <
                CalculationType
            > type;
    };

    template <typename Geometry>
    static inline typename distance_strategy<Geometry>::type get_distance_strategy()
    {
        typedef typename distance_strategy<Geometry>::type strategy_type;
        return strategy_type();
    }

    typedef envelope::cartesian_segment<CalculationType>
        envelope_strategy_type;

    static inline envelope_strategy_type get_envelope_strategy()
    {
        return envelope_strategy_type();
    }

    template <typename CoordinateType, typename SegmentRatio>
    struct segment_intersection_info
    {
        typedef typename select_most_precise
            <
                CoordinateType, double
            >::type promoted_type;

        promoted_type comparable_length_a() const
        {
            return dx_a * dx_a + dy_a * dy_a;
        }

        promoted_type comparable_length_b() const
        {
            return dx_b * dx_b + dy_b * dy_b;
        }

        template <typename Point, typename Segment1, typename Segment2>
        void assign_a(Point& point, Segment1 const& a, Segment2 const& ) const
        {
            assign(point, a, dx_a, dy_a, robust_ra);
        }
        template <typename Point, typename Segment1, typename Segment2>
        void assign_b(Point& point, Segment1 const& , Segment2 const& b) const
        {
            assign(point, b, dx_b, dy_b, robust_rb);
        }

        template <typename Point, typename Segment>
        void assign(Point& point, Segment const& segment, CoordinateType const& dx, CoordinateType const& dy, SegmentRatio const& ratio) const
        {
            // Calculate the intersection point based on segment_ratio
            // Up to now, division was postponed. Here we divide using numerator/
            // denominator. In case of integer this results in an integer
            // division.
            BOOST_GEOMETRY_ASSERT(ratio.denominator() != 0);

            typedef typename promote_integral<CoordinateType>::type promoted_type;

            promoted_type const numerator
                = boost::numeric_cast<promoted_type>(ratio.numerator());
            promoted_type const denominator
                = boost::numeric_cast<promoted_type>(ratio.denominator());
            promoted_type const dx_promoted = boost::numeric_cast<promoted_type>(dx);
            promoted_type const dy_promoted = boost::numeric_cast<promoted_type>(dy);

            set<0>(point, get<0, 0>(segment) + boost::numeric_cast
                <
                    CoordinateType
                >(numerator * dx_promoted / denominator));
            set<1>(point, get<0, 1>(segment) + boost::numeric_cast
                <
                    CoordinateType
                >(numerator * dy_promoted / denominator));
        }

        CoordinateType dx_a, dy_a;
        CoordinateType dx_b, dy_b;
        SegmentRatio robust_ra;
        SegmentRatio robust_rb;
    };

    template <typename D, typename W, typename ResultType>
    static inline void cramers_rule(D const& dx_a, D const& dy_a,
        D const& dx_b, D const& dy_b, W const& wx, W const& wy,
        // out:
        ResultType& d, ResultType& da)
    {
        // Cramers rule
        d = geometry::detail::determinant<ResultType>(dx_a, dy_a, dx_b, dy_b);
        da = geometry::detail::determinant<ResultType>(dx_b, dy_b, wx, wy);
        // Ratio is da/d , collinear if d == 0, intersecting if 0 <= r <= 1
        // IntersectionPoint = (x1 + r * dx_a, y1 + r * dy_a)
    }

    // Relate segments a and b
    template
    <
        typename Segment1,
        typename Segment2,
        typename Policy,
        typename RobustPolicy
    >
    static inline typename Policy::return_type
        apply(Segment1 const& a, Segment2 const& b,
              Policy const& policy, RobustPolicy const& robust_policy)
    {
        // type them all as in Segment1 - TODO reconsider this, most precise?
        typedef typename geometry::point_type<Segment1>::type point_type;

        typedef typename geometry::robust_point_type
            <
                point_type, RobustPolicy
            >::type robust_point_type;

        point_type a0, a1, b0, b1;
        robust_point_type a0_rob, a1_rob, b0_rob, b1_rob;

        detail::assign_point_from_index<0>(a, a0);
        detail::assign_point_from_index<1>(a, a1);
        detail::assign_point_from_index<0>(b, b0);
        detail::assign_point_from_index<1>(b, b1);

        geometry::recalculate(a0_rob, a0, robust_policy);
        geometry::recalculate(a1_rob, a1, robust_policy);
        geometry::recalculate(b0_rob, b0, robust_policy);
        geometry::recalculate(b1_rob, b1, robust_policy);

        return apply(a, b, policy, robust_policy, a0_rob, a1_rob, b0_rob, b1_rob);
    }

    // The main entry-routine, calculating intersections of segments a / b
    // NOTE: Robust* types may be the same as Segments' point types
    template
    <
        typename Segment1,
        typename Segment2,
        typename Policy,
        typename RobustPolicy,
        typename RobustPoint1,
        typename RobustPoint2
    >
    static inline typename Policy::return_type
        apply(Segment1 const& a, Segment2 const& b,
              Policy const&, RobustPolicy const& /*robust_policy*/,
              RobustPoint1 const& robust_a1, RobustPoint1 const& robust_a2,
              RobustPoint2 const& robust_b1, RobustPoint2 const& robust_b2)
    {
        BOOST_CONCEPT_ASSERT( (concepts::ConstSegment<Segment1>) );
        BOOST_CONCEPT_ASSERT( (concepts::ConstSegment<Segment2>) );

        using geometry::detail::equals::equals_point_point;
        bool const a_is_point = equals_point_point(robust_a1, robust_a2);
        bool const b_is_point = equals_point_point(robust_b1, robust_b2);

        if(a_is_point && b_is_point)
        {
            return equals_point_point(robust_a1, robust_b2)
                ? Policy::degenerate(a, true)
                : Policy::disjoint()
                ;
        }

        side_info sides;
        sides.set<0>(side_strategy_type::apply(robust_b1, robust_b2, robust_a1),
                     side_strategy_type::apply(robust_b1, robust_b2, robust_a2));

        if (sides.same<0>())
        {
            // Both points are at same side of other segment, we can leave
            return Policy::disjoint();
        }

        sides.set<1>(side_strategy_type::apply(robust_a1, robust_a2, robust_b1),
                     side_strategy_type::apply(robust_a1, robust_a2, robust_b2));

        if (sides.same<1>())
        {
            // Both points are at same side of other segment, we can leave
            return Policy::disjoint();
        }

        bool collinear = sides.collinear();

        typedef typename select_most_precise
            <
                typename geometry::coordinate_type<RobustPoint1>::type,
                typename geometry::coordinate_type<RobustPoint2>::type
            >::type robust_coordinate_type;

        typedef typename segment_ratio_type
            <
                typename geometry::point_type<Segment1>::type, // TODO: most precise point?
                RobustPolicy
            >::type ratio_type;

        segment_intersection_info
            <
                typename select_calculation_type<Segment1, Segment2, CalculationType>::type,
                ratio_type
            > sinfo;

        sinfo.dx_a = get<1, 0>(a) - get<0, 0>(a); // distance in x-dir
        sinfo.dx_b = get<1, 0>(b) - get<0, 0>(b);
        sinfo.dy_a = get<1, 1>(a) - get<0, 1>(a); // distance in y-dir
        sinfo.dy_b = get<1, 1>(b) - get<0, 1>(b);

        robust_coordinate_type const robust_dx_a = get<0>(robust_a2) - get<0>(robust_a1);
        robust_coordinate_type const robust_dx_b = get<0>(robust_b2) - get<0>(robust_b1);
        robust_coordinate_type const robust_dy_a = get<1>(robust_a2) - get<1>(robust_a1);
        robust_coordinate_type const robust_dy_b = get<1>(robust_b2) - get<1>(robust_b1);

        // r: ratio 0-1 where intersection divides A/B
        // (only calculated for non-collinear segments)
        if (! collinear)
        {
            robust_coordinate_type robust_da0, robust_da;
            robust_coordinate_type robust_db0, robust_db;

            cramers_rule(robust_dx_a, robust_dy_a, robust_dx_b, robust_dy_b,
                get<0>(robust_a1) - get<0>(robust_b1),
                get<1>(robust_a1) - get<1>(robust_b1),
                robust_da0, robust_da);

            cramers_rule(robust_dx_b, robust_dy_b, robust_dx_a, robust_dy_a,
                get<0>(robust_b1) - get<0>(robust_a1),
                get<1>(robust_b1) - get<1>(robust_a1),
                robust_db0, robust_db);

            math::detail::equals_factor_policy<robust_coordinate_type>
                policy(robust_dx_a, robust_dy_a, robust_dx_b, robust_dy_b);
            robust_coordinate_type const zero = 0;
            if (math::detail::equals_by_policy(robust_da0, zero, policy)
             || math::detail::equals_by_policy(robust_db0, zero, policy))
            {
                // If this is the case, no rescaling is done for FP precision.
                // We set it to collinear, but it indicates a robustness issue.
                sides.set<0>(0,0);
                sides.set<1>(0,0);
                collinear = true;
            }
            else
            {
                sinfo.robust_ra.assign(robust_da, robust_da0);
                sinfo.robust_rb.assign(robust_db, robust_db0);
            }
        }

        if (collinear)
        {
            std::pair<bool, bool> const collinear_use_first
                    = is_x_more_significant(geometry::math::abs(robust_dx_a),
                                            geometry::math::abs(robust_dy_a),
                                            geometry::math::abs(robust_dx_b),
                                            geometry::math::abs(robust_dy_b),
                                            a_is_point, b_is_point);

            if (collinear_use_first.second)
            {
                // Degenerate cases: segments of single point, lying on other segment, are not disjoint
                // This situation is collinear too

                if (collinear_use_first.first)
                {
                    return relate_collinear<0, Policy, ratio_type>(a, b,
                            robust_a1, robust_a2, robust_b1, robust_b2,
                            a_is_point, b_is_point);
                }
                else
                {
                    // Y direction contains larger segments (maybe dx is zero)
                    return relate_collinear<1, Policy, ratio_type>(a, b,
                            robust_a1, robust_a2, robust_b1, robust_b2,
                            a_is_point, b_is_point);
                }
            }
        }

        return Policy::segments_crosses(sides, sinfo, a, b);
    }

private:
    // first is true if x is more significant
    // second is true if the more significant difference is not 0
    template <typename RobustCoordinateType>
    static inline std::pair<bool, bool>
        is_x_more_significant(RobustCoordinateType const& abs_robust_dx_a,
                              RobustCoordinateType const& abs_robust_dy_a,
                              RobustCoordinateType const& abs_robust_dx_b,
                              RobustCoordinateType const& abs_robust_dy_b,
                              bool const a_is_point,
                              bool const b_is_point)
    {
        //BOOST_GEOMETRY_ASSERT_MSG(!(a_is_point && b_is_point), "both segments shouldn't be degenerated");

        // for degenerated segments the second is always true because this function
        // shouldn't be called if both segments were degenerated

        if (a_is_point)
        {
            return std::make_pair(abs_robust_dx_b >= abs_robust_dy_b, true);
        }
        else if (b_is_point)
        {
            return std::make_pair(abs_robust_dx_a >= abs_robust_dy_a, true);
        }
        else
        {
            RobustCoordinateType const min_dx = (std::min)(abs_robust_dx_a, abs_robust_dx_b);
            RobustCoordinateType const min_dy = (std::min)(abs_robust_dy_a, abs_robust_dy_b);
            return min_dx == min_dy ?
                    std::make_pair(true, min_dx > RobustCoordinateType(0)) :
                    std::make_pair(min_dx > min_dy, true);
        }
    }

    template
    <
        std::size_t Dimension,
        typename Policy,
        typename RatioType,
        typename Segment1,
        typename Segment2,
        typename RobustPoint1,
        typename RobustPoint2
    >
    static inline typename Policy::return_type
        relate_collinear(Segment1 const& a,
                         Segment2 const& b,
                         RobustPoint1 const& robust_a1, RobustPoint1 const& robust_a2,
                         RobustPoint2 const& robust_b1, RobustPoint2 const& robust_b2,
                         bool a_is_point, bool b_is_point)
    {
        if (a_is_point)
        {
            return relate_one_degenerate<Policy, RatioType>(a,
                get<Dimension>(robust_a1),
                get<Dimension>(robust_b1), get<Dimension>(robust_b2),
                true);
        }
        if (b_is_point)
        {
            return relate_one_degenerate<Policy, RatioType>(b,
                get<Dimension>(robust_b1),
                get<Dimension>(robust_a1), get<Dimension>(robust_a2),
                false);
        }
        return relate_collinear<Policy, RatioType>(a, b,
                                get<Dimension>(robust_a1),
                                get<Dimension>(robust_a2),
                                get<Dimension>(robust_b1),
                                get<Dimension>(robust_b2));
    }

    /// Relate segments known collinear
    template
    <
        typename Policy,
        typename RatioType,
        typename Segment1,
        typename Segment2,
        typename RobustType1,
        typename RobustType2
    >
    static inline typename Policy::return_type
        relate_collinear(Segment1 const& a, Segment2 const& b,
                         RobustType1 oa_1, RobustType1 oa_2,
                         RobustType2 ob_1, RobustType2 ob_2)
    {
        // Calculate the ratios where a starts in b, b starts in a
        //         a1--------->a2         (2..7)
        //                b1----->b2      (5..8)
        // length_a: 7-2=5
        // length_b: 8-5=3
        // b1 is located w.r.t. a at ratio: (5-2)/5=3/5 (on a)
        // b2 is located w.r.t. a at ratio: (8-2)/5=6/5 (right of a)
        // a1 is located w.r.t. b at ratio: (2-5)/3=-3/3 (left of b)
        // a2 is located w.r.t. b at ratio: (7-5)/3=2/3 (on b)
        // A arrives (a2 on b), B departs (b1 on a)

        // If both are reversed:
        //         a2<---------a1         (7..2)
        //                b2<-----b1      (8..5)
        // length_a: 2-7=-5
        // length_b: 5-8=-3
        // b1 is located w.r.t. a at ratio: (8-7)/-5=-1/5 (before a starts)
        // b2 is located w.r.t. a at ratio: (5-7)/-5=2/5 (on a)
        // a1 is located w.r.t. b at ratio: (7-8)/-3=1/3 (on b)
        // a2 is located w.r.t. b at ratio: (2-8)/-3=6/3 (after b ends)

        // If both one is reversed:
        //         a1--------->a2         (2..7)
        //                b2<-----b1      (8..5)
        // length_a: 7-2=+5
        // length_b: 5-8=-3
        // b1 is located w.r.t. a at ratio: (8-2)/5=6/5 (after a ends)
        // b2 is located w.r.t. a at ratio: (5-2)/5=3/5 (on a)
        // a1 is located w.r.t. b at ratio: (2-8)/-3=6/3 (after b ends)
        // a2 is located w.r.t. b at ratio: (7-8)/-3=1/3 (on b)
        RobustType1 const length_a = oa_2 - oa_1; // no abs, see above
        RobustType2 const length_b = ob_2 - ob_1;

        RatioType ra_from(oa_1 - ob_1, length_b);
        RatioType ra_to(oa_2 - ob_1, length_b);
        RatioType rb_from(ob_1 - oa_1, length_a);
        RatioType rb_to(ob_2 - oa_1, length_a);

        // use absolute measure to detect endpoints intersection
        // NOTE: it'd be possible to calculate bx_wrt_a using ax_wrt_b values
        int const a1_wrt_b = position_value(oa_1, ob_1, ob_2);
        int const a2_wrt_b = position_value(oa_2, ob_1, ob_2);
        int const b1_wrt_a = position_value(ob_1, oa_1, oa_2);
        int const b2_wrt_a = position_value(ob_2, oa_1, oa_2);

        // fix the ratios if necessary
        // CONSIDER: fixing ratios also in other cases, if they're inconsistent
        // e.g. if ratio == 1 or 0 (so IP at the endpoint)
        // but position value indicates that the IP is in the middle of the segment
        // because one of the segments is very long
        // In such case the ratios could be moved into the middle direction
        // by some small value (e.g. EPS+1ULP)
        if (a1_wrt_b == 1)
        {
            ra_from.assign(0, 1);
            rb_from.assign(0, 1);
        }
        else if (a1_wrt_b == 3)
        {
            ra_from.assign(1, 1);
            rb_to.assign(0, 1);
        }

        if (a2_wrt_b == 1)
        {
            ra_to.assign(0, 1);
            rb_from.assign(1, 1);
        }
        else if (a2_wrt_b == 3)
        {
            ra_to.assign(1, 1);
            rb_to.assign(1, 1);
        }

        if ((a1_wrt_b < 1 && a2_wrt_b < 1) || (a1_wrt_b > 3 && a2_wrt_b > 3))
        //if ((ra_from.left() && ra_to.left()) || (ra_from.right() && ra_to.right()))
        {
            return Policy::disjoint();
        }

        bool const opposite = math::sign(length_a) != math::sign(length_b);

        return Policy::segments_collinear(a, b, opposite,
                                          a1_wrt_b, a2_wrt_b, b1_wrt_a, b2_wrt_a,
                                          ra_from, ra_to, rb_from, rb_to);
    }

    /// Relate segments where one is degenerate
    template
    <
        typename Policy,
        typename RatioType,
        typename DegenerateSegment,
        typename RobustType1,
        typename RobustType2
    >
    static inline typename Policy::return_type
        relate_one_degenerate(DegenerateSegment const& degenerate_segment,
                              RobustType1 d, RobustType2 s1, RobustType2 s2,
                              bool a_degenerate)
    {
        // Calculate the ratios where ds starts in s
        //         a1--------->a2         (2..6)
        //              b1/b2      (4..4)
        // Ratio: (4-2)/(6-2)
        RatioType const ratio(d - s1, s2 - s1);

        if (!ratio.on_segment())
        {
            return Policy::disjoint();
        }

        return Policy::one_degenerate(degenerate_segment, ratio, a_degenerate);
    }

    template <typename ProjCoord1, typename ProjCoord2>
    static inline int position_value(ProjCoord1 const& ca1,
                                     ProjCoord2 const& cb1,
                                     ProjCoord2 const& cb2)
    {
        // S1x  0   1    2     3   4
        // S2       |---------->
        return math::equals(ca1, cb1) ? 1
             : math::equals(ca1, cb2) ? 3
             : cb1 < cb2 ?
                ( ca1 < cb1 ? 0
                : ca1 > cb2 ? 4
                : 2 )
              : ( ca1 > cb1 ? 0
                : ca1 < cb2 ? 4
                : 2 );
    }
};

#ifndef DOXYGEN_NO_STRATEGY_SPECIALIZATIONS
namespace services
{

template <typename CalculationType>
struct default_strategy<cartesian_tag, CalculationType>
{
    typedef cartesian_segments<CalculationType> type;
};

} // namespace services
#endif // DOXYGEN_NO_STRATEGY_SPECIALIZATIONS

}} // namespace strategy::intersection

namespace strategy
{

namespace within { namespace services
{

template <typename Geometry1, typename Geometry2, typename AnyTag1, typename AnyTag2>
struct default_strategy<Geometry1, Geometry2, AnyTag1, AnyTag2, linear_tag, linear_tag, cartesian_tag, cartesian_tag>
{
    typedef strategy::intersection::cartesian_segments<> type;
};

template <typename Geometry1, typename Geometry2, typename AnyTag1, typename AnyTag2>
struct default_strategy<Geometry1, Geometry2, AnyTag1, AnyTag2, linear_tag, polygonal_tag, cartesian_tag, cartesian_tag>
{
    typedef strategy::intersection::cartesian_segments<> type;
};

template <typename Geometry1, typename Geometry2, typename AnyTag1, typename AnyTag2>
struct default_strategy<Geometry1, Geometry2, AnyTag1, AnyTag2, polygonal_tag, linear_tag, cartesian_tag, cartesian_tag>
{
    typedef strategy::intersection::cartesian_segments<> type;
};

template <typename Geometry1, typename Geometry2, typename AnyTag1, typename AnyTag2>
struct default_strategy<Geometry1, Geometry2, AnyTag1, AnyTag2, polygonal_tag, polygonal_tag, cartesian_tag, cartesian_tag>
{
    typedef strategy::intersection::cartesian_segments<> type;
};

}} // within::services

namespace covered_by { namespace services
{

template <typename Geometry1, typename Geometry2, typename AnyTag1, typename AnyTag2>
struct default_strategy<Geometry1, Geometry2, AnyTag1, AnyTag2, linear_tag, linear_tag, cartesian_tag, cartesian_tag>
{
    typedef strategy::intersection::cartesian_segments<> type;
};

template <typename Geometry1, typename Geometry2, typename AnyTag1, typename AnyTag2>
struct default_strategy<Geometry1, Geometry2, AnyTag1, AnyTag2, linear_tag, polygonal_tag, cartesian_tag, cartesian_tag>
{
    typedef strategy::intersection::cartesian_segments<> type;
};

template <typename Geometry1, typename Geometry2, typename AnyTag1, typename AnyTag2>
struct default_strategy<Geometry1, Geometry2, AnyTag1, AnyTag2, polygonal_tag, linear_tag, cartesian_tag, cartesian_tag>
{
    typedef strategy::intersection::cartesian_segments<> type;
};

template <typename Geometry1, typename Geometry2, typename AnyTag1, typename AnyTag2>
struct default_strategy<Geometry1, Geometry2, AnyTag1, AnyTag2, polygonal_tag, polygonal_tag, cartesian_tag, cartesian_tag>
{
    typedef strategy::intersection::cartesian_segments<> type;
};

}} // within::services

} // strategy

}} // namespace boost::geometry

#endif // BOOST_GEOMETRY_STRATEGIES_CARTESIAN_INTERSECTION_HPP

max_stars_repo_name: SnailTowardThesun/face-detect

max_issues_repo_name: SnailTowardThesun/face-detect

max_forks_repo_name: gradinkov/nheqminer-gradinkov


text:
#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>
#include <CGAL/Polyhedron_3.h>
#include <CGAL/Polygon_mesh_processing/compute_normal.h>
#include <boost/property_map/property_map.hpp>

#include <map>
// #include <CGAL/Unique_hash_map.h>
// #include <boost/unordered_map.hpp>

#include <iostream>
#include <fstream>

typedef CGAL::Exact_predicates_inexact_constructions_kernel K;
typedef K::Point_3 Point;
typedef K::Vector_3 Vector;

typedef CGAL::Polyhedron_3<K> Polyhedron;
typedef boost::graph_traits<Polyhedron>::vertex_descriptor vertex_descriptor;
typedef boost::graph_traits<Polyhedron>::face_descriptor   face_descriptor;

int main(int argc, char* argv[])
{
  const char* filename = (argc > 1) ? argv[1] : "data/eight.off";
  std::ifstream input(filename);

  Polyhedron mesh;
  if (!input || !(input >> mesh) || mesh.is_empty()) {
    std::cerr << "Not a valid off file." << std::endl;
    return 1;
  }

  std::map<face_descriptor,Vector> fnormals;
  std::map<vertex_descriptor,Vector> vnormals;
  // Instead of std::map you may use std::unordered_map, boost::unordered_map
  // or CGAL::Unique_hash_map
  // CGAL::Unique_hash_map<face_descriptor,Vector> fnormals;
  // boost::unordered_map<vertex_descriptor,Vector> vnormals;

  CGAL::Polygon_mesh_processing::compute_normals(mesh,
                                                 boost::make_assoc_property_map(vnormals),
                                                 boost::make_assoc_property_map(fnormals));

  std::cout << "Face normals :" << std::endl;
  for(face_descriptor fd: faces(mesh)){
    std::cout << fnormals[fd] << std::endl;
  }
  std::cout << "Vertex normals :" << std::endl;
  for(vertex_descriptor vd: vertices(mesh)){
    std::cout << vnormals[vd] << std::endl;
  }
  return 0;
}

ext: cpp

max_stars_repo_name: gaschler/cgal

max_issues_repo_name: gaschler/cgal

max_forks_repo_name: gaschler/cgal


text: #include <boost/mpl/aux_/preprocessed/msvc70/vector.hpp>


text:
#include "Test.h"
#include <Eigen/Dense>
#include <iostream>

typedef Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> MatrixXdR;
JNIEXPORT void JNICALL Java_Test_inverse (JNIEnv *env, jclass cls,jdoubleArray jm1,  jdoubleArray jm2, jdoubleArray jr, jint nrow, jint ncol)
{
	jboolean isCopy=JNI_TRUE;
	double* pm1=(double*)env->GetPrimitiveArrayCritical(jm1, &isCopy);
	double* pm2=(double*)env->GetPrimitiveArrayCritical(jm2, &isCopy);
	double* pr=(double*)env->GetPrimitiveArrayCritical(jr, &isCopy);
	Eigen::Map<MatrixXdR> em1(pm1, nrow, ncol);
	Eigen::Map<MatrixXdR> em2(pm2, nrow, ncol);
	Eigen::Map<MatrixXdR> er(pr, nrow, ncol);
	er=em1*em2; //.inverse();

	/*
	std::cout << "----" << std::endl;
	std::cout << em1 << std::endl;
	std::cout << em2 << std::endl;
	std::cout << er << std::endl;
	*/
	env->ReleasePrimitiveArrayCritical(jm1, pm1, 0);
	env->ReleasePrimitiveArrayCritical(jm2, pm2, 0);
	env->ReleasePrimitiveArrayCritical(jr, pr, 0);
}

JNIEXPORT void inverse(double* m1, double* m2, double* r, int nrow, int ncol)
{
	Eigen::Map<MatrixXdR> em1(m1, nrow, ncol);
	Eigen::Map<MatrixXdR> em2(m2, nrow, ncol);
	Eigen::Map<MatrixXdR> er(r, nrow, ncol);
	//er=em1*em2; //.inverse();
}

max_stars_repo_name: wxmerkt/ihmc-open-robotics-software

max_issues_repo_name: wxmerkt/ihmc-open-robotics-software

max_forks_repo_name: wxmerkt/ihmc-open-robotics-software


text:
#include "dmux/connector.h"
#include <vector>
#include <iostream>
#include <boost/interprocess/sync/scoped_lock.hpp>
#include <boost/interprocess/sync/named_mutex.hpp>

using namespace dmux;

int main(int argc, char** argv)
{
    const char *name = "test";
    pconnector_type pconnector = argc < 2 ?
        connector::make<in_multiout_connector_type>(name) :
        connector::make<connector::safe_connector<
            connector::input_connector<connector::multi_connector_type>,
            connector::sharable_locker_with_sharable_pop_interface> >(name);

    if (pconnector->open())
    {
        boost::interprocess::named_mutex mutex(boost::interprocess::open_only, "test_client");
        struct timespec timeout = { 0, 0 };
        timeout.tv_sec = 1;
        struct timespec ts = { 0, 0 };
        {
            boost::interprocess::scoped_lock<boost::interprocess::named_mutex> lock(mutex);
            ts = get_monotonic_time();
            std::cout << ts.tv_sec << "." << ts.tv_nsec << "\t: open " << argc << std::endl;
        }
        while (true)
        {
            pmessage_type pmessage = pconnector->get(timeout);
            if (!pmessage)
            {
                ts = get_monotonic_time();
                std::cout << ts.tv_sec << "." << ts.tv_nsec << "\t: close" << std::endl;
                boost::interprocess::scoped_lock<boost::interprocess::named_mutex> lock(mutex);
                return 0;
            }
            const size_t size = pmessage->data_size();
            if (size > 0)
            {
                std::vector<char> s(size);
                pmessage->unpack(&s[0]);
                ts = get_monotonic_time();
                std::cout << ts.tv_sec << "." << ts.tv_nsec << "\t: " << &s[0] << std::endl;
            }
            pconnector->pop(timeout);
        }
    }
    return 0;
}

max_stars_repo_name: belyaev-ms/dmux

max_issues_repo_name: belyaev-ms/dmux

max_forks_repo_name: belyaev-ms/dmux


text:
#ifndef BASETYPES
#define BASETYPES

/** \file BaseTypes.hpp
 * \brief Basic type definitions and global constants */

#include <armadillo>

using Matrix = arma::mat;
using Vector = arma::vec;
using Vector_un = arma::Col<unsigned>;

namespace math
{
const double pi = arma::datum::pi;
const double rpi2 = 1.0 / (2.0 * pi);
};

#endif

max_stars_repo_name: gdeskos/DVMpp

max_issues_repo_name: gdeskos/DVMpp

max_forks_repo_name: gdeskos/DVMpp


text:
#include <boost_adaptbx/graph/graph_type.hpp>
#include <boost_adaptbx/graph/graph_export_adaptor.hpp>
#include <boost_adaptbx/graph/vertex_map.hpp>

#include <boost_adaptbx/exporting.hpp>

#include <boost/python/module.hpp>
#include <boost/python/def.hpp>
#include <boost/python/list.hpp>
#include <boost/python/tuple.hpp>

#include <boost/graph/graph_traits.hpp>
#include <boost/graph/mcgregor_common_subgraphs.hpp>
#include <boost/property_map/property_map.hpp>

#include <map>
#include <iterator>

namespace boost_adaptbx
{
namespace
{

template< typename Graph >
class mcg_python_callback_adaptor
{
public:
  typedef boost::graph_traits< Graph > graph_traits;
  typedef typename graph_traits::vertex_descriptor vertex_descriptor;
  typedef typename graph_traits::vertices_size_type vertices_size_type;

  typedef graph_export_adaptor::vertex_descriptor_converter< vertex_descriptor > converter;

private:
  const Graph& m_graph1;
  const Graph& m_graph2;
  boost::python::object m_callable;

public:

mcg_python_callback_adaptor(
  Graph const& graph1,
  Graph const& graph2,
  boost::python::object callable
  )
  : m_graph1( graph1 ), m_graph2( graph2 ), m_callable( callable )
{}

~mcg_python_callback_adaptor()
{}

template< typename VertexMap >
bool operator()(
  VertexMap cmap_1_to_2,
  VertexMap cmap_2_to_1,
  vertices_size_type subgraph_size
  )
{
  boost::python::list pairs;

  BGL_FORALL_VERTICES_T(vertex1, m_graph1, Graph)
  {
    vertex_descriptor vertex2 = boost::get( cmap_1_to_2, vertex1 );

    if ( vertex2 != graph_traits::null_vertex() )
    {
      pairs.append(
        boost::python::make_tuple( converter::forward( vertex1 ), converter::forward( vertex2 ) )
        );
    }
  }

  return m_callable( pairs );
}

};

template< typename PropertyMap >
class python_property_equivalent
{
private:
  const PropertyMap m_property_map1;
  const PropertyMap m_property_map2;
  boost::python::object m_callable;

public:

python_property_equivalent(
  PropertyMap const property_map1,
  PropertyMap const property_map2,
  boost::python::object callable
  )
  : m_property_map1( property_map1 ), m_property_map2( property_map2 ),
    m_callable( callable )
{}

template< typename Item >
bool operator()(Item const item1, Item const item2)
{
  typename PropertyMap::value_type property1 = get(m_property_map1, item1);
  typename PropertyMap::value_type property2 = get(m_property_map2, item2);

  return m_callable( property1, property2 );
}

};

template< typename PropertyMap >
python_property_equivalent< PropertyMap >
make_python_property_equivalent(
  PropertyMap const property_map1,
  PropertyMap const property_map2,
  boost::python::object callable
  )
{
  return python_property_equivalent< PropertyMap >(
    property_map1,
    property_map2,
    callable
    );
}

template< typename Graph >
struct mcgregor_common_subgraphs_unique_export
{
  typedef Graph graph_type;
  typedef boost::graph_traits< Graph > graph_traits;
  typedef typename graph_traits::vertex_descriptor vertex_descriptor;
  typedef typename graph_traits::vertices_size_type vertices_size_type;
  typedef vertex_map::index_map< graph_type > index_map_type;

  static
  void
  mcgregor_common_subgraphs_unique(
    graph_type const& graph1,
    graph_type  const& graph2,
    boost::python::object vertex_equality,
    boost::python::object edge_equality,
    boost::python::object callback
    )
  {
    // Vertex equality
    typedef typename boost::property_map< graph_type, boost::vertex_name_t>::const_type vertex_name_map_t;
    typedef python_property_equivalent< vertex_name_map_t > vertex_comp_t;
    vertex_comp_t vertex_comp = make_python_property_equivalent(
      boost::get( boost::vertex_name_t(), graph1 ),
      boost::get( boost::vertex_name_t(), graph2 ),
      vertex_equality
      );

    // Edge equality
    typedef typename boost::property_map< graph_type, boost::edge_weight_t >::const_type edge_weight_map_t;
    typedef python_property_equivalent< edge_weight_map_t > edge_comp_t;
    edge_comp_t edge_comp = make_python_property_equivalent(
      boost::get( boost::edge_weight_t(), graph1 ),
      boost::get( boost::edge_weight_t(), graph2 ),
      edge_equality
      );

    // Callback
    mcg_python_callback_adaptor< graph_type > mcg_callback( graph1, graph2, callback );

    // Call
    index_map_type index_map1( graph1 ), index_map2( graph2 );
    boost::mcgregor_common_subgraphs_unique(
      graph1,
      graph2,
      index_map1.get(),
      index_map2.get(),
      edge_comp,
      vertex_comp,
      true,
      mcg_callback
      );
  }

  static void process()
  {
    using namespace boost::python;

    def(
      "mcgregor_common_subgraphs_unique",
      mcgregor_common_subgraphs_unique,
      ( arg( "graph1" ), arg( "graph2" ), arg( "vertex_equality" ),
        arg( "edge_equality" ), arg( "callback" ) )
      );
  }
};

struct graph_structure_comparison_exporter
{
  template< typename Export >
  void operator ()(boost::mpl::identity< Export > myexport) const
  {
    typedef typename Export::first graph_type;
    typedef typename Export::second name_type;

    mcgregor_common_subgraphs_unique_export< graph_type >::process();
  }
};

} // namespace <anonymnous>
} // namespace boost_adaptbx

BOOST_PYTHON_MODULE(boost_adaptbx_graph_graph_structure_comparison_ext)
{
  boost_adaptbx::exporting::class_list< boost_adaptbx::graph_type::exports >::process(
    boost_adaptbx::graph_structure_comparison_exporter()
    );
}


text: #include <boost/pending/lowest_bit.hpp>


text:
#include <cstring>
#include <iostream>
#include <cstdint>
#include <string>
#include <boost/filesystem.hpp>
#include <boost/program_options.hpp>
#include <libpmemblk.h>

class close_pmemblk {
public:
  template< typename T >
  void operator()( T *p ) const {
    if( p ) pmemblk_close( p );
  }
};

namespace fs = boost::filesystem;

bool is_special_file( const fs::path &p ) {
  return
    fs::status( p ).type() == fs::file_type::character_file ||
    fs::status( p ).type() == fs::file_type::block_file;
}

int main( int argc, const char *argv[] ) {
  namespace po = boost::program_options;
  po::options_description desc( "Options" );
  std::string new_value;
  uint64_t pool_size;
  std::string filename;
  desc.add_options()
    ( "help,h", "show this message" )
    ( "create,c", "create" )
    ( "size,s", po::value< size_t >( &pool_size )->default_value( PMEMBLK_MIN_POOL ), "pool size" )
    ( "filename,f", po::value< std::string >( &filename )->default_value( "/dev/dax0.0" ), "filename" )
    ( "append,a", po::value< std::string >( &new_value ), "append" )
    ( "list,l", "list" );
  po::variables_map vm;
  po::store( po::parse_command_line( argc, argv, desc ), vm );
  po::notify( vm );
  if( vm.count( "help" ) ) {
    std::cout << desc << std::endl;
    return 0;
  }
  size_t mapped_length = 0u;
  int is_pmem = 0;
  fs::path path( filename );
  bool device_dax = false;
  size_t file_size = 0u;
  bool create = vm.count( "create" );
  if( fs::exists( path ) ) {
    device_dax = is_special_file( path );
    if( !device_dax ) file_size = fs::file_size( path );
    else file_size = 0;
  }
  else {
    file_size = pool_size;
    create = true;
  }
  constexpr size_t block_size = 1024;
  PMEMblkpool *raw_pool = create ?
    pmemblk_create( filename.c_str(), block_size, file_size, 0666 ) :
    pmemblk_open( filename.c_str(), block_size );
  if( !raw_pool ) {
    std::cerr << filename << ':' << strerror( errno ) << std::endl;
    return 1;
  }
  std::unique_ptr< PMEMblkpool, close_pmemblk > pool( raw_pool );
  const size_t block_count = pmemblk_nblock( pool.get() );
  if( create ) {
    const char buffer[ block_size ] = { 0 };
    for( size_t i = 0; i != block_count; ++i ) {
      pmemblk_write( pool.get(), buffer, i );
      if( i % ( block_count / 10 ) == 0 )
        std::cout << 100 * i / block_count << "%" << std::endl;
    }
  }
  if( !new_value.empty() ) {
    char buffer[ block_size ];
    for( size_t i = 0; i != block_count; ++i ) {
      pmemblk_read( pool.get(), buffer, i );
      if( buffer[ 0 ] == '\0' ) {
        new_value.resize( block_size - 1 );
        std::copy( new_value.begin(), new_value.end(), buffer );
	buffer[ new_value.size() ] = '\0';
        pmemblk_write( pool.get(), buffer, i );
	break;
      }
    }
  }
  if( vm.count( "list" ) ) {
    char buffer[ block_size ];
    for( size_t i = 0; i != block_count; ++i ) {
      pmemblk_read( pool.get(), buffer, i );
      if( buffer[ 0 ] == '\0' ) break;
      std::cout << buffer << std::endl;
    }
  }
}


text:
#include "controller.h"

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

Controller::Controller(int device_index):
  _joystick(SDL_JoystickOpen(device_index), &SDL_JoystickClose)
{
  if(!_joystick)
    throw std::runtime_error(std::string("Failed to create joystick: ") + SDL_GetError());

  BOOST_LOG_TRIVIAL(info) << "Loaded joystick " << SDL_JoystickName(_joystick.get());
}

void Controller::update()
{
  Sint16 view_x = SDL_JoystickGetAxis(_joystick.get(), 0);
  Sint16 view_y = SDL_JoystickGetAxis(_joystick.get(), 1);
  _viewSignal.emit(glm::vec2(normalize(view_x), normalize(view_y)));

  Sint16 pos_x = SDL_JoystickGetAxis(_joystick.get(), 4);
  Sint16 pos_y = SDL_JoystickGetAxis(_joystick.get(), 3);
  _positionSignal.emit(glm::vec2(normalize(pos_x), normalize(pos_y)));
}

Signal<glm::vec2> & Controller::onViewChange()
{
  return _viewSignal;
}

Signal<glm::vec2> & Controller::onPositionChange()
{
  return _positionSignal;
}

float Controller::normalize(Sint16 value) const
{
  if(std::abs(value) > 600)
  {
    return float(value - 600) / 32768.0;
  }
  else
    return 0.0f;
}

max_stars_repo_name: smallduckinette/dino

max_issues_repo_name: smallduckinette/dino

max_forks_repo_name: smallduckinette/dino


text:
/*
 * #%L
 * %%
 * Copyright (C) 2018 BMW Car IT GmbH
 * %%
 * 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.
 * #L%
 */
#include <sstream>

#include <boost/format.hpp>

#include "mococrw/bio.h"
#include "mococrw/key.h"
#include "mococrw/error.h"

#include "mococrw/openssl_wrap.h"

namespace {
void ensureEccCurveSupported(mococrw::openssl::ellipticCurveNid nid)
{
    if (nid == mococrw::openssl::ellipticCurveNid::Ed448
            || nid == mococrw::openssl::ellipticCurveNid::Ed25519)
    {
        throw mococrw::MoCOCrWException("The given curve is not supported. Ed448 and Ed25519 are not supported");
    }
}
}

namespace mococrw
{
using namespace openssl;
AsymmetricKey::KeyTypes AsymmetricKey::getType() const {
    switch(openssl::_EVP_PKEY_type(_key.get())) {
        case EVP_PKEY_RSA:
            return KeyTypes::RSA;
        case EVP_PKEY_EC:
            return KeyTypes::ECC;
        case EVP_PKEY_ED25519:
        case EVP_PKEY_ED448:
            return KeyTypes::ECC_ED;
        default:
            throw MoCOCrWException("Unknown Key Type");
    }
}

AsymmetricKeypair AsymmetricKeypair::generate()
{
    RSASpec defaultSpec{};
    return generate(defaultSpec);
}

AsymmetricKeypair AsymmetricKeypair::generateRSA()
{
    RSASpec defaultSpec{};
    return generate(defaultSpec);
}

AsymmetricKeypair AsymmetricKeypair::generateECC()
{
    ECCSpec defaultSpec{};
    return generate(defaultSpec);
}

AsymmetricKeypair AsymmetricKeypair::generateEd448() {
    ECCSpec spec{ellipticCurveNid::Ed448};
    return generate(spec);
}

AsymmetricKeypair AsymmetricKeypair::generateEd25519() {
    ECCSpec spec{ellipticCurveNid::Ed25519};
    return generate(spec);
}

AsymmetricKeypair AsymmetricKeypair::generate(const AsymmetricKey::Spec &keySpec)
{
    return AsymmetricKeypair{keySpec.generate()};
}

std::string AsymmetricPublicKey::publicKeyToPem() const
{
    BioObject bio{BioObject::Types::MEM};
    _PEM_write_bio_PUBKEY(bio.internal(), _key.internal().get());
    return bio.flushToString();
}

AsymmetricPublicKey AsymmetricPublicKey::readPublicKeyFromPEM(const std::string& pem)
{
    BioObject bio{BioObject::Types::MEM};
    bio.write(pem);
    auto key = _PEM_read_bio_PUBKEY(bio.internal());
    return AsymmetricPublicKey{std::move(key)};
}

AsymmetricPublicKey AsymmetricPublicKey::fromECPoint(const std::shared_ptr<ECCSpec> keySpec,
                                                     const std::vector<uint8_t> &point)
{
    ensureEccCurveSupported(keySpec->curve());

    SSL_EC_KEY_Ptr ec_key = _EC_KEY_oct2key(static_cast<int>(keySpec.get()->curve()), point);
    SSL_EVP_PKEY_Ptr evp_key(_EVP_PKEY_new());
    /* As set1 is incrementing the internal ref count, we can and need to invoke the destructor of ec_key here */
    _EVP_PKEY_set1_EC_KEY(evp_key.get(), ec_key.get());

    return AsymmetricPublicKey{std::move(evp_key)};
}

std::vector<uint8_t> AsymmetricPublicKey::toECPoint(EllipticCurvePointConversionForm form)
{
    if (getType() != AsymmetricKey::KeyTypes::ECC) {
        throw MoCOCrWException("The function toECPoint can only be invoked for EC keys.");
    }
    std::shared_ptr<AsymmetricKey::Spec> keySpec = getKeySpec();
    auto spec = std::dynamic_pointer_cast<ECCSpec>(keySpec);
    if (!spec) {
        /* this is very unlikely as we are already checking if the key type is ECC */
        throw MoCOCrWException("Failure downcasting from AsymmetricKey::Spec to ECCSpec.");
    }
    ensureEccCurveSupported(spec->curve());

    return _EC_KEY_key2buf(internal(), static_cast<point_conversion_form_t>(form));
}

size_t AsymmetricPublicKey::getECOctetLength(openssl::EllipticCurvePointConversionForm form)
{
    if (getType() != AsymmetricKey::KeyTypes::ECC) {
        throw MoCOCrWException("The function getECOctetLength can only be invoked for EC keys.");
    }

    // See SEC1 section 2.3.3 Elliptic-Curve-Point-to-Octet-String Conversion.
    // Length is ceil((log2(q))/8)+1 for compressed form and 2*ceil((log2(q))/8)+1 for uncompressed form
    // where q is the field size which is NOT necessarily the same as key size as the latter can be smaller.
    const EC_GROUP *group = _EC_KEY_get0_group(_EVP_PKEY_get0_EC_KEY(internal()));
    unsigned int field_size = _EC_GROUP_get_degree(group);
    unsigned int field_size_bytes = (field_size + 7) / 8;
    size_t enc_len_bytes =
        form == openssl::EllipticCurvePointConversionForm::compressed ? 1 + field_size_bytes : 1 + 2 * field_size_bytes;
    return enc_len_bytes;
}

std::string AsymmetricKeypair::privateKeyToPem(const std::string& pwd) const
{
    BioObject bio{BioObject::Types::MEM};
    const EVP_CIPHER *pkey_cipher = nullptr;
    if (pwd.size() > 0) {
        // only set a cipher if we do want to set a password
        pkey_cipher = _EVP_aes_256_cbc();
    }
    _PEM_write_bio_PKCS8PrivateKey(bio.internal(),
                                   _key.internal().get(),
                                   pkey_cipher,
                                   pwd);
    return bio.flushToString();
}

// In OpenSSL, private keys are the same as keypairs, in that they also contain the public key.
AsymmetricKeypair AsymmetricKeypair::readPrivateKeyFromPEM(const std::string& pem,
                                                    const std::string& password)
{
    BioObject bio{BioObject::Types::MEM};
    bio.write(pem);
    auto key = _PEM_read_bio_PrivateKey(bio.internal(), password.c_str());
    return AsymmetricKeypair{std::move(key)};
}

AsymmetricKey RSASpec::generate() const
{
    auto keyCtx = _EVP_PKEY_CTX_new_id(EVP_PKEY_RSA);
    _EVP_PKEY_keygen_init(keyCtx.get());

    _EVP_PKEY_CTX_set_rsa_keygen_bits(keyCtx.get(), _numBits);

    auto pkey = _EVP_PKEY_keygen(keyCtx.get());
    return AsymmetricKey{std::move(pkey)};
}

AsymmetricKey ECCSpec::generate() const {
   SSL_EVP_PKEY_Ptr pkey{nullptr};
   SSL_EVP_PKEY_CTX_Ptr keyCtx{nullptr};
   try {
        /*Setting the correct curve to generate the ECC key*/
        if (_curveNid != ellipticCurveNid::Ed448 && _curveNid != ellipticCurveNid::Ed25519) {
            auto paramCtx = _EVP_PKEY_CTX_new_id(EVP_PKEY_EC);
            _EVP_PKEY_paramgen_init(paramCtx.get());
            _EVP_PKEY_CTX_set_ec_paramgen_curve_nid(paramCtx.get(),
                    static_cast<int>(_curveNid));
            /*Set the curve ans1 flag so that we can save the key to a PEM format and reuse it later*/
            _EVP_PKEY_CTX_set_ec_param_enc(paramCtx.get(), OPENSSL_EC_NAMED_CURVE);
            auto params = _EVP_PKEY_paramgen(paramCtx.get());

            keyCtx = _EVP_PKEY_CTX_new(params.get());
        } else {
            keyCtx = _EVP_PKEY_CTX_new_id(static_cast<int>(_curveNid));
        }

        /*Key Generation*/
        _EVP_PKEY_keygen_init(keyCtx.get());
        pkey = _EVP_PKEY_keygen(keyCtx.get());

   } catch (const OpenSSLException &e) {
        throw MoCOCrWException(e.what());
   }
   return AsymmetricKey{std::move(pkey)};
}

std::unique_ptr<AsymmetricKey::Spec> AsymmetricKey::getKeySpec() const
{
    try {
        switch(getType()) {
            case KeyTypes::ECC:
            {
                const EC_GROUP *group = _EC_KEY_get0_group(_EVP_PKEY_get0_EC_KEY(_key.get()));
                auto nid = static_cast<openssl::ellipticCurveNid>(_EC_GROUP_get_curve_name(group));
                return std::make_unique<ECCSpec>(nid);
            }
            case KeyTypes::ECC_ED:
            {
                auto nid = static_cast<openssl::ellipticCurveNid>(openssl::_EVP_PKEY_type(_key.get()));
                return std::make_unique<ECCSpec>(nid);
            }
            case KeyTypes::RSA:
                return std::make_unique<RSASpec>(getKeySize());
            default:
                throw MoCOCrWException("Key type not supported.");
        }
    }
    catch (const OpenSSLException &e) {
        throw MoCOCrWException(e.what());
    }
}
}

max_stars_repo_name: istepic/MoCOCrW

max_issues_repo_name: istepic/MoCOCrW

max_forks_repo_name: istepic/MoCOCrW


text:
/**
 * Cloud Manager API
 * This API allows access to Cloud Manager programs, pipelines, and environments by an authorized technical account created through the Adobe I/O Console. The base url for this API is https://cloudmanager.adobe.io, e.g. to get the list of programs for an organization, you would make a GET request to https://cloudmanager.adobe.io/api/programs (with the correct set of headers as described below). This swagger file can be downloaded from https://raw.githubusercontent.com/AdobeDocs/cloudmanager-api-docs/master/swagger-specs/api.yaml.
 *
 * The version of the OpenAPI document: 1.0.0
 * Contact: opensource@shinesolutions.com
 *
 * NOTE: This class is auto generated by OpenAPI-Generator 4.3.1-SNAPSHOT.
 * https://openapi-generator.tech
 * Do not edit the class manually.
 */

#include "EnvironmentList__embedded.h"

#include <string>
#include <sstream>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>

using boost::property_tree::ptree;
using boost::property_tree::read_json;
using boost::property_tree::write_json;

namespace org {
namespace openapitools {
namespace server {
namespace model {

EnvironmentList__embedded::EnvironmentList__embedded()
{
}

EnvironmentList__embedded::~EnvironmentList__embedded()
{
}

std::string EnvironmentList__embedded::toJsonString(bool prettyJson)
{
	std::stringstream ss;
	write_json(ss, this->toPropertyTree(), prettyJson);
	return ss.str();
}

void EnvironmentList__embedded::fromJsonString(std::string const& jsonString)
{
	std::stringstream ss(jsonString);
	ptree pt;
	read_json(ss,pt);
	this->fromPropertyTree(pt);
}

ptree EnvironmentList__embedded::toPropertyTree()
{
	ptree pt;
	ptree tmp_node;
	// generate tree for Environments
	if (!m_Environments.empty()) {
		for (const auto &childEntry : m_Environments) {
			ptree Environments_node;
			Environments_node.put("", childEntry);
			tmp_node.push_back(std::make_pair("", Environments_node));
		}
		pt.add_child("environments", tmp_node);
		tmp_node.clear();
	}
	return pt;
}

void EnvironmentList__embedded::fromPropertyTree(ptree const &pt)
{
	ptree tmp_node;
	// push all items of Environments into member vector
	if (pt.get_child_optional("environments")) {
		for (const auto &childTree : pt.get_child("environments")) {
			m_Environments.emplace_back(childTree.second.data());
		}
	}
}

std::vector<std::shared_ptr<Environment>> EnvironmentList__embedded::getEnvironments() const
{
    return m_Environments;
}
void EnvironmentList__embedded::setEnvironments(std::vector<std::shared_ptr<Environment>> value)
{
	m_Environments = value;
}

}
}
}
}

max_stars_repo_name: shinesolutions/cloudmanager-api-clients

max_issues_repo_name: shinesolutions/cloudmanager-api-clients

max_forks_repo_name: shinesolutions/cloudmanager-api-clients


text:
/**
@file

Copyright John Reid 2007, 2013
*/

#include "bio-pch.h"

#include <bio/application.h>
#include <bio/pssm_likelihood_cache.h>
#include <bio/environment.h>
#include <bio/serialisable.h>
USING_BIO_NS;

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

#include <iostream>
using namespace std;

/**
 * Estimates the likelihoods of biobase scores (under a binding model) for all PSSMs.
 */
struct CalculatePssmLikelihoodsApp : Application
{
	int task()
	{
		PssmLikelihoodCache::singleton().populate_from_biobase();

		boost::filesystem::path file(
			BioEnvironment::singleton().get_pssm_likelihoods_cache_file()
		);

		std::cout
			<< "Serialising to "
			<< file._BOOST_FS_NATIVE()
			<< "\n"
			;
		serialise< false >(
			PssmLikelihoodCache::singleton(),
			file);

		return 0;
	}
};

int
main(int argc, char * argv [])
{
	return CalculatePssmLikelihoodsApp().main( argc, argv );
}

max_stars_repo_name: JohnReid/biopsy

max_issues_repo_name: JohnReid/biopsy

max_forks_repo_name: JohnReid/biopsy


text:
#include "examples/Cassie/input_supervisor.h"

#include "drake/multibody/plant/multibody_plant.h"
#include "examples/Cassie/cassie_utils.h"
#include <Eigen/Dense>
#include <gtest/gtest.h>

namespace dairlib {
namespace systems {
namespace {

using Eigen::VectorXd;

// class InputSupervisorTest: public ::testing::Test {};

class InputSupervisorTest : public ::testing::Test {
protected:
  InputSupervisorTest() : plant_(drake::multibody::MultibodyPlant<double>(0.0)) {
    addCassieMultibody(&plant_, nullptr, true /*floating base*/,
                       "examples/Cassie/urdf/cassie_v2.urdf",
                       true /*spring model*/, false /*loop closure*/);
    plant_.Finalize();
    supervisor_ = std::make_unique<InputSupervisor>(
        plant_, 10.0, 0.01, min_consecutive_failures, 20.0);
    context_ = supervisor_->CreateDefaultContext();
    status_output_ = std::make_unique<TimestampedVector<double>>(1);
    command_input_ =
        std::make_unique<TimestampedVector<double>>(plant_.num_actuators());
    state_input_ = std::make_unique<OutputVector<double>>(
        plant_.num_positions(), plant_.num_velocities(),
        plant_.num_actuators());
  }

  drake::multibody::MultibodyPlant<double> plant_;
  const int min_consecutive_failures = 5;
  std::unique_ptr<InputSupervisor> supervisor_;
  std::unique_ptr<TimestampedVector<double>> status_output_;
  std::unique_ptr<TimestampedVector<double>> command_input_;
  std::unique_ptr<OutputVector<double>> state_input_;
  std::unique_ptr<drake::systems::Context<double>> context_;
};

TEST_F(InputSupervisorTest, StatusBitTest) {
  double output_bit;
  VectorXd zero_input = VectorXd::Zero(plant_.num_actuators());
  command_input_->get_mutable_value() = zero_input;
  context_->FixInputPort(0, *command_input_);

  supervisor_->SetStatus(*context_, status_output_.get());
  output_bit = status_output_->get_value()[0];
  EXPECT_EQ(output_bit, 0);

  VectorXd large_input = 100 * VectorXd::Ones(plant_.num_actuators());
  command_input_->get_mutable_value() = large_input;
  context_->FixInputPort(0, *command_input_);
  supervisor_->SetStatus(*context_, status_output_.get());
  output_bit = status_output_->get_value()[0];
  EXPECT_EQ(output_bit, 2);

  VectorXd high_velocities = 100 * VectorXd::Ones(plant_.num_velocities());
  state_input_->SetVelocities(high_velocities);
  context_->FixInputPort(1, *state_input_);
  supervisor_->UpdateErrorFlag(*context_,
                               &context_->get_mutable_discrete_state());
  supervisor_->SetStatus(*context_, status_output_.get());
  output_bit = status_output_->get_value()[0];
  EXPECT_EQ(output_bit, 3);

  // Trigger the min_consecutive_failures
  for (int i = 0; i < min_consecutive_failures; ++i) {
    supervisor_->UpdateErrorFlag(*context_,
                                 &context_->get_mutable_discrete_state());
  }
  supervisor_->SetStatus(*context_, status_output_.get());
  output_bit = status_output_->get_value()[0];
  EXPECT_EQ(output_bit, 7);
}

} // namespace
} // namespace systems
} // namespace dairlib

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

ext: cc