text:
//  (C) Copyright Matt Borland 2022.
//  Use, modification and distribution are subject to the
//  Boost Software License, Version 1.0. (See accompanying file
//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#ifndef BOOST_MATH_CCMATH_FDIM_HPP
#define BOOST_MATH_CCMATH_FDIM_HPP

#include <cmath>
#include <limits>
#include <type_traits>
#include <boost/math/tools/is_constant_evaluated.hpp>
#include <boost/math/ccmath/isnan.hpp>

namespace boost::math::ccmath {

namespace detail {

template <typename T>
inline constexpr T fdim_impl(const T x, const T y) noexcept
{
    if (x <= y)
    {
        return 0;
    }
    else if ((y < 0) && (x > (std::numeric_limits<T>::max)() + y))
    {
        return std::numeric_limits<T>::infinity();
    }
    else
    {
        return x - y;
    }
}

} // Namespace detail

template <typename Real, std::enable_if_t<!std::is_integral_v<Real>, bool> = true>
inline constexpr Real fdim(Real x, Real y) noexcept
{
    if (BOOST_MATH_IS_CONSTANT_EVALUATED(x))
    {
        return boost::math::ccmath::isnan(x) ? std::numeric_limits<Real>::quiet_NaN() :
               boost::math::ccmath::isnan(y) ? std::numeric_limits<Real>::quiet_NaN() :
               boost::math::ccmath::detail::fdim_impl(x, y);
    }
    else
    {
        using std::fdim;
        return fdim(x, y);
    }
}

template <typename T1, typename T2>
inline constexpr auto fdim(T1 x, T2 y) noexcept
{
    if (BOOST_MATH_IS_CONSTANT_EVALUATED(x))
    {
        // If the type is an integer (e.g. epsilon == 0) then set the epsilon value to 1 so that type is at a minimum
        // cast to double
        constexpr auto T1p = std::numeric_limits<T1>::epsilon() > 0 ? std::numeric_limits<T1>::epsilon() : 1;
        constexpr auto T2p = std::numeric_limits<T2>::epsilon() > 0 ? std::numeric_limits<T2>::epsilon() : 1;

        using promoted_type =
                              #ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS
                              std::conditional_t<T1p <= LDBL_EPSILON && T1p <= T2p, T1,
                              std::conditional_t<T2p <= LDBL_EPSILON && T2p <= T1p, T2,
                              #endif
                              std::conditional_t<T1p <= DBL_EPSILON && T1p <= T2p, T1,
                              std::conditional_t<T2p <= DBL_EPSILON && T2p <= T1p, T2, double
                              #ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS
                              >>>>;
                              #else
                              >>;
                              #endif

        return boost::math::ccmath::fdim(promoted_type(x), promoted_type(y));
    }
    else
    {
        using std::fdim;
        return fdim(x, y);
    }
}

inline constexpr float fdimf(float x, float y) noexcept
{
    return boost::math::ccmath::fdim(x, y);
}

#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS
inline constexpr long double fdiml(long double x, long double y) noexcept
{
    return boost::math::ccmath::fdim(x, y);
}
#endif

} // Namespace boost::math::ccmath

#endif // BOOST_MATH_CCMATH_FDIM_HPP


text:
#ifndef __SERIALSERVER_H__
#define __SERIALSERVER_H__

#include <ros/ros.h>
#include <boost/thread.hpp>
#include <string.h>
#include <sensor_msgs/Joy.h>
#include <nav_msgs/Odometry.h>
#include <sensor_msgs/CompressedImage.h>
#include <sensor_msgs/PointCloud2.h>
#include <geometry_msgs/TransformStamped.h>
#include <rssi_get/Nvip_status.h>
#include <libelium_waspmote_gas_node/GasMeasure.h>
#include <siar_driver/SiarStatus.h>
#include <std_msgs/UInt32.h>
#include <std_msgs/UInt8.h>
#include <std_msgs/Bool.h>
#include <std_msgs/Float32.h>
#include "cycle.hpp"
#include "udp_manager.hpp"

#include <dynamic_reconfigure/IntParameter.h>
#include <dynamic_reconfigure/Reconfigure.h>
#include <dynamic_reconfigure/Config.h>

#include <boost/asio.hpp>
#include <boost/array.hpp>

using boost::asio::ip::udp;

class UDPServer : public UDPManager
{
private:

  // ROS params
  double odomRate, imageRate, depthRate, siar_status_rate, rssiRate, point_rate;
  std::string odomTopic, imageTopic, imageTopic_2, imageTopic_3, imageTopic_4, imageTopic_5;
  std::string inspectionImageTopic1, inspectionImageTopic2;
  std::string depthTopic, depthTopic_2, depthTopic_3, depthTopic_4, depthTopic_5;
  std::string allCamerasTopic, publishDepthTopic, joyTopic, rssi_topic, point_topic;
  std::string siar_status_topic, slowTopic, geo_tf_topic;
  std::string camera_1, camera_2, camera_3, camera_4, camera_5, inspection_camera1, inspection_camera2;
  std::string posTopic, widthTopic;
  int jpeg_quality, min_quality;
  bool quality_set, quality_set_2;
  std::string thermal_camera_topic;
  u_int8_t comm_mode;

  // Subscriber rates
  Cycle odomCycle, imageCycle, imageCycle_2, imageCycle_3, imageCycle_4, imageCycle_5;
  Cycle inspectionCycle_1, inspectionCycle_2, thermalCycle;
  Cycle depthCycle, depthCycle_2, rssiCycle, depthCycle_3, depthCycle_4, depthCycle_5;
  Cycle siarStatusCycle, pointCycle;

  // Publishers and subscribers
  ros::Publisher publish_depth_pub, all_cameras_pub, joy_pub, slow_pub, elec_x_pos_pub, width_pos_pub;
  ros::Subscriber odom_sub, image_sub, image_sub_2, image_sub_3, image_sub_4, image_sub_5;
  ros::Subscriber inspection_sub_1, inspection_sub_2, thermal_sub;
  ros::Subscriber depth_sub, depth_sub_2, rssi_sub, gas_sub, depth_sub_3, depth_sub_4, depth_sub_5, geo_tf_sub;
  ros::Subscriber  siar_status_sub, point_sub;
  ros::Subscriber arm_mode_sub, arm_torque_sub;
  ros::NodeHandle nh;

public:

  // Default constructor
  UDPServer():UDPManager()
  {
    comm_mode = 0;
    ROS_INFO("In UDPServer::UDPServer");
    // Read node parameters
    ros::NodeHandle lnh("~");
    if(!lnh.getParam("odom_topic", odomTopic))
      odomTopic = "odom";
    if(!lnh.getParam("odom_rate", odomRate))
      odomRate = 5.0; // At first the odometry measures are discraded
    if(!lnh.getParam("joy_topic", joyTopic))
      joyTopic = "/joy";
    if(!lnh.getParam("width_topic", widthTopic))
      widthTopic = "/width_pos";
    if(!lnh.getParam("pos_topic", posTopic))
      posTopic = "/set_x_pos";
    if(!lnh.getParam("camera_1", camera_1))
      camera_1 = "/front";
    if(!lnh.getParam("camera_3", camera_3))
      camera_3 = "/front_left_web";
    if(!lnh.getParam("camera_4", camera_4))
      camera_4 = "/front_right_web";
    if(!lnh.getParam("camera_5", camera_5))
      camera_5 = "/up_web";
    if(!lnh.getParam("image_rate", imageRate))
      imageRate = 5.0;
    if(!lnh.getParam("depth_rate", depthRate))
      depthRate = 4.0;
    if(!lnh.getParam("camera_2", camera_2))
      camera_2 = "/back";
    if(!lnh.getParam("jpeg_quality", jpeg_quality))
      jpeg_quality = 60;
    if(!lnh.getParam("port", port))
      port = 16000;
    if (!lnh.getParam("rssi_topic", rssi_topic))
      rssi_topic = "/rssi_nvip_2400";
    if (!lnh.getParam("rssi_rate", rssiRate))
      rssiRate = 1.0;
    if (!lnh.getParam("siar_status_topic", siar_status_topic))
      siar_status_topic = "/siar_status";
    if (!lnh.getParam("siar_status_rate", siar_status_rate))
      siar_status_rate = 5;
    if (!lnh.getParam("point_cloud_topic", point_topic))
      point_topic = "/rgbd_odom_node/point_cloud";
    if (!lnh.getParam("point_cloud_rate", point_rate))
      point_rate = 1.0;
    if (!lnh.getParam("inspection_camera_1", inspection_camera1))
      inspection_camera1 = "/inspection1_cam";
    if (!lnh.getParam("inspection_camera_2", inspection_camera2))
      inspection_camera2 = "/inspection2_cam";
    if (!lnh.getParam("thermal_camera_topic", thermal_camera_topic))
      thermal_camera_topic = "/flip_image/compressed";

    // Set the image topics
    imageTopic = camera_1 + "/rgb/image_raw/compressed";
    imageTopic_2 = camera_2 + "/rgb/image_raw/compressed";
    imageTopic_3 = camera_3 + "/rgb/image_raw/compressed";
    imageTopic_4 = camera_4 + "/rgb/image_raw/compressed";
    imageTopic_5 = camera_5 + "/rgb/image_raw/compressed";
    depthTopic = camera_1 + "/depth_registered/image_raw/compressedDepth";
    depthTopic_2 = camera_2 + "/depth_registered/image_raw/compressedDepth";
    depthTopic_3 = camera_3 + "/depth_registered/image_raw/compressedDepth";
    depthTopic_4 = camera_4 + "/depth_registered/image_raw/compressedDepth";
    depthTopic_5 = camera_5 + "/depth_registered/image_raw/compressedDepth";
    geo_tf_topic = "/rgbd_odom/transform";

    inspectionImageTopic1 = inspection_camera1 + "/image_raw/compressed";
    inspectionImageTopic2 = inspection_camera2 + "/image_raw/compressed";

    allCamerasTopic = "/all_cameras";
    publishDepthTopic = "/publish_depth";
    slowTopic = "/slow_motion";

    gasTopic = "/gas_info";

    // Create publishers
    publish_depth_pub = nh.advertise<std_msgs::Bool>(publishDepthTopic, 1);
    all_cameras_pub = nh.advertise<std_msgs::Bool>(allCamerasTopic, 1);
    slow_pub = nh.advertise<std_msgs::Bool>(slowTopic, 1);
    joy_pub = nh.advertise<sensor_msgs::Joy>(joyTopic, 1);
    elec_x_pos_pub = nh.advertise<std_msgs::Float32>(posTopic, 1);
    width_pos_pub = nh.advertise<std_msgs::Float32>(widthTopic, 1);

    // Create subscribers and setup rates
    odom_sub = nh.subscribe(odomTopic, 1, &UDPServer::odomCallback, this);
    odomCycle.init(odomRate);
    image_sub = nh.subscribe(imageTopic, 1, &UDPServer::imageCallback, this);
    imageCycle.init(imageRate);
    image_sub_2 = nh.subscribe(imageTopic_2, 1, &UDPServer::imageCallback_2, this);
    imageCycle_2.init(imageRate);
    image_sub_3 = nh.subscribe(imageTopic_3, 1, &UDPServer::imageCallback_3, this);
    imageCycle_3.init(imageRate);
    image_sub_4 = nh.subscribe(imageTopic_4, 1, &UDPServer::imageCallback_4, this);
    imageCycle_4.init(imageRate);
    image_sub_5 = nh.subscribe(imageTopic_5, 1, &UDPServer::imageCallback_5, this);
    imageCycle_5.init(imageRate);
    inspection_sub_1 = nh.subscribe(inspectionImageTopic1, 1, &UDPServer::inspectionCallback_1, this);
    inspectionCycle_1.init(imageRate);
    inspection_sub_2 = nh.subscribe(inspectionImageTopic2, 1, &UDPServer::inspectionCallback_2, this);
    inspectionCycle_2.init(imageRate);
    thermal_sub = nh.subscribe(thermal_camera_topic, 1, &UDPServer::thermalCallback, this);
    thermalCycle.init(imageRate);
    depth_sub = nh.subscribe(depthTopic, 1, &UDPServer::depthCallback, this);
    depthCycle.init(depthRate);
    depth_sub_2 = nh.subscribe(depthTopic_2, 1, &UDPServer::depthCallback_2, this);
    depthCycle_2.init(depthRate);
    depth_sub_3 = nh.subscribe(depthTopic_3, 1, &UDPServer::depthCallback_3, this);
    depthCycle_3.init(depthRate);
    depth_sub_4 = nh.subscribe(depthTopic_4, 1, &UDPServer::depthCallback_4, this);
    depthCycle_4.init(depthRate);
    depth_sub_5 = nh.subscribe(depthTopic_5, 1, &UDPServer::depthCallback_5, this);
    depthCycle_5.init(depthRate);
    rssi_sub = nh.subscribe(rssi_topic, 1, &UDPServer::rssiCallback, this);
    rssiCycle.init(rssiRate);
    gas_sub = nh.subscribe(gasTopic, 1, &UDPServer::gasCallback, this);
    siar_status_sub = nh.subscribe(siar_status_topic, 1, &UDPServer::siarStatusCallback, this);
    siarStatusCycle.init(siar_status_rate);
    point_sub = nh.subscribe(point_topic, 1, &UDPServer::pointCallback, this);
    pointCycle.init(point_rate);
    geo_tf_sub = nh.subscribe(geo_tf_topic, 1, &UDPServer::tfCallback, this);

    arm_torque_sub = nh.subscribe("/arm_torque", 1, &UDPServer::armTorqueCallback, this);
    arm_mode_sub = nh.subscribe("/arm_mode", 1, &UDPServer::armModeCallback, this);

    // Set default compression quality
    int i = 0;

    quality_set = setJPEGQuality(jpeg_quality, imageTopic);
    quality_set_2 = setJPEGQuality(jpeg_quality, imageTopic_2);
    setJPEGQuality(jpeg_quality, inspectionImageTopic1);

    // Init the UDP session
    init();
  }

  ~UDPServer()
  {
    endSession();
  }

  // Create the socket and wait for the client to connect
  virtual bool startSession() {
    try
    {
      std::vector<uint8_t> buffer;
      buffer.resize(max_udp_length);
      socket_ptr.reset( new udp::socket(io_service, udp::endpoint(udp::v4(), port)) );

      boost::system::error_code error;
      ROS_INFO("Waiting for the client");

      std::string s;

      while (s != start) {
        size_t len = socket_ptr->receive_from(boost::asio::buffer(buffer, max_udp_length), remote_endpoint, 0, error);

        if (len == start.size()) {

          s.resize(len);
          for (size_t i = 0; i < len; i++) {
            s.at(i) = buffer[i];
          }
          ROS_INFO("About to start a session. Received: %s", s.c_str());
        }
      }
      ROS_INFO("Client found!");

      if (error && error != boost::asio::error::message_size)
        throw boost::system::system_error(error);
    }
    catch (std::exception &e) {
      ROS_INFO("Exception in UPDServer::startSession(). Content: %s", e.what());
      return false;
    }
    return true;
  }

protected:
  void odomCallback(const nav_msgs::Odometry::ConstPtr& msg)
  {
    // Check if it is time for sending new data
    if(!odomCycle.newCycle())
      return;

    // Serialize msg and write in serial port
    serializeWrite<nav_msgs::Odometry>(odomTopic, *msg);
  }

  void imageCallback(const sensor_msgs::CompressedImage::ConstPtr& msg)
  {
    // Check if it is time for sending new data
    if(!imageCycle.newCycle())
    {
      return;
    }

    // Check for quality set
    // Serialize msg and write over UDP
    if (!quality_set)
      quality_set = setJPEGQuality(jpeg_quality, imageTopic);
    else
      serializeWrite<sensor_msgs::CompressedImage>(imageTopic, *msg);
  }

  void imageCallback_2(const sensor_msgs::CompressedImage::ConstPtr& msg)
  {
    // Check if it is time for sending new data
    if(!imageCycle_2.newCycle() && comm_mode > 1)
    {
      return;
    }
    // Check for quality set
    // Serialize msg and write over UDP
    if (!quality_set_2)
      quality_set_2 = setJPEGQuality(jpeg_quality, imageTopic_2);
    else
      serializeWrite<sensor_msgs::CompressedImage>(imageTopic_2, *msg);
  }

  void imageCallback_3(const sensor_msgs::CompressedImage::ConstPtr& msg)
  {
    // Check if it is time for sending new data
    if(!imageCycle_3.newCycle() || comm_mode > 0)
    {
      return;
    }

    // Serialize msg and write over UDP
    serializeWrite<sensor_msgs::CompressedImage>(imageTopic_3, *msg);
  }

  void imageCallback_4(const sensor_msgs::CompressedImage::ConstPtr& msg)
  {
    // Check if it is time for sending new data
    if(!imageCycle_4.newCycle() || comm_mode > 0)
    {
      return;
    }
    // Serialize msg and write over UDP
    serializeWrite<sensor_msgs::CompressedImage>(imageTopic_4, *msg);
  }

  void imageCallback_5(const sensor_msgs::CompressedImage::ConstPtr& msg)
  {
    // Check if it is time for sending new data
    if(!imageCycle_5.newCycle() || comm_mode > 0)
    {
      return;
    }
    // Serialize msg and write over UDP
    serializeWrite<sensor_msgs::CompressedImage>(imageTopic_5, *msg);
  }

  void inspectionCallback_1(const sensor_msgs::CompressedImage::ConstPtr& msg)
  {
    // Check if it is time for sending new data
    if(!inspectionCycle_1.newCycle() || comm_mode > 1)
    {
      return;
    }

    // Serialize msg and write over UDP
    serializeWrite<sensor_msgs::CompressedImage>(inspectionImageTopic1, *msg);
  }

  void inspectionCallback_2(const sensor_msgs::CompressedImage::ConstPtr& msg)
  {
    // Check if it is time for sending new data
    if(!inspectionCycle_2.newCycle() || comm_mode > 1)
    {
      return;
    }
    // Serialize msg and write over UDP
    serializeWrite<sensor_msgs::CompressedImage>(inspectionImageTopic2, *msg);
  }

  void thermalCallback(const sensor_msgs::CompressedImage::ConstPtr &msg) {
    // Check if the cycle has elapsed
    if (!thermalCycle.newCycle())
      return;

    serializeWrite<sensor_msgs::CompressedImage>(thermal_camera_topic, *msg);
  }

  void depthCallback(const sensor_msgs::CompressedImage::ConstPtr& msg)
  {
    // Check if it is time for sending new data
    if(!depthCycle.newCycle())
    {
      return;
    }
    // Serialize msg and write over UDP
    serializeWrite<sensor_msgs::CompressedImage>(depthTopic, *msg);
  }

  void depthCallback_2(const sensor_msgs::CompressedImage::ConstPtr& msg)
  {
    // Check if it is time for sending new data
    if(!depthCycle_2.newCycle())
    {
      return;
    }
    // Serialize msg and write over UDP
    serializeWrite<sensor_msgs::CompressedImage>(depthTopic_2, *msg);
  }

  void depthCallback_3(const sensor_msgs::CompressedImage::ConstPtr& msg)
  {
    // Check if it is time for sending new data
    if(!depthCycle_3.newCycle())
    {
      return;
    }
    // Serialize msg and write over UDP
    serializeWrite<sensor_msgs::CompressedImage>(depthTopic_3, *msg);
  }

  void depthCallback_4(const sensor_msgs::CompressedImage::ConstPtr& msg)
  {
    // Check if it is time for sending new data
    if(!depthCycle_4.newCycle())
    {
      return;
    }
    // Serialize msg and write over UDP
    serializeWrite<sensor_msgs::CompressedImage>(depthTopic_4, *msg);
  }

  void depthCallback_5(const sensor_msgs::CompressedImage::ConstPtr& msg)
  {
    // Check if it is time for sending new data
    if(!depthCycle_5.newCycle())
    {
      return;
    }
    // Serialize msg and write over UDP
    serializeWrite<sensor_msgs::CompressedImage>(depthTopic_5, *msg);
  }

  void rssiCallback(const rssi_get::Nvip_status::ConstPtr& msg)
  {
    // Check if it is time for sending new data
    if(!rssiCycle.newCycle())
    {
      return;
    }
    // Check for quality set
    // Serialize msg and write over UDP
    serializeWrite<rssi_get::Nvip_status>(rssi_topic, *msg);
  }

  void gasCallback(const libelium_waspmote_gas_node::GasMeasure::ConstPtr &msg)
  {
    serializeWrite<libelium_waspmote_gas_node::GasMeasure>(gasTopic, *msg);
  }

  void siarStatusCallback(const siar_driver::SiarStatus::ConstPtr& msg)
  {
    // Check if it is time for sending new data
    if(!siarStatusCycle.newCycle())
    {
      return;
    }
    // Check for quality set
    // Serialize msg and write over UDP
    serializeWrite<siar_driver::SiarStatus>(siar_status_topic, *msg);
  }

  void tfCallback(const geometry_msgs::TransformStamped::ConstPtr& msg)
  {
    serializeWrite<geometry_msgs::TransformStamped>(geo_tf_topic, *msg);

  }

  void readThread()
  {
    std::string topic;
    std::vector<uint8_t> buffer;
    buffer.reserve(max_length);

    while(ros::ok() && running)
    {
      // Read one message from serial port
      topic.clear();
      int result = getChunk(topic, buffer);
      if(result < 0) {
        if (result == -3)
          running = false;
        continue;
      }

      // Deserialize and publish
      if (topic == allCamerasTopic) {
	deserializePublish<std_msgs::Bool>(buffer.data(), buffer.size(), all_cameras_pub);
      }
      if (topic == publishDepthTopic) {
	deserializePublish<std_msgs::Bool>(buffer.data(), buffer.size(), publish_depth_pub);
      }
      if (topic == joyTopic) {
        deserializePublish<sensor_msgs::Joy>(buffer.data(), buffer.size(), joy_pub);
      }
      if (topic == slowTopic) {
        deserializePublish<std_msgs::Bool>(buffer.data(), buffer.size(), slow_pub);
      }
      if (topic == posTopic) {
        deserializePublish<std_msgs::Float32>(buffer.data(), buffer.size(), elec_x_pos_pub);
      }
      if (topic == widthTopic) {
        deserializePublish<std_msgs::Float32>(buffer.data(), buffer.size(), width_pos_pub);
      }
      if (topic == "comms_mode") {
	// Handle the arm_mode
	std_msgs::UInt8  msg;
	try
	{
	  ros::serialization::IStream stream(buffer.data(), buffer.size());
	  ros::serialization::Serializer<std_msgs::UInt8>::read(stream, msg);
	  comm_mode = msg.data;
	  ROS_INFO("Received a new comm mode: %d", (int)msg.data);
          if (msg.data > 1)
            setJPEGQuality(jpeg_quality*0.5, imageTopic);
          else
            setJPEGQuality(jpeg_quality, imageTopic);

	}
	catch (std::exception &e)
	{
	}

      }
    }
  }

  void pointCallback(const sensor_msgs::PointCloud2::ConstPtr& msg)
  {
    // Check if it is time for sending new data
    if(!pointCycle.newCycle())
      return;

    // Serialize msg and write in serial port
    serializeWrite<sensor_msgs::PointCloud2>(point_topic, *msg);
  }

  void armModeCallback(const std_msgs::Bool::ConstPtr &msg) {
    serializeWrite<std_msgs::Bool>("/arm_mode", *msg);
  }
  void armTorqueCallback(const std_msgs::UInt8::ConstPtr &msg) {
    serializeWrite<std_msgs::UInt8>("/arm_torque", *msg);
  }

  bool setJPEGQuality(int quality, const std::string image_topic) {
    dynamic_reconfigure::ReconfigureRequest srv_req;
    dynamic_reconfigure::ReconfigureResponse srv_resp;
    dynamic_reconfigure::IntParameter param;
    dynamic_reconfigure::Config conf;
    param.name = "jpeg_quality";
    param.value = quality;
    conf.ints.push_back(param);
    srv_req.config = conf;

    std::string service = image_topic + "/set_parameters";
    if (!ros::service::call(service, srv_req, srv_resp)) {
      ROS_ERROR("Could not call the service %s reconfigure to %d", service.c_str(), quality);
      return false;
    }
    ROS_INFO("New quality %d", jpeg_quality);
    return true;
  }
  const char* gasTopic;
};

#endif

ext: hpp


text:
//Copyright (c) 2006-2008 Emil Dotchevski and Reverge Studios, Inc.

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

#ifndef UUID_78CC85B2914F11DC8F47B48E55D89593
#define UUID_78CC85B2914F11DC8F47B48E55D89593

#include <boost/exception/exception.hpp>
#include <boost/exception/detail/cloning_base.hpp>
#include <boost/detail/atomic_count.hpp>
#include <boost/assert.hpp>
#include <new>

namespace
boost
    {
    namespace
    exception_detail
        {
        class
        clone_base:
            public counted_base
            {
            public:

            virtual void rethrow() const=0;
            };

        struct
        bad_alloc_impl:
            public clone_base,
            public std::bad_alloc
            {
            void
            add_ref() const
                {
                }

            void
            release() const
                {
                }

            void
            rethrow() const
                {
                throw *this;
                }
            };

        template <class T>
        clone_base * make_clone( T const & );

        template <class T>
        class
        clone_impl:
            public T,
            public cloning_base
            {
            public:

            explicit
            clone_impl( T const & x ):
                T(x)
                {
                if( boost::exception * be1=dynamic_cast<boost::exception *>(this) )
                    if( boost::exception const * be2=dynamic_cast<boost::exception const *>(&x) )
                        *be1 = *be2;
                }

            private:

            clone_base const *
            clone() const
                {
                return make_clone<T>(*this);
                }
            };

        template <class T>
        class
        exception_clone:
            public T,
            public clone_base
            {
            public:

            explicit
            exception_clone( T const & x ):
                T(x),
                count_(0)
                {
                if( boost::exception * be1=dynamic_cast<boost::exception *>(this) )
                    if( boost::exception const * be2=dynamic_cast<boost::exception const *>(&x) )
                        *be1 = *be2;
                }

            private:

            detail::atomic_count mutable count_;

            void
            add_ref() const
                {
                ++count_;
                }

            void
            release() const
                {
                if( !--count_ )
                    delete this;
                }

            void
            rethrow() const
                {
                throw clone_impl<T>(*this);
                }
            };

        template <class T>
        inline
        clone_base *
        make_clone( T const & x )
            {
            try
                {
                return new exception_clone<T>(x);
                }
            catch(
            std::bad_alloc & )
                {
                static bad_alloc_impl bad_alloc;
                return &bad_alloc;
                }
            catch(
            ... )
                {
                BOOST_ASSERT(0);
                return 0;
                }
            }
        }

    template <class T>
    inline
    exception_detail::clone_impl<T>
    enable_current_exception( T const & x )
        {
        return exception_detail::clone_impl<T>(x);
        }
    }

#endif

max_stars_repo_name: jaredhoberock/gotham

max_issues_repo_name: jaredhoberock/gotham

max_forks_repo_name: jaredhoberock/gotham


text:
/* This file is part of the Tomographer project, which is distributed under the
 * terms of the MIT license.
 *
 * The MIT License (MIT)
 *
 * Copyright (c) 2016 ETH Zurich, Institute for Theoretical Physics, Philippe Faist
 * Copyright (c) 2017 Caltech, Institute for Quantum Information and Matter, Philippe Faist
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

#include <cmath>

#include <string>
#include <iostream>
#include <random>

#include <boost/math/constants/constants.hpp>

// definitions for Tomographer test framework -- this must be included before any
// <Eigen/...> or <tomographer/...> header
#include "test_tomographer.h"

#include <tomographer/tools/eigen_assert_exception.h>

// -----------------------------------------------------------------------------
// fixture(s)

// -----------------------------------------------------------------------------
// test suites

BOOST_AUTO_TEST_SUITE(test_tools_eigen_assert_exception)

// test the eigen_assert dynamic functionality
BOOST_AUTO_TEST_CASE(base)
{
  BOOST_CHECK(EigenAssertTest::setting_scope_ptr == NULL);
  {
    //    fprintf(stderr, "entering block...\n");
    EigenAssertTest::setting_scope mysettingvar(true); // eigen_assert() should throw an exception.
    //    fprintf(stderr, "instanciated mysettingvar\n");
    BOOST_CHECK(EigenAssertTest::setting_scope_ptr != NULL);
    BOOST_CHECK(EigenAssertTest::setting_scope_ptr->throws_exception);
    bool pt1 = false;
    bool pt2 = false;
    BOOST_CHECK_THROW(
	pt1 = true;
        eigen_assert( false );
	pt2 = true;
	,
        Tomographer::Tools::EigenAssertException
        );
    BOOST_CHECK(pt1 && !pt2);
    //    fprintf(stderr, "leaving block.\n");
  }
  BOOST_CHECK(EigenAssertTest::setting_scope_ptr == NULL);
}

BOOST_AUTO_TEST_SUITE_END();

ext: cxx

max_stars_repo_name: Tomographer/tomographer

max_issues_repo_name: Tomographer/tomographer

max_forks_repo_name: Tomographer/tomographer


text:
// Copyright (c) 2021 George E. Brown and Rahul Narain
//
// WRAPD uses the MIT License (https://opensource.org/licenses/MIT)
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is furnished
// to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// By George E. Brown (https://www-users.cse.umn.edu/~brow2327/)

#ifndef SRC_MATH_HPP_
#define SRC_MATH_HPP_

#include <Eigen/SparseCholesky>
#include <Eigen/Dense>
#include <Eigen/Sparse>

#include <iostream>
#include <memory>
#include <string>
#include <vector>

namespace wrapd {
namespace math {

using VecX = Eigen::VectorXd;
using RowVecX = Eigen::RowVectorXd;
using VecXi = Eigen::VectorXi;
using MatX = Eigen::MatrixXd;
using MatXi = Eigen::MatrixXi;
using MatX2 = Eigen::MatrixX2d;
using Mat2X = Eigen::Matrix2Xd;
using MatX3 = Eigen::MatrixX3d;
using Mat3X = Eigen::Matrix3Xd;
using SpMat = Eigen::SparseMatrix<double, Eigen::RowMajor>;
using DiagMat = Eigen::DiagonalMatrix<double, Eigen::Dynamic>;
using RowVec3 = Eigen::RowVector3d;
using RowVec4 = Eigen::RowVector4d;

using Triplet = Eigen::Triplet<double>;
using Triplets = std::vector<Triplet>;

using Doubles = std::vector<double>;

using Cholesky = Eigen::SimplicialLDLT< Eigen::SparseMatrix<double>, Eigen::Lower>;

using ConjugateGradient = Eigen::ConjugateGradient<Eigen::SparseMatrix<double>, Eigen::Lower|Eigen::Upper>;

using AlignedBox = Eigen::AlignedBox<double, 3>;

// Singular value decomposition
template <typename TYPE>
using JacobiSVD = Eigen::JacobiSVD<TYPE>;
static constexpr int ComputeFullU = Eigen::ComputeFullU;
static constexpr int ComputeFullV = Eigen::ComputeFullV;

// Mapping between vectors and matrices
template <typename TYPE>
using Map = Eigen::Map<TYPE>;

// Vectors of doubles
template <int DIM>
using Vec = Eigen::Matrix<double, DIM, 1>;
using Vec2 = Vec<2>;
using Vec3 = Vec<3>;
using Vec4 = Vec<4>;
using Vec5 = Vec<5>;
using Vec6 = Vec<6>;
using Vec7 = Vec<7>;
using Vec8 = Vec<8>;
using Vec9 = Vec<9>;
using Vec10 = Vec<10>;
using Vec11 = Vec<11>;
using Vec12 = Vec<12>;

// Vectors of floats
template <int DIM>
using Vecf = Eigen::Matrix<float, DIM, 1>;
using Vec2f = Vecf<2>;
using Vec3f = Vecf<3>;
using Vec4f = Vecf<4>;

// Vectors of integers
template <int DIM>
using Veci = Eigen::Matrix<int, DIM, 1>;
using Vec1i = Veci<1>;
using Vec2i = Veci<2>;
using Vec3i = Veci<3>;
using Vec4i = Veci<4>;

template <int ROWS, int COLS>
using Mat = Eigen::Matrix<double, ROWS, COLS>;

using Mat1x3 = Mat<1, 3>;
using Mat2x2 = Mat<2, 2>;
using Mat2x3 = Mat<2, 3>;
using Mat3x2 = Mat<3, 2>;
using Mat3x3 = Mat<3, 3>;
using Mat3x4 = Mat<3, 4>;
using Mat3x9 = Mat<3, 9>;
using Mat3x12 = Mat<3, 12>;
using Mat4x3 = Mat<4, 3>;
using Mat4x4 = Mat<4, 4>;
using Mat4x6 = Mat<4, 6>;
using Mat4x9 = Mat<4, 9>;
using Mat6x4 = Mat<6, 4>;
using Mat6x6 = Mat<6, 6>;
using Mat6x9 = Mat<6, 9>;
using Mat9x4 = Mat<9, 4>;
using Mat9x6 = Mat<9, 6>;
using Mat9x9 = Mat<9, 9>;
using Mat9x12 = Mat<9, 12>;
using Mat12x3 = Mat<12, 3>;
using Mat12x9 = Mat<12, 9>;
using Mat12x12 = Mat<12, 12>;

inline double clamp(const double minval, const double val, const double maxval) {
    double retval = val;
    if (val < minval) {
        retval = minval;
    }
    if (val > maxval) {
        retval = maxval;
    }
    return retval;
}

inline void svd(const math::Mat3x3& F, math::Vec3& sigma, math::Mat3x3& U, math::Mat3x3& V, bool identify_flips = true) {

    Eigen::JacobiSVD<math::Mat3x3, Eigen::FullPivHouseholderQRPreconditioner> svd(F, math::ComputeFullU | math::ComputeFullV);
    sigma = svd.singularValues();
    U = svd.matrixU();
    V = svd.matrixV();

    if (identify_flips) {
        math::Mat3x3 J = math::Mat3x3::Identity();
        J(2, 2) = -1.0;
        if (U.determinant() < 0.) {
            U = U * J;
            sigma[2] = -sigma[2];
        }
        if (V.determinant() < 0.0) {
            math::Mat3x3 Vt = V.transpose();
            Vt = J * Vt;
            V = Vt.transpose();
            sigma[2] = -sigma[2];
        }
    }
}

inline void svd(const std::vector<math::Mat3x3> &A, std::vector<math::Vec3> &sigma,
        std::vector<math::Mat3x3> &U, std::vector<math::Mat3x3> &V) {

    const int num_elements = A.size();

    using EigenSVD = Eigen::JacobiSVD<math::Mat3x3, Eigen::FullPivHouseholderQRPreconditioner>;

    #pragma omp parallel
    {
        EigenSVD svd(3, 3, math::ComputeFullU | math::ComputeFullV);
        #pragma omp for
        for (int e = 0; e < num_elements; e++) {
            svd.compute(A[e]);
            sigma[e] = svd.singularValues();
            U[e] = svd.matrixU();
            V[e] = svd.matrixV();
            math::Mat3x3 J = math::Mat3x3::Identity();
            J(2, 2) = -1.0;
            if (U[e].determinant() < 0.) {
                U[e] = U[e] * J;
                sigma[e][2] = -sigma[e][2];
            }
            if (V[e].determinant() < 0.0) {
                math::Mat3x3 Vt = V[e].transpose();
                Vt = J * Vt;
                V[e] = Vt.transpose();
                sigma[e][2] = -sigma[e][2];
            }
        }
    }
}

inline void svd(const math::Mat2x2 &A, math::Vec2 &sigma, math::Mat2x2 &U,
        math::Mat2x2 &V, bool identify_flips = true) {
    Eigen::JacobiSVD<math::Mat2x2, Eigen::FullPivHouseholderQRPreconditioner> svd(A, math::ComputeFullU | math::ComputeFullV);
    sigma = svd.singularValues();
    U = svd.matrixU();
    V = svd.matrixV();

    if (identify_flips) {
        math::Mat2x2 J = math::Mat2x2::Identity();
        J(1, 1) = -1.0;
        if (U.determinant() < 0.) {
            U = U * J;
            sigma[1] = -sigma[1];
        }
        if (V.determinant() < 0.0) {
            math::Mat2x2 Vt = V.transpose();
            Vt = J * Vt;
            V = Vt.transpose();
            sigma[1] = -sigma[1];
        }
    }
}

inline void polar(const math::Mat3x3& F, math::Mat3x3& R, math::Mat3x3& S, bool identify_flips = true) {
    math::Vec3 sigma;
    math::Mat3x3 U;
    math::Mat3x3 V;
    svd(F, sigma, U, V, identify_flips);
    R = U * V.transpose();
    S = V * sigma.asDiagonal() * V.transpose();
}

inline math::Mat3x3 rot(const math::Mat3x3& A) {
    math::Mat3x3 R;
    math::Mat3x3 S;
    polar(A, R, S, true);
    return R;
}

inline math::Mat3x3 sym(const math::Mat3x3& A) {
    math::Mat3x3 R;
    math::Mat3x3 S;
    polar(A, R, S, true);
    return S;
}

// Project a symmetric real matrix to the nearest SPD matrix
// Source: https://github.com/liminchen/OptCuts/blob/master/src/Utils/IglUtils.hpp#L72
template<typename Scalar, int size>
inline void makePD(Eigen::Matrix<Scalar, size, size>& symMtr) {
    Eigen::SelfAdjointEigenSolver<Eigen::Matrix<Scalar, size, size>> eigenSolver(symMtr);
    if(eigenSolver.eigenvalues()[0] >= 0.0) {
        return;
    }
    Eigen::DiagonalMatrix<Scalar, size> D(eigenSolver.eigenvalues());
    int rows = ((size == Eigen::Dynamic) ? symMtr.rows() : size);
    int i = 0;
    for(; i < rows; i++) {
        if(D.diagonal()[i] < 0.0) {
            D.diagonal()[i] = 0.0;
        }
        else {
            break;
        }
    }
    symMtr = eigenSolver.eigenvectors() * D * eigenSolver.eigenvectors().transpose();
}

}  // namespace math
}  // namespace wrapd

#endif  // SRC_MATH_HPP_

max_stars_repo_name: georgbrown/wrapd

max_issues_repo_name: georgbrown/wrapd

max_forks_repo_name: georgbrown/wrapd


text:
#pragma once
#include <Eigen/Core>

#include "fixed_size_container_type_trait.hpp"
#include "internal/no_discard.hpp"

namespace ubs {

/**
 * @brief Uniform B-spline output trait for multi-dimensional Eigen vectors.
 * \sa FixedSizeContainerTypeTrait
 * @tparam T_ The value type.
 * @tparam N_ The number of output dimensions.
 */
template <typename T_, int N_>
struct FixedSizeContainerTypeTrait<Eigen::Matrix<T_, N_, 1>> {
    static_assert(N_ > 0, "Only fixed size output dimensions supported.");

    using Type = Eigen::Matrix<T_, N_, 1>;
    using ValueType = T_;
    using Allocator = Eigen::aligned_allocator<Type>;

    static constexpr int Size = N_;
    static constexpr bool IsContinuous = true;

    UBS_NO_DISCARD static auto zero() {
        return Eigen::Matrix<T_, N_, 1>::Zero();
    }

    UBS_NO_DISCARD static auto ones() {
        return Eigen::Matrix<T_, N_, 1>::Ones();
    }

    UBS_NO_DISCARD static ValueType& get(Type& vec, int idx) {
        return vec[idx];
    }

    UBS_NO_DISCARD static const ValueType& get(const Type& vec, int idx) {
        return vec[idx];
    }

    UBS_NO_DISCARD static const ValueType* data(const Type& vec) {
        return vec.data();
    }

    UBS_NO_DISCARD static ValueType* data(Type& vec) {
        return vec.data();
    }

    UBS_NO_DISCARD static Type evalSmoothness(ValueType factor, const Type& p1, const Type& p2) {
        return factor * p1.array() * p2.array();
    }
};

} // namespace ubs


text:
// (C) Copyright Jonathan Turkanis 2003.
// (C) Copyright Craig Henderson 2002.   'boost/memmap.hpp' from sandbox
// 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.)

// See http://www.boost.org/libs/iostreams for documentation.

//
// This header and its accompanying source file libs/iostreams/memmap.cpp are
// an adaptation of Craig Henderson's memmory mapped file library. The
// interface has been revised significantly, but the underlying OS-specific
// code is essentially the same, with some code from Boost.Filesystem
// mixed in. (See notations in source.)
//
// The following changes have been made:
//
// 1. OS-specific code put in a .cpp file.
// 2. Name of main class changed to mapped_file.
// 3. mapped_file given an interface similar to std::fstream (open(),
//    is_open(), close()) and std::string (data(), size(), begin(), end()).
// 4. An additional class readonly_mapped_file has been provided as a
//    convenience.
// 5. [Obsolete: Error states are reported using filesystem::error_code.]
// 6. Read-only or read-write states are specified using ios_base::openmode.
// 7. Access to the underlying file handles and to security parameters
//    has been removed.
//

#ifndef BOOST_IOSTREAMS_MAPPED_FILE_HPP_INCLUDED
#define BOOST_IOSTREAMS_MAPPED_FILE_HPP_INCLUDED

#if defined(_MSC_VER) && (_MSC_VER >= 1020)
# pragma once
#endif

#include <boost/config.hpp>                   // make sure size_t is in std.
#include <cstddef>                            // size_t.
#include <string>                             // pathnames.
#include <utility>                            // pair.
#include <boost/config.hpp>                   // BOOST_MSVC.
#include <boost/detail/workaround.hpp>
#include <boost/iostreams/close.hpp>
#include <boost/iostreams/concepts.hpp>
#include <boost/iostreams/detail/config/auto_link.hpp>
#include <boost/iostreams/detail/config/dyn_link.hpp>
#include <boost/iostreams/detail/ios.hpp>     // openmode.
#include <boost/iostreams/operations_fwd.hpp>
#include <boost/iostreams/positioning.hpp>
#include <boost/shared_ptr.hpp>

// Must come last.
#include <boost/iostreams/detail/config/disable_warnings.hpp>
#include <boost/config/abi_prefix.hpp>

namespace boost { namespace iostreams {

namespace detail {

struct mapped_file_impl;

} // End namespace detail.

struct mapped_file_params {
    explicit mapped_file_params()
        : mode(), offset(0), length(static_cast<std::size_t>(-1)),
          new_file_size(0), hint(0)
        { }
    explicit mapped_file_params(const std::string& path)
        : path(path), mode(), offset(0),
          length(static_cast<std::size_t>(-1)),
          new_file_size(0), hint(0)
        { }
    std::string          path;
    BOOST_IOS::openmode  mode;
    stream_offset        offset;
    std::size_t          length;
    stream_offset        new_file_size;
    const char*          hint;
};

//------------------Definition of mapped_file_source--------------------------//

class BOOST_IOSTREAMS_DECL mapped_file_source {
private:
    struct safe_bool_helper { int x; };         // From Bronek Kozicki.
    typedef int safe_bool_helper::* safe_bool;
    friend struct operations<mapped_file_source>;
public:
    typedef char               char_type;
    struct category
        : public source_tag,
          public direct_tag,
          public closable_tag
        { };
    typedef std::size_t        size_type;
    typedef const char*        iterator;
    BOOST_STATIC_CONSTANT(size_type, max_length = static_cast<size_type>(-1));

    mapped_file_source() { }
    explicit mapped_file_source(mapped_file_params);
    explicit mapped_file_source( const std::string& path,
                                 size_type length = max_length,
                                 boost::intmax_t offset = 0 );

    //--------------Stream interface------------------------------------------//

    void open(mapped_file_params params);
    void open( const std::string& path,
               size_type length = max_length,
               boost::intmax_t offset = 0 );
    bool is_open() const;
    void close();

    operator safe_bool() const;
    bool operator!() const;
    BOOST_IOS::openmode mode() const;

    //--------------Container interface---------------------------------------//

    size_type size() const;
    const char* data() const;
    iterator begin() const;
    iterator end() const;

    //--------------Query admissible offsets----------------------------------//

    // Returns the allocation granularity for virtual memory. Values passed
    // as offsets must be multiples of this value.
    static int alignment();
private:
    friend class mapped_file;
    typedef detail::mapped_file_impl impl_type;
    void open_impl(mapped_file_params);

    boost::shared_ptr<impl_type> pimpl_;
};

//------------------Definition of mapped_file---------------------------------//

class BOOST_IOSTREAMS_DECL mapped_file {
private:
    typedef mapped_file_source delegate_type;
    delegate_type delegate_;
    friend struct operations<mapped_file>;
public:
    typedef char                           char_type;
    struct category
        : public seekable_device_tag,
          public direct_tag,
          public closable_tag
        { };
    typedef mapped_file_source::size_type  size_type;
    typedef char*                          iterator;
    typedef const char*                    const_iterator;
    BOOST_STATIC_CONSTANT(size_type, max_length = delegate_type::max_length);
    mapped_file() { }
    explicit mapped_file(mapped_file_params p);
    explicit mapped_file( const std::string& path,
                          BOOST_IOS::openmode mode =
                              BOOST_IOS::in | BOOST_IOS::out,
                          size_type length = max_length,
                          stream_offset offset = 0 );

    //--------------Conversion to readonly_mapped_file------------------------//

    operator mapped_file_source&() { return delegate_; }
    operator const mapped_file_source&() const { return delegate_; }

    //--------------Stream interface------------------------------------------//

    void open(mapped_file_params p);
    void open( const std::string& path,
               BOOST_IOS::openmode mode =
                   BOOST_IOS::in | BOOST_IOS::out,
               size_type length = max_length,
               stream_offset offset = 0 );
    bool is_open() const { return delegate_.is_open(); }
    void close() { delegate_.close(); }
    operator delegate_type::safe_bool() const { return delegate_; }
    bool operator!() const { return !is_open(); }
    BOOST_IOS::openmode mode() const { return delegate_.mode(); }

    //--------------Container interface---------------------------------------//

    size_type size() const { return delegate_.size(); }
    char* data() const
    {
        return (mode() & BOOST_IOS::out) ?
            const_cast<char*>(delegate_.data()) :
            0;
    }
    const char* const_data() const { return delegate_.data(); }
    iterator begin() const { return data(); }
    const_iterator const_begin() const { return data(); }
    iterator end() const { return data() + size(); }
    const_iterator const_end() const { return data() + size(); }

    //--------------Query admissible offsets----------------------------------//

    // Returns the allocation granularity for virtual memory. Values passed
    // as offsets must be multiples of this value.
    static int alignment() { return mapped_file_source::alignment(); }
};

struct BOOST_IOSTREAMS_DECL mapped_file_sink : private mapped_file {
    friend struct operations<mapped_file_sink>;
    typedef char char_type;
    struct category
        : public sink_tag,
          public direct_tag,
          public closable_tag
        { };
    using mapped_file::close;
    explicit mapped_file_sink(mapped_file_params p);
    explicit mapped_file_sink( const std::string& path,
                               size_type length = max_length,
                               boost::intmax_t offset = 0 );
    void open(mapped_file_params p);
    void open( const std::string& path,
               size_type length = max_length,
               boost::intmax_t offset = 0 );
};

//------------------Specialization of direct_impl-----------------------------//

template<>
struct operations<boost::iostreams::mapped_file_source>
    : detail::close_impl<closable_tag>
{
    static std::pair<char*, char*>
    input_sequence(boost::iostreams::mapped_file_source& src)
    {
        return std::make_pair( const_cast<char*>(src.begin()),
                               const_cast<char*>(src.end()) );
    }
};

template<>
struct operations<boost::iostreams::mapped_file_sink>
    : detail::close_impl<closable_tag>
{
    static std::pair<char*, char*>
    output_sequence(boost::iostreams::mapped_file_sink& sink)
    {
        return std::make_pair(sink.begin(), sink.end());
    }
};

template<>
struct operations<boost::iostreams::mapped_file>
    : detail::close_impl<closable_tag>
{
    static std::pair<char*, char*>
    input_sequence(boost::iostreams::mapped_file& file)
    {
        return std::make_pair(file.begin(), file.end());
    }
    static std::pair<char*, char*>
    output_sequence(boost::iostreams::mapped_file& file)
    {
        return std::make_pair(file.begin(), file.end());
    }
};

} } // End namespaces iostreams, boost.

#include <boost/config/abi_suffix.hpp> // pops abi_suffix.hpp pragmas
#include <boost/iostreams/detail/config/enable_warnings.hpp> // MSVC.

#endif // #ifndef BOOST_IOSTREAMS_MAPPED_FILE_HPP_INCLUDED

max_stars_repo_name: dstrigl/mcotf

max_issues_repo_name: dstrigl/mcotf

max_forks_repo_name: dstrigl/mcotf


text:
#ifndef __FOLDING_UTILS__
#define __FOLDING_UTILS__

#include <math.h>
#include <ros/ros.h>
#include <Eigen/Dense>
#include <stdexcept>

namespace generic_control_toolbox
{
class MatrixParser
{
 public:
  MatrixParser();
  ~MatrixParser();

  /**
    Initialize a nxn matrix with values obtained from the ros parameter
    server.

    @param M The matrix to be initialized
    @param param_name The parameter server location
    @param n The ros nodehandle used to query the parameter server

    @throw logic_error in case vals does not have square dimensions.
    @return True for success, False if parameter is not available.
  **/
  static bool parseMatrixData(Eigen::MatrixXd &M, const std::string param_name,
                              const ros::NodeHandle &n);

  /**
    Computed the skew-symmetric matrix of a 3-dimensional vector.

    @param v The 3-dimensional vector
    @return The skew-symmetric matrix
  **/
  static Eigen::Matrix3d computeSkewSymmetric(const Eigen::Vector3d &v);

 private:
  /**
    Fill in a nxn matrix with the given values.

    @param M The matrix to be filled in. Will be set to the size nxn.
    @param vals A vector with the values to fill in
    @throw logic_error in case vals does not have square dimensions.
  **/
  static void initializeEigenMatrix(Eigen::MatrixXd &M,
                                    const std::vector<double> &vals);
};
}  // namespace generic_control_toolbox

#endif


text:
// Copyright Louis Dionne 2013-2017
// 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 TEST_SUPPORT_EQUIVALENCE_CLASS_HPP
#define TEST_SUPPORT_EQUIVALENCE_CLASS_HPP

#include <boost/hana/fwd/equal.hpp>

struct EquivalenceClass { };

template <typename Token, typename T>
struct equivalence_class_impl {
    Token equivalence_class;
    T unwrap;
    using hana_tag = EquivalenceClass;
};

template <typename Token, typename X>
constexpr equivalence_class_impl<Token, X> equivalence_class(Token token, X x) {
    return {token, x};
}

namespace boost { namespace hana {
    template <>
    struct equal_impl<EquivalenceClass, EquivalenceClass> {
        template <typename X, typename Y>
        static constexpr auto apply(X x, Y y)
        { return hana::equal(x.equivalence_class, y.equivalence_class); }
    };
}} // end namespace boost::hana

#endif // !TEST_SUPPORT_EQUIVALENCE_CLASS_HPP


text:
#include <iostream>
#include <iomanip>
#include <cstring>
#include <boost/program_options.hpp>
#include <boost/filesystem.hpp>
#include "opencv2/core.hpp"
#include "opencv2/imgproc.hpp"
#include "opencv2/highgui.hpp"

#include <Eigen/Core>
#include "RTree.h"

namespace {
constexpr char WIND_NAME[] = "Image";

cv::Vec3b paletteColor(int color_index, bool bgr)
{
    using cv::Vec3b;
    static const Vec3b palette[] = {
        Vec3b(0, 220, 255), Vec3b(177, 13, 201), Vec3b(94, 255, 34),
        Vec3b(54, 65, 255), Vec3b(64, 255, 255), Vec3b(217, 116, 0),
        Vec3b(27, 133, 255), Vec3b(190, 18, 240), Vec3b(20, 31, 210),
        Vec3b(75, 20, 133), Vec3b(255, 219, 127), Vec3b(204, 204, 57),
        Vec3b(112, 153, 61), Vec3b(64, 204, 46), Vec3b(112, 255, 1),
        Vec3b(170, 170, 170), Vec3b(225, 30, 42), Vec3b(255, 255, 32),
        Vec3b(255, 45, 250), Vec3b(101, 0, 209), Vec3b(40, 70, 50),
        Vec3b(100, 100, 100), Vec3b(105, 200, 120), Vec3b(150,150,150)
    };

    if (color_index == 255) return Vec3b(0, 0, 0);
    Vec3b color = palette[color_index % (int)(sizeof palette / sizeof palette[0])];
    return bgr ? color : Vec3b(color[2], color[1], color[0]);
}
}

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

    std::vector<std::string> model_paths;
    std::string dataset_path;
    int image_index;

    namespace po = boost::program_options;
    po::options_description desc("Option arguments");
    po::options_description descPositional("OpenARK Random Tree/Forest empirical validation tool, for directly loading avatar dataset v0.1 (c) Alex Yu 2019\nPositional arguments");
    po::options_description descCombined("");

    desc.add_options()
        ("help", "Produce help message")
    ;

    descPositional.add_options()
        ("dataset", po::value<std::string>(&dataset_path)->required(), "Dataset root path (should have depth_exr, part_mask subdirs)")
        ("image", po::value<int>(&image_index)->required(), "Image index to use")
        ("models", po::value<std::vector<std::string> >(&model_paths)->required(), "Model path (from rtree-train)")
        ;

    descCombined.add(descPositional);
    descCombined.add(desc);
    po::variables_map vm;

    po::positional_options_description posopt;
    posopt.add("dataset", 1);
    posopt.add("image", 1);
    posopt.add("models", -1);

    try {
        po::store(po::command_line_parser(argc, argv).options(descCombined)
                .positional(posopt).run(),
                vm);
    } catch (std::exception& e) {
        std::cerr << "Error: " << e.what() << "\n";
        std::cerr << descPositional << "\n" << desc << "\n";
        return 1;
    }

    if ( vm.count("help")  )
    {
        std::cout << descPositional << "\n" << desc << "\n";
        return 0;
    }

    try {
        po::notify(vm);
    } catch (std::exception& e) {
        std::cerr << "Error: " << e.what() << "\n";
        std::cerr << descPositional << "\n" << desc << "\n";
        return 1;
    }

    if (model_paths.empty()) {
        std::cerr << "Error: please specify at least one model path" << "\n";
        std::cerr << descPositional << "\n" << desc << "\n";
        return 1;
    }

    using boost::filesystem::path;
    using boost::filesystem::exists;
    std::vector<ark::RTree> rtrees;
    for (auto& model_path: model_paths) {
        rtrees.emplace_back(model_path);
    }
    bool show_mask = false;
    while (true) {
        std::cerr << image_index << " LOAD\n";
        std::stringstream ss_img_id;
        ss_img_id << std::setw(8) << std::setfill('0') << std::to_string(image_index);

        if (show_mask) {
            std::string mask_path = (path(dataset_path) / "part_mask" / ("part_mask_" + ss_img_id.str() + ".tiff")).string();
            if (!exists(mask_path)) {
                mask_path = (path(dataset_path) / "part_mask" / ("part_mask_" + ss_img_id.str() + ".png")).string();
            }
            cv::Mat mask = cv::imread(mask_path, cv::IMREAD_GRAYSCALE);
            cv::Mat mask_color = cv::imread(mask_path);
            for (int r = 0; r < mask.rows; ++r) {
                auto* maskPtr = mask.ptr<uint8_t>(r);
                auto* outPtr = mask_color.ptr<cv::Vec3b>(r);
                for (int c = 0; c < mask.cols; ++c){
                    outPtr[c] = paletteColor(maskPtr[c], true);
                }
            }
            cv::imshow(WIND_NAME, mask_color);
        } else {
            std::string image_path = (path(dataset_path) / "depth_exr" / ("depth_" + ss_img_id.str() + ".exr")).string();

            cv::Mat image = cv::imread(image_path, cv::IMREAD_ANYCOLOR | cv::IMREAD_ANYDEPTH);
            cv::Mat visual = cv::Mat::zeros(image.size(), CV_8UC3);
            if (rtrees.size() > 1) {
                std::vector<cv::Mat> result;
                for (auto& rtree : rtrees) {
                    std::vector<cv::Mat> model_results = rtree.predict(image);
                    if (result.empty()) result = model_results;
                    else {
                        for (size_t i = 0; i < result.size(); ++i) {
                            result[i] += model_results[i];
                        }
                    }
                }
                // for (size_t i = 0; i < result.size(); ++i) {
                //     result[i] /= model_paths.size();
                // }

                cv::Mat maxVals(image.size(), CV_32F);
                maxVals.setTo(0);
                for (size_t i = 0; i < result.size(); ++i) {
                    for (int r = 0; r < image.rows; ++r) {
                        auto* imPtr = image.ptr<float>(r);
                        auto* inPtr = result[i].ptr<float>(r);
                        auto* maxValPtr = maxVals.ptr<float>(r);
                        auto* visualPtr = visual.ptr<cv::Vec3b>(r);
                        for (int c = 0; c < image.cols; ++c){
                            if (imPtr[c] == 0.0) continue;
                            if (inPtr[c] > maxValPtr[c]) {
                                maxValPtr[c] = inPtr[c];
                                visualPtr[c] = paletteColor(i, true);
                            }
                        }
                    }
                }
            } else {
                cv::Mat result = rtrees[0].predictBest(image, std::thread::hardware_concurrency());
                for (int r = 0; r < image.rows; ++r) {
                    auto* inPtr = result.ptr<uint8_t>(r);
                    auto* visualPtr = visual.ptr<cv::Vec3b>(r);
                    for (int c = 0; c < image.cols; ++c){
                        if (inPtr[c] == 255) continue;
                        visualPtr[c] = paletteColor(inPtr[c], true);
                    }
                }
            }
            cv::imshow(WIND_NAME, visual);
        }

        int k = cv::waitKey(0);
        if (k == 'q' || k == 27) break;
        else if (k == 'a' && image_index >= 0) {
            --image_index;
        } else if (k == 'd') {
            ++image_index;
        } else if (k == 'm') {
            show_mask = !show_mask;
        }
    }

    /*
    for (size_t i = 0; i < result.size(); ++i) {
        std::cerr << i << "\n";
        cv::normalize(result[i], result[i], 0.0, 1.0, cv::NORM_MINMAX);
        cv::imshow(WIND_NAME, result[i]);
        cv::waitKey(0);
    }
    */
    return 0;
}

ext: cpp

max_stars_repo_name: jyuatsfl/avatar


text:
#ifndef SQL_TEXT_GRAMMAR_DEF_SQL_HPP
#define SQL_TEXT_GRAMMAR_DEF_SQL_HPP

#include "sql/text/grammar/sql.hpp"

#include "sql/text/grammar_def/sql_stmt.hpp"
#include "sql/text/parser/error_handler.hpp"

#include <boost/spirit/home/x3/support/utility/annotate_on_success.hpp>

namespace sql { namespace text {

    using boost::spirit::x3::annotate_on_success;

    ///////////////////////////////////////////////////////////////////////////
    // Grammar
    ///////////////////////////////////////////////////////////////////////////

    auto const sql_def = sql_stmt_list;

    ///////////////////////////////////////////////////////////////////////////
    // Definition
    ///////////////////////////////////////////////////////////////////////////

    BOOST_SPIRIT_DEFINE( sql );

    ///////////////////////////////////////////////////////////////////////////
    // Annotation and Error handling
    ///////////////////////////////////////////////////////////////////////////

    struct sql_class              : annotate_on_success, error_handler_base {};

}}

#endif //SQL_TEXT_GRAMMAR_DEF_SQL_HPP

max_stars_repo_name: cviebig/lib-sql-text

max_issues_repo_name: cviebig/lib-sql-text

max_forks_repo_name: cviebig/lib-sql-text


text:
/*
 Copyright 2014 Arjan van der Velde, vandervelde.ag [at] gmail

 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.
 */

// see http://genome.ucsc.edu/FAQ/FAQformat#format7
#pragma once

#include "TwoBit/objects/TwoBitSequenceMeta.hpp"
#include "TwoBit/err/Exception.hpp"
#include <boost/filesystem.hpp>
#include <string>
#include <fstream>
#include <unordered_map>

namespace TwoBit
{
namespace bfs = boost::filesystem;

class TwoBitSequenceMeta;
class TwoBitSequence;

/**@brief Class for reading from the TwoBit format
 *
 */
class TwoBitFile
{
private:

	static const uint32_t MAGIC_NUMBER = 0x1A412743;
	static const uint32_t REVERSE_MAGIC_NUMBER = 0x4327411A;
	static const uint32_t VERSION = 0;
	static const uint32_t RESERVED = 0;
	static const uint32_t SEQNAME_MAX_LEN = 256; // represented by one byte so, ...

	bool swapped_;
	uint32_t magic_;
	uint32_t version_;
	uint32_t sequenceCount_;
	uint32_t reserved_;
	bfs::path filename_;
	std::ifstream file_;
	std::unordered_map<std::string, TwoBitSequenceMeta> sequences_;
	std::vector<std::string> sequenceNames_;

	/**@brief read a uint32_t from file handle and swap bytes if required
	 *
	 * @return the uint32_t read from file_
	 */
	inline const uint32_t nextInt()
	{
		union aligned
		{
			uint32_t uint;
			char bytes[4];
		} in, out;

		if (file_.read(reinterpret_cast<char*>(&in), 4)) {
			if (swapped_) {
				for (uint32_t i = 0; i < 4; ++i) {
					out.bytes[3 - i] = in.bytes[i];
				}
				return out.uint;
			} else {
				return in.uint;
			}
		} else {
			throw Exception(__PRETTY_FUNCTION__, "Error reading file.");
		}
	}

	/**@brief read one char from file handle
	 *
	 * @return read a char read from file_
	 */
	inline const unsigned char nextChar()
	{
		char out;
		if (file_.read(&out, 1)) {
			return out;
		} else {
			throw Exception(__PRETTY_FUNCTION__, "Error reading file.");
		}
	}

	/**@brief read 16 header bytes from file
	 *
	 */
	void readTwoBitHeader();

	/**@brief create sequences from file
	 *
	 */
	void createSequenceMeta();
	void populateSequenceMeta(TwoBitSequenceMeta& meta);
	void readRegions(std::vector<TwoBitSequenceMeta::Region>& out);

public:

	/**@brief copy construct by simply get the filename from the other reader and constructing
	 *
	 * @param other
	 */
	TwoBitFile(const TwoBitFile& other);
	//delete some stuff
	TwoBitFile() = delete;
	TwoBitFile& operator=(const TwoBitFile& other) = delete;

	/**@brief Construct with filename
	 *
	 * @param filename The twobit file name
	 */
	TwoBitFile(const bfs::path& filename);

	/**@brief operator to get the sequence for seq name
	 *
	 * @param s the sequence name
	 * @return the sequence for seq name
	 */
	std::unique_ptr<TwoBitSequence> operator[](const std::string& s) const;

	/**@brief Get the seq names stored in
	 *
	 * @return The sequences names
	 */
	const std::vector<std::string>& sequenceNames() const;

	/**@brief Return if sequence name is in file
	 *
	 * @param seqName the sequence name
	 * @return true if seq name is in file
	 */
	bool hasSequenceName(const std::string & seqName) const;

	/**@brief Get a map of seq name to seq length
	 *
	 * @return a map of seq name to seq length
	 */
	std::unordered_map<std::string, uint32_t> getSeqLens() const;

	/**@brief Get the number of sequences
	 *
	 * @return the number of sequences
	 */
	const uint32_t size() const;

	/**@brief Get the filename of the twobit file
	 *
	 * @return the filename of the twobit file
	 */
	bfs::path getFilename() const;

};

} // namespace TwoBit


text:
#include "options.hxx"

#include <iostream>
#include <iomanip>
#include <fstream>
#include <stdexcept>
#include <sys/utsname.h>
#include <boost/filesystem.hpp>
#include <boost/algorithm/string.hpp>

namespace dbl {

void Options::parse(int argc, char** argv, config::Config& config)
{
	namespace fs = boost::filesystem;
	using std::string;
	po::options_description flags("Generic");
	po::options_description service("Service options");
	po::options_description dnsproxy("DNS proxy");
	po::options_description dnsproxy_custom("Custom DNS proxy instance options");
	po::options_description network("Network options");
	po::options_description http_responder("HTTP Responder");
	po::options_description lists("DNS lists options");
	po::options_description query("Querying options");
	po::options_description management("Management");
	po::options_description config_file_options("");

	string config_path;

	struct utsname utsn;
	int status = uname(&utsn);
	if(status != 0) {
		throw std::runtime_error("uname() failed");
	}

	string current_platform(utsn.sysname);
	boost::algorithm::to_lower(current_platform);
	string current_path = fs::current_path().string();

	bool no_config = false;

	std::vector<std::string> empty_str_vec {};

	flags.add_options()
		("help,h", "Display this help")
		("debug,D",
		 po::value(&(config.is_debug))->implicit_value(true)->zero_tokens()->default_value(false),
		 "Debug mode"
		)
		("fatal,F",
		 po::value(&(config.is_fatal))->implicit_value(true)->zero_tokens()->default_value(false),
		 "Make all errors fatal"
		)
		("foreground,f",
		 po::value(&(config.is_foreground))->implicit_value(true)->zero_tokens()->default_value(false),
		 "Do not go into background"
		)
		("verbose,v",
		 po::value(&(config.is_verbose))->implicit_value(true)->zero_tokens()->default_value(false),
		 "Verbose run"
		)
		("test,T",
		 po::value(&(config.is_test))->implicit_value(true)->zero_tokens()->default_value(false),
		 "Do not start/generate anything - just test init"
		)
		;

	service.add_options()
		("basedir",
		 po::value(&(config.base_dir))->default_value(config.base_dir),
		 "base application directory"
		)
		("config,c",
		 po::value(&(config.service_config))->default_value(config.service_config),
		 "Configuration file path"
		)
		("no-config,N",
		 po::value(&no_config)->implicit_value(true)->zero_tokens()->default_value(no_config),
		 "Do not read configuration file"
		)
		("db",
		 po::value(&(config.service_db))->default_value(config.service_db),
		 "Database file path"
		)
		("logfile",
		 po::value(&(config.service_logfile))->default_value(config.service_logfile)
		)
		("logger-config-path",
		 po::value(&(config.logger_config_path))->default_value(
			 config.logger_config_path
		 )
		)
		("no-chdir",
		 po::value(&(config.no_chdir))->implicit_value(true)->zero_tokens()->default_value(false),
		 "Do not chdir after daemonizing"
		)
		("no-close-fds",
		 po::value(&(config.no_chdir))->implicit_value(true)->zero_tokens()->default_value(false),
		 "Do not close file descriptors after daemonizing"
		)
		("pidfile",
		 po::value(&(config.service_pidfile))->default_value(config.service_pidfile)
		)
		("platform",
		 po::value(&(config.platform))->default_value(current_platform),
		 "Override platform"
		)
		("service-port",
		 po::value(&(config.service_port))->default_value(config.service_port),
		 "Service port"
		)
		("script-dir",
		 po::value(&(config.script_dir))->default_value(config.script_dir),
		 "Location of scripts"
		)
		("service-user",
		 po::value(&(config.service_user))->default_value(config.service_user),
		 "Drop privileges and run as this user"
		)
		("templates-dir",
		 po::value(&(config.templates_dir))->default_value(config.templates_dir),
		 "Override platform (if guessed incorrect)"
		)
		("no-system-dns-proxy",
		 po::value(&(config.no_system_dns_proxy))->implicit_value(true)->zero_tokens()->default_value(false),
		 "Use system installed DNS Proxy server"
		)
		("no-update",
		 po::value(&(config.no_update))->implicit_value(true)->zero_tokens()->default_value(false),
		 "Disable all updates"
		)
		("update-interval",
		 po::value(&(config.update_interval))->default_value(config.update_interval),
		 "Update interval in seconds (min 3600)"
		)
		;

	lists.add_options()
		("disable-list-update",
		 po::value(&(config.disable_list_update))->implicit_value(true)->zero_tokens()->default_value(
			 config.disable_list_update
		 ),
		 "Do not update blocking lists"
		)
		("list-ids",
		 po::value<std::vector<std::string>>(&(config.list_ids))->multitoken()
		)
		;

	dnsproxy.add_options()
		("dns-proxy",
		 po::value(&(config.dns_proxy))->default_value(config.dns_proxy),
		 "DNS Proxy server"
		)
		("dns-proxy-include-dir",
		 po::value(&(config.dns_proxy_include_dir))->default_value(config.dns_proxy_include_dir)
		)
	;
	dnsproxy_custom.add_options()
		("dns-proxy-chroot",
		 po::value(&(config.dns_proxy_chroot))->default_value(config.dns_proxy_chroot),
		 "DNS Proxy chroot dir (must be already set up)"
		)
		("dns-proxy-config",
		 po::value(&(config.dns_proxy_config))->default_value("")
		)
		("dns-proxy-config-destdir",
		 po::value(&(config.dns_proxy_config_dest_dir))->default_value(config.dns_proxy_config_dest_dir),
		 "Location of generated proxy configuration file"
		)
		("dns-proxy-disable-dnssec",
		 po::value(&(config.dns_proxy_disable_dnssec))->implicit_value(true)->zero_tokens()->default_value(
			 config.dns_proxy_disable_dnssec
		 )
		)
		("dns-proxy-generate-config",
		 po::value(&(config.dns_proxy_generate_config))->implicit_value(true)->zero_tokens()->default_value(
			 config.dns_proxy_generate_config
		 )
		)
		("dns-proxy-logfile",
		 po::value(&(config.dns_proxy_logfile))->default_value(config.dns_proxy_logfile)
		)
		("dns-proxy-pidfile",
		 po::value(&(config.dns_proxy_pidfile))->default_value(config.dns_proxy_pidfile)
		)
		("dns-proxy-port",
		 po::value(&(config.dns_proxy_port))->default_value(config.dns_proxy_port)
		)
		("dns-proxy-root-key",
		 po::value(&(config.dns_proxy_root_key))->default_value(config.dns_proxy_root_key)
		)
		("dns-proxy-user",
		 po::value(&(config.dns_proxy_user))->default_value(config.dns_proxy_user)
		)
		("dns-proxy-workdir",
		 po::value(&(config.dns_proxy_workdir))->default_value(config.dns_proxy_workdir)
		)
		;

	network.add_options()
		("network-interface",
		 po::value(&(config.network_interface))->default_value(config.network_interface),
		 "Network interface (defaults to loopback)"
		)
		("network-ip4address",
		 po::value(&(config.network_ip4address))->default_value(config.network_ip4address)
		)
		("network-ip6address",
		 po::value(&(config.network_ip6address))->default_value(config.network_ip6address)
		)
		("network-no-ip4",
		 po::value(&(config.network_no_ip4))->implicit_value(true)->zero_tokens()->default_value(
			 config.network_no_ip4
		 )
		)
		("network-no-ip6",
		 po::value(&(config.network_no_ip6))->implicit_value(true)->zero_tokens()->default_value(
			 config.network_no_ip6
		 )
		)
		;

	http_responder.add_options()
		("http-responder-enable",
		 po::value(&(config.http_responder_enable))->implicit_value(true)->zero_tokens()->default_value(false),
		 "builtin HTTP responder"
		)
		("http-responder-port",
		 po::value(&(config.http_responder_port))->default_value(config.http_responder_port),
		 "Override builtin HTTP responder"
		)
		("http-responder-status-code",
		 po::value(&(config.http_responder_status_code))->default_value(config.http_responder_status_code)
		)
		("http-responder-status-text",
		 po::value(&(config.http_responder_status_text))->default_value(config.http_responder_status_text)
		)
		;

	query.add_options()
		("query,Q",
		 po::value<bool>()->implicit_value(true)->zero_tokens()->default_value(false),
		 "Query/info mode"
		)
		("domain-lists,L",
		 po::value<bool>()->implicit_value(true)->zero_tokens()->default_value(false),
		 "Show domain lists"
		)
		("domains,l",
		 po::value<bool>()->implicit_value(true)->zero_tokens()->default_value(false),
		 "List blocked domains"
		)
		("domain,d",
		 po::value<std::string>()->default_value(""),
		 "Display domain info"
		)
		;

	management.add_options()
		("block,B",
		 po::value<std::vector<std::string>>()->multitoken(),
		 "Block domain(s)"
		)
		("unblock,U",
		 po::value<std::vector<std::string>>()->multitoken(),
		 "Unblock domain(s)"
		)
		("add-list,A",
		 po::value<bool>()->implicit_value(true)->zero_tokens()->default_value(false),
		 "Add list (requires name and url)"
		)
		("list-name",
		 po::value<std::string>()->default_value(""),
		 "Name of a new list"
		)
		("list-url",
		 po::value<std::string>()->default_value(""),
		 "URL of a new list"
		)
		("list-description",
		 po::value<std::string>()->default_value(""),
		 "Description of a new list"
		)
		("delete-list", po::value<std::string>()->default_value(""),
		 "Delete list"
		)
		("enable-list", po::value<std::string>()->default_value(""),
		 "Enable list"
		)
		("disable-list", po::value<std::string>()->default_value(""),
		 "Disable list"
		)
		("export-lists,E", po::value<std::string>()->default_value(""),
		 "Export list"
		)
		;

	all_.add(flags)
		.add(service)
		.add(network)
		.add(dnsproxy)
		.add(dnsproxy_custom)
		.add(http_responder)
		.add(lists)
		.add(management)
		.add(query);

	try {
		po::store(po::command_line_parser(argc, argv).options(all_).run(), vm_);
		po::notify(vm_);

		if(!has_help()) {
			if(config.is_debug) {
				std::cout << "Reading config file: " << config.service_config << std::endl;
			}

			if(!no_config) {
				if(!fs::exists(config.service_config)) {
					throw std::runtime_error(
						"Configuration file does not exist: "
						+ config.service_config
					);
				}

				std::ifstream cf(config.service_config.c_str());

				if(!cf.good()) {
					throw std::runtime_error(
						"Cannot read configuration file"
					);
				}

				po::store(po::parse_config_file(cf, all_, true), vm_);
				po::notify(vm_);
				cf.close();
			}
		}
		//throw_on_conflict();
	}
	catch(std::exception& e) {
		std::cerr << "Options error: " << e.what() << "\n";
		throw std::runtime_error(e.what());
	}
}

void Options::dump_variables_map() const
{
	for(const auto& it : vm_) {
		std::cout << ": "  << std::setw(48) << std::left << it.first;
		std::cout.width(0);
		auto& raw = it.second.value();
		std::string v;
		if (auto v = boost::any_cast<int>(&raw)) {
			std::cout << *v;
		}
		else if (auto v = boost::any_cast<std::string>(&raw)) {
			std::cout << *v;
		}
		else if (auto v = boost::any_cast<bool>(&raw)) {
			std::cout << *v;
		}

		std::cout << std::endl;
	}
}

bool Options::has_help() const
{
	return vm_.count("help");
}

void Options::display_help() const
{
	std::cout << all_ << std::endl;
}

void Options::throw_on_conflict(const std::string& x, const std::string& y)
{
	if(vm_.count(x) && !vm_[x].defaulted() &&
	   vm_.count(y) && !vm_[y].defaulted())
	{
		throw std::logic_error(
			std::string("Conflicting options '") +
			x + "' and '" + y + "'."
		);
	}
}

} // dbl

max_stars_repo_name: mcptr/dbl-service

max_issues_repo_name: mcptr/dbl-service

max_forks_repo_name: mcptr/dbl-service


text:
/*
 * MIT License
 *
 * Copyright (c) 2018 Tech Solutions Malta LTD
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

#include <boost/test/unit_test.hpp>
#include <boost/program_options.hpp>

#include <graphene/account_history/account_history_plugin.hpp>
#include <graphene/market_history/market_history_plugin.hpp>

#include <graphene/db/simple_index.hpp>

// #include <graphene/chain/account_object.hpp>
// #include <graphene/chain/asset_object.hpp>
// #include <graphene/chain/committee_member_object.hpp>
// #include <graphene/chain/fba_object.hpp>
// #include <graphene/chain/license_objects.hpp>
// #include <graphene/chain/market_object.hpp>
// #include <graphene/chain/vesting_balance_object.hpp>
// #include <graphene/chain/witness_object.hpp>

#include <graphene/utilities/tempdir.hpp>

#include <fc/crypto/digest.hpp>

#include <iostream>
#include <iomanip>
#include <sstream>

#include "database_fixture.hpp"

namespace graphene { namespace chain {

const global_property_object& database_fixture::get_global_properties() const
{
  return db.get_global_properties();
}

const dynamic_global_property_object& database_fixture::get_dynamic_global_properties() const
{
  return db.get_dynamic_global_properties();
}

const chain_parameters& database_fixture::get_chain_parameters() const
{
  return db.get_global_properties().parameters;
}

account_id_type database_fixture::get_license_administrator_id() const
{
  return db.get_global_properties().authorities.license_administrator;
}

account_id_type database_fixture::get_license_issuer_id() const
{
  return db.get_global_properties().authorities.license_issuer;
}

account_id_type database_fixture::get_webasset_issuer_id() const
{
  return db.get_global_properties().authorities.webasset_issuer;
}

account_id_type database_fixture::get_webasset_authenticator_id() const
{
  return db.get_global_properties().authorities.webasset_authenticator;
}

account_id_type database_fixture::get_cycle_issuer_id() const
{
  return db.get_global_properties().authorities.cycle_issuer;
}

account_id_type database_fixture::get_cycle_authenticator_id() const
{
  return db.get_global_properties().authorities.cycle_authenticator;
}

account_id_type database_fixture::get_registrar_id() const
{
  return db.get_global_properties().authorities.registrar;
}

account_id_type database_fixture::get_pi_validator_id() const
{
  return db.get_global_properties().authorities.pi_validator;
}

account_id_type database_fixture::get_wire_out_handler_id() const
{
  return db.get_global_properties().authorities.wire_out_handler;
}

account_id_type database_fixture::get_daspay_administrator_id() const
{
  return db.get_global_properties().authorities.daspay_administrator;
}

const global_property_object::daspay& database_fixture::get_daspay_parameters() const
{
  return db.get_global_properties().daspay_parameters;
}

account_id_type database_fixture::get_das33_administrator_id() const
{
  return db.get_global_properties().authorities.das33_administrator;
}

asset_id_type database_fixture::get_web_asset_id() const
{
  return db.get_web_asset_id();
}
asset_id_type database_fixture::get_cycle_asset_id() const
{
  return db.get_cycle_asset_id();
}

asset_id_type database_fixture::get_dascoin_asset_id() const
{
  return db.get_dascoin_asset_id();
}

asset_id_type database_fixture::get_btc_asset_id() const
{
  return db.get_btc_asset_id();
}

frequency_type database_fixture::get_global_frequency() const
{
  return db.get_dynamic_global_properties().frequency;
}

} }  // namespace graphene::chain

max_stars_repo_name: powerchain-ltd/greenpower-blockchain


text:
//
//  cal_T_abc.hpp
//  hybrid_fem_bie
//
//  Created by Max on 2/7/18.
//
//

#ifndef cal_T_abc_hpp
#define cal_T_abc_hpp

#include <stdio.h>
#include <Eigen/Eigen>

using namespace Eigen;

void cal_T_abc(MatrixXd coord ,double density, MatrixXd &T_abc, double v_p, double v_s);

#endif /* cal_T_abc_hpp */


text:
#include "reflect/TypeInfo.hpp"

#include "reflect/ast_utils.hpp"
#include "reflect/ReflectAST.hpp"
#include "reflect/ast_utils.hpp"

#include <clang/AST/TypeVisitor.h>
#include <clang/AST/DeclTemplate.h>

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

#include <iostream>
#include <sstream>

namespace reflection
{

class TypeUnwrapper : public clang::TypeVisitor<TypeUnwrapper, bool>
{
public:
    TypeUnwrapper(TypeInfo* targetType, const clang::ASTContext* astContext)
        : m_targetType(targetType)
          , m_astContext(astContext)
    {
    }

    bool VisitBuiltinType(const clang::BuiltinType* tp)
    {
        BuiltinType result;
        switch (tp->getKind())
        {
        case clang::BuiltinType::Void:
            result.type = BuiltinType::Void;
            m_targetType->m_declaredName = "void";
            break;
        case clang::BuiltinType::Bool:
            result.type = BuiltinType::Bool;
            result.bits = 1;
            m_targetType->m_declaredName = "bool";
            break;
        case clang::BuiltinType::Char_U:
        case clang::BuiltinType::Char_S:
            result.type = BuiltinType::Char;
            result.bits = 8;
            m_targetType->m_declaredName = "char";
            break;
        case clang::BuiltinType::WChar_U:
        case clang::BuiltinType::WChar_S:
            result.type = BuiltinType::Char;
            result.bits = 32;
            m_targetType->m_declaredName = "wchar_t";
            break;
        case clang::BuiltinType::SChar:
            result.type = BuiltinType::Char;
            result.bits = 8;
            result.isSigned = BuiltinType::Signed;
            m_targetType->m_declaredName = "signed char";
            break;
        case clang::BuiltinType::UChar:
            result.type = BuiltinType::Char;
            result.bits = 8;
            result.isSigned = BuiltinType::Unsigned;
            m_targetType->m_declaredName = "unsigned char";
            break;
        case clang::BuiltinType::Char16:
            result.type = BuiltinType::Char;
            result.bits = 16;
            m_targetType->m_declaredName = "char16_t";
            break;
        case clang::BuiltinType::Char32:
            result.type = BuiltinType::Char;
            result.bits = 32;
            m_targetType->m_declaredName = "char32_t";
            break;
        case clang::BuiltinType::UShort:
            result.type = BuiltinType::Short;
            result.bits = 16;
            result.isSigned = BuiltinType::Unsigned;
            m_targetType->m_declaredName = "unsigned short";
            break;
        case clang::BuiltinType::Short:
            result.type = BuiltinType::Short;
            result.bits = 16;
            result.isSigned = BuiltinType::Signed;
            m_targetType->m_declaredName = "short";
            break;
        case clang::BuiltinType::UInt:
            result.type = BuiltinType::Int;
            result.bits = 32;
            result.isSigned = BuiltinType::Unsigned;
            m_targetType->m_declaredName = "unsigned int";
            break;
        case clang::BuiltinType::Int:
            result.type = BuiltinType::Int;
            result.bits = 32;
            result.isSigned = BuiltinType::Signed;
            m_targetType->m_declaredName = "int";
            break;
        case clang::BuiltinType::ULong:
            result.type = BuiltinType::Long;
            result.bits = 64;
            result.isSigned = BuiltinType::Unsigned;
            m_targetType->m_declaredName = "unsigned long";
            break;
        case clang::BuiltinType::Long:
            result.type = BuiltinType::Long;
            result.bits = 64;
            result.isSigned = BuiltinType::Signed;
            m_targetType->m_declaredName = "long";
            break;
        case clang::BuiltinType::ULongLong:
            result.type = BuiltinType::LongLong;
            result.bits = 64;
            result.isSigned = BuiltinType::Unsigned;
            m_targetType->m_declaredName = "unsigned long long";
            break;
        case clang::BuiltinType::LongLong:
            result.type = BuiltinType::LongLong;
            result.bits = 64;
            result.isSigned = BuiltinType::Signed;
            m_targetType->m_declaredName = "long long";
            break;
        case clang::BuiltinType::Float:
            result.type = BuiltinType::Float;
            result.bits = 32;
            m_targetType->m_declaredName = "float";
            break;
        case clang::BuiltinType::Double:
            result.type = BuiltinType::Double;
            result.bits = 64;
            m_targetType->m_declaredName = "double";
            break;
        case clang::BuiltinType::LongDouble:
            result.type = BuiltinType::LongDouble;
            result.bits = 80;
            m_targetType->m_declaredName = "long double";
            break;
        case clang::BuiltinType::NullPtr:
            result.type = BuiltinType::Nullptr;
            m_targetType->m_declaredName = "nullptr_t";
            break;
        default:
            result.type = BuiltinType::Extended;
            break;
        }
        result.typeInfo = tp;
        result.kind = tp->getKind();
        m_targetType->m_type = result;
        m_targetType->m_scopedName = m_targetType->m_declaredName;
        m_targetType->m_fullQualifiedName = m_targetType->m_declaredName;

        return true;
    }

    bool VisitElaboratedType(const clang::ElaboratedType* tp)
    {
        return VisitQualType(tp->isSugared() ? tp->desugar() : tp->getNamedType());
    }

    bool VisitReferenceType(const clang::ReferenceType* tp)
    {
        if (tp->isSpelledAsLValue())
            m_targetType->m_isReference = true;
        else
            m_targetType->m_isRVReference = true;

        return VisitQualType(tp->getPointeeType());
    }

    bool VisitDecayedType(const clang::DecayedType* tp)
    {
        return VisitQualType(tp->getOriginalType());
    }

    bool VisitPointerType(const clang::PointerType* tp)
    {
        m_targetType->m_pointingLevels ++;
        return VisitQualType(tp->getPointeeType());
    }

    bool VisitTypedefType(const clang::TypedefType* tp)
    {
        return VisitQualType(tp->getDecl()->getUnderlyingType());
    }

    bool VisitRecordType(const clang::RecordType* tp)
    {
        RecordType result;
        result.decl = tp->getDecl();
        FillDeclDependentFields(result.decl);
        m_targetType->m_type = result;
        return true;
    }

    bool VisitDecltypeType(const clang::DecltypeType* tp)
    {
        DecltypeType result;
        result.declType = tp;
        result.declTypeExpr = tp->getUnderlyingExpr();
        m_targetType->m_type = result;
        return true;
    }

    bool VisitTemplateSpecializationType(const clang::TemplateSpecializationType* tp)
    {
        WellKnownType result;

        clang::TemplateName tplName = tp->getTemplateName();
        if (tplName.getKind() != clang::TemplateName::Template)
            return false;
        const clang::TemplateDecl* tplDecl = tplName.getAsTemplateDecl();
        result.decl = tplDecl;
        FillDeclDependentFields(tplDecl);

        if (tp->isTypeAlias())
            result.aliasedType = TypeInfo::Create(tp->getAliasedType(), m_astContext);

        for (const clang::TemplateArgument& tplArg : tp->template_arguments())
        {
            TemplateType::TplArg argInfo;
            switch (tplArg.getKind())
            {
            case clang::TemplateArgument::Null:
                argInfo = TemplateType::GenericArg{TemplateType::NullTplArg};
                break;
            case clang::TemplateArgument::Type:
                argInfo = TypeInfo::Create(tplArg.getAsType(), m_astContext);
                break;
            case clang::TemplateArgument::Declaration:
                argInfo = tplArg.getAsDecl();
                break;
            case clang::TemplateArgument::NullPtr:
                argInfo = TemplateType::GenericArg{TemplateType::NullPtrTplArg};
                break;
            case clang::TemplateArgument::Integral:
                argInfo = ConvertAPSInt(tplArg.getAsIntegral()).AsSigned();
                break;
            case clang::TemplateArgument::Template:
                argInfo = TemplateType::GenericArg{TemplateType::TemplateTplArg};
                break;
            case clang::TemplateArgument::TemplateExpansion:
                argInfo = TemplateType::GenericArg{TemplateType::TemplateExpansionTplArg};
                break;
            case clang::TemplateArgument::Expression:
            {
                llvm::APSInt value;
                if (tplArg.getAsExpr()->EvaluateAsInt(value, *m_astContext))
                    argInfo = ConvertAPSInt(value).AsSigned();
                else
                    argInfo = TemplateType::GenericArg{TemplateType::UnknownTplArg};

                break;
            }
            case clang::TemplateArgument::Pack:
                argInfo = TemplateType::GenericArg{TemplateType::PackTplArg};
                break;
            }
            result.arguments.push_back(argInfo);
        }

        bool isWellKnownType = DetectWellKnownType(result);

        if (isWellKnownType)
            m_targetType->m_type = std::move(result);
        else
            m_targetType->m_type = static_cast<TemplateType&&>(std::move(result));

        return true;
    }

    bool VisitTemplateTypeParmType(const clang::TemplateTypeParmType* tp)
    {
        TemplateParamType result;
        result.decl = tp->getDecl();
        result.isPack = tp->isParameterPack();
        m_targetType->m_type = result;
        return true;
    }

    bool DetectWellKnownType(WellKnownType& typeInfo)
    {
        bool result = true;
        if (m_targetType->m_fullQualifiedName == "std::basic_string")
        {
            const BuiltinType* charType = typeInfo.GetTypeArg(0)->getAsBuiltin();
            if (charType->type == BuiltinType::Char)
                typeInfo.type = WellKnownType::StdString;
            else if (charType->type == BuiltinType::WChar)
                typeInfo.type = WellKnownType::StdWstring;
            else
                result = false;
        }
        else if (m_targetType->m_fullQualifiedName == "std::vector")
            typeInfo.type = WellKnownType::StdVector;
        else if (m_targetType->m_fullQualifiedName == "std::array")
            typeInfo.type = WellKnownType::StdArray;
        else if (m_targetType->m_fullQualifiedName == "std::list")
            typeInfo.type = WellKnownType::StdList;
        else if (m_targetType->m_fullQualifiedName == "std::deque")
            typeInfo.type = WellKnownType::StdDeque;
        else if (m_targetType->m_fullQualifiedName == "std::map")
            typeInfo.type = WellKnownType::StdMap;
        else if (m_targetType->m_fullQualifiedName == "std::set")
            typeInfo.type = WellKnownType::StdSet;
        else if (m_targetType->m_fullQualifiedName == "std::unordered_map")
            typeInfo.type = WellKnownType::StdUnorderedMap;
        else if (m_targetType->m_fullQualifiedName == "std::unordered_set")
            typeInfo.type = WellKnownType::StdUnorderedSet;
        else if (m_targetType->m_fullQualifiedName == "std::shared_ptr")
            typeInfo.type = WellKnownType::StdSharedPtr;
        else if (m_targetType->m_fullQualifiedName == "std::unique_ptr")
            typeInfo.type = WellKnownType::StdUniquePtr;
        else if (m_targetType->m_fullQualifiedName == "std::optional")
            typeInfo.type = WellKnownType::StdOptional;
        else
            result = false;

        return result;
    }

    bool VisitEnumType(const clang::EnumType* tp)
    {
        EnumType result;
        result.decl = tp->getDecl();
        FillDeclDependentFields(result.decl);
        m_targetType->m_type = result;
        return true;
    }

    bool VisitConstantArrayType(const clang::ConstantArrayType* tp)
    {
        ArrayType result;
        result.dims.push_back(ConvertAPInt(tp->getSize()).AsUnsigned());
        TypeInfoPtr itemType = TypeInfo::Create(tp->getElementType(), m_astContext);
        if (itemType->getAsArrayType() != nullptr)
        {
            const ArrayType* subArray = itemType->getAsArrayType();
            result.dims.insert(result.dims.end(), subArray->dims.begin(), subArray->dims.end());
            itemType = subArray->itemType;
        }
        result.itemType = itemType;
        m_targetType->m_type = result;
        return true;
    }

    bool VisitQualType(const clang::QualType& qt)
    {
        m_targetType->m_isConst |= qt.isConstQualified();
        m_targetType->m_isVolatile |= qt.isVolatileQualified();

        return Visit(qt.getTypePtr());
    }

private:
    void FillDeclDependentFields(const clang::NamedDecl* decl)
    {
        NamedDeclInfo declInfo;
        AstReflector::SetupNamedDeclInfo(decl, &declInfo, m_astContext);
        m_targetType->m_declaredName = declInfo.name;
        m_targetType->m_scopedName = declInfo.scopeSpecifier.empty() ? declInfo.name : declInfo.scopeSpecifier + "::" + declInfo.name;
        m_targetType->m_fullQualifiedName = declInfo.namespaceQualifier.empty() ? m_targetType->m_scopedName : declInfo.namespaceQualifier + "::" + m_targetType->m_scopedName;
    }

private:
    TypeInfo* m_targetType;
    const clang::ASTContext* m_astContext;
};

TypeInfo::TypeInfo()
{

}

TypeInfo::TypeDescr TypeInfo::getTypeDescr() const
{
    TypeDescr result;

    auto getScope = [](const std::string& full, const std::string& name)
    {
        auto range = boost::algorithm::find_last(full, name);
        if (range.begin() == full.begin())
            return std::string();

        return full.substr(0, range.begin() - full.begin() - 2);
    };

    result.name = m_declaredName;
    result.scopeSpec = getScope(m_scopedName, m_declaredName);
    result.namespaceQual = getScope(m_fullQualifiedName, m_scopedName);
    result.isConst = m_isConst;
    result.isReference = m_isReference;
    result.isRVReference = m_isRVReference;
    result.isVolatile = m_isVolatile;
    result.pointingLevels = m_pointingLevels;
    result.type = m_type;

    return result;
}

TypeInfoPtr TypeInfo::Create(const clang::QualType& qt, const clang::ASTContext* astContext)
{
    TypeInfoPtr result = std::make_shared<TypeInfo>();

    result->m_printedName = EntityToString(&qt, astContext);
    result->m_typeDecl= qt.getTypePtr();

    TypeUnwrapper visitor(result.get(), astContext);
    bool unwrapped = visitor.VisitQualType(qt);

    if (!unwrapped) // result->m_type.empty())
    {
        result->m_typeDecl->dump();
        std::clog << std::endl;
    }
    // std::clog << "### Unwrapped type: " << result->getFullQualifiedName() << ", " << result << std::endl;

    return result;
}

TypeInfoPtr TypeInfo::Create(const TypeInfo::TypeDescr& descr)
{
    TypeInfoPtr result = std::make_shared<TypeInfo>();

    result->m_type = descr.type;
    result->m_declaredName = descr.name;
    result->m_scopedName = descr.scopeSpec.empty() ? descr.name : descr.scopeSpec + "::" + descr.name;
    result->m_fullQualifiedName = descr.namespaceQual.empty() ? result->m_scopedName : descr.namespaceQual + "::" + result->m_scopedName;
    result->m_isConst = descr.isConst;
    result->m_isReference = descr.isReference;
    result->m_isRVReference = descr.isRVReference;
    result->m_isVolatile = descr.isVolatile;
    result->m_pointingLevels = descr.pointingLevels;

    std::ostringstream os;
    if (descr.isConst)
        os << "const ";
    if (descr.isVolatile)
        os << "volatile ";
    os << result->m_fullQualifiedName;

    if (descr.isReference)
        os << "&";
    else if (descr.isRVReference)
        os << "&&";
    else for(int i = 0; i < descr.pointingLevels; ++ i)
            os << "*";

    result->m_printedName = os.str();

    return result;
}

} // reflection

max_stars_repo_name: mohibqureshi/CXXCTP

max_issues_repo_name: mohibqureshi/CXXCTP

max_forks_repo_name: mohibqureshi/CXXCTP