text:
#include <ros/ros.h>
#include <image_transport/image_transport.h>
#include <image_geometry/pinhole_camera_model.h>
#include <sensor_msgs/image_encodings.h>
#include <sensor_msgs/PointCloud2.h>
#include <geometry_msgs/PoseStamped.h>
// #include <sensor_msgs/Point_cloud2.h>
#include <jsk_recognition_msgs/BoundingBox.h>

// opencv.
// #include <opencv/cv.h>
#include <opencv2/opencv.hpp>
// #include <opencv2/Core/core.hpp>
#include <cv_bridge/cv_bridge.h>

// pcl.
// #include <pcl/pcl.h>

//! Eigen
#include <Eigen/Dense>

//! user
#include "Utility.hpp"

using namespace std;
using namespace Eigen;

//http://wiki.ros.org/image_transport/Tutorials/SubscribingToImages
//http://wiki.ros.org/image_geometry/Tutorials/ProjectTfFrameToImage

class Registration
{
    ros::NodeHandle node_;

    image_transport::ImageTransport it_;
    image_transport::Subscriber imgSub_;
    image_transport::CameraSubscriber imgCamSub_;
    image_transport::Publisher imgPub_;

    ros::Subscriber cloudSub_;
    ros::Subscriber poseSub_;
    ros::Subscriber bbxSub_;

    image_geometry::PinholeCameraModel camModel_;

public:
    // Registration(ros::NodeHandle& node);
    // virtual ~Registration();
    Registration(ros::NodeHandle& node)
        : node_(node),
        it_(node)
    {
        cout<<"imgCloudRegistration"<<endl;

        string imgTopic = node_.resolveName("/zed/zed_node/left/image_rect_color");
        string cloudTopic = node_.resolveName("/zed/zed_node/point_cloud/cloud_registered");
        string poseTopic = node_.resolveName("/republish_cxx_node/bbxpose");
        string bbxTopic = node_.resolveName("/republish_cxx_node/bbx");
        // cout<<"resolved image topic name: "<<imgTopic<<endl;

        imgCamSub_ = it_.subscribeCamera(imgTopic, 10, &Registration::imgCamCallback, this);
        // imgSub_ = it_.subscribe(imgTopic, 10, &Registration::imgCallback, this);

        // http://wiki.ros.org/image_transport/Tutorials/PublishingImages
        imgPub_ = it_.advertise("image", 10);

        cloudSub_ = node_.subscribe(cloudTopic, 10, &Registration::cloudCallback, this);
        // poseSub_ = node_.subscribe(poseTopic, 10, &Registration::poseCallback, this);
        bbxSub_ = node_.subscribe(bbxTopic, 10, &Registration::bbxCallback, this);
    }

    // bool initilization()
    // {
    //     // ros::NodeHandle node2(node);
    //     cout<<"Registration"<<endl;

    //     string imgTopic = node_.resolveName("/zed/zed_node/left/image_rect_color");
    //     string cloudTopic = node_.resolveName("/zed/zed_node/point_cloud/cloud_registered");
    //     cout<<"resolved image topic name: "<<imgTopic<<endl;

    //     it_(node_);
    //     imgSub_ = it_.subscribeCamera(imgTopic, 10, &Registration::imgCallback, this);
    //     cloudSub_ = node_.subscribe(cloudTopic, 10, &Registration::cloudCallback, this);
    //     // imgSub_ = it_.subscribeCamera(imgTopic, 10, &Registration::imgCallback, this);
    //     // cloudSub_ = node_.subscribe("/zed/zed_node/point_cloud/cloud_registered", 10, &Registration::cloudCallback, this);
    // }

    void imgCamCallback(const sensor_msgs::ImageConstPtr& imgMsg, const sensor_msgs::CameraInfoConstPtr& infoMsg){
        cout<<"image info callback"<<endl;

        //! intrinsic parameters.
        // cout<<infoMsg->K[0]<<endl;
        // cout<<infoMsg->K[1]<<endl;
        // cout<<infoMsg->K[2]<<endl;
        // cout<<infoMsg->K[3]<<endl;
        // cout<<infoMsg->K[4]<<endl;
        // cout<<infoMsg->K[5]<<endl;
        // cout<<infoMsg->K[6]<<endl;
        // cout<<infoMsg->K[7]<<endl;
        // cout<<infoMsg->K[8]<<endl;

        //! 获取相机的内参
        K_ << infoMsg->K[0],0,infoMsg->K[2],
            0,infoMsg->K[4],infoMsg->K[5],
            0,0,1;
        // K_ << 677.393,0,620.749,
        //     0,677.393,350.597,
        //     0,0,1;

        P_.resize(3,4);
        P_ << infoMsg->P[0],0,infoMsg->P[2],infoMsg->P[3],
            0,infoMsg->P[5],infoMsg->P[6],infoMsg->P[7],
            0,0,1,0;

        camModel_.fromCameraInfo(infoMsg);
        // cout<<"camera model: "<<camModel_<<endl;

        //! 获取RGB图像，转成opencv格式，并处理后发布出去
        // http://wiki.ros.org/cv_bridge/Tutorials/UsingCvBridgeToConvertBetweenROSImagesAndOpenCVImages
        cv::Mat img;
        cv_bridge::CvImagePtr br;
        try{
            br = cv_bridge::toCvCopy(imgMsg, sensor_msgs::image_encodings::BGR8);
            img = br->image;
            // cout<<"input image size: "<<img.cols<<"  "<<img.rows<<endl;
        }catch(cv_bridge::Exception& ex){
            ROS_ERROR("Failed to convert image!");
            return;
        }

        //! draw markers on image. http://wiki.ros.org/image_geometry/Tutorials/ProjectTfFrameToImage
        cv::circle(img, center_, 10, CV_RGB(255,0,0), -1);
        //! BBX四条边的中点
        cv::circle(img, pp1PixelFrame_, 8, CV_RGB(255,0,0), -1);
        cv::circle(img, pp2PixelFrame_, 8, CV_RGB(0,255,0), -1);
        cv::circle(img, pp3PixelFrame_, 8, CV_RGB(0,0,255), -1);
        cv::circle(img, pp4PixelFrame_, 8, CV_RGB(255,255,0), -1);
        //! ROI
        cv::rectangle(img, roiP1_, roiP2_, CV_RGB(0,255,0), 3, 8, 0);

        //! publish drawn image.
        imgPub_.publish(br->toImageMsg());
    }

    /*
    暂停使用
    */
    void imgCallback(const sensor_msgs::ImageConstPtr& imgMsg){
        // cout<<"image callback"<<endl;

        // http://wiki.ros.org/cv_bridge/Tutorials/UsingCvBridgeToConvertBetweenROSImagesAndOpenCVImages
        cv::Mat img;
        cv_bridge::CvImagePtr br;
        try{
            br = cv_bridge::toCvCopy(imgMsg, sensor_msgs::image_encodings::BGR8);
            img = br->image;
            // cout<<"input image size: "<<img.cols<<"  "<<img.rows<<endl;
        }catch(cv_bridge::Exception& ex){
            ROS_ERROR("Failed to convert image!");
            return;
        }

        //! draw markers on image. http://wiki.ros.org/image_geometry/Tutorials/ProjectTfFrameToImage
        cv::circle(img, center_, 10, CV_RGB(255,0,0), -1);
        //! BBX四条边的中点
        cv::circle(img, pp1PixelFrame_, 8, CV_RGB(255,0,0), -1);
        cv::circle(img, pp2PixelFrame_, 8, CV_RGB(0,255,0), -1);
        cv::circle(img, pp3PixelFrame_, 8, CV_RGB(0,0,255), -1);
        cv::circle(img, pp4PixelFrame_, 8, CV_RGB(255,255,0), -1);
        //! ROI
        cv::rectangle(img, roiP1_, roiP2_, CV_RGB(0,255,0), 3, 8, 0);

        //! publish drawn image.
        imgPub_.publish(br->toImageMsg());
    }

    void cloudCallback(const sensor_msgs::PointCloud2ConstPtr& msg){
        // cout<<"cloud callback"<<endl;
    }

    void poseCallback(const geometry_msgs::PoseStampedConstPtr& msg){
        cout<<"pose callback"<<endl;

        Vector3f p3;
        // p3 << msg->pose.position.x,msg->pose.position.y,msg->pose.position.z;
        // cloud frame(x front) to camera frame(z front)
        p3 << -msg->pose.position.y,-msg->pose.position.z,msg->pose.position.x;
        cout<<"p3 = "<<p3<<endl;
        // Matrix3f K;
        // K << 702.67,0,636.38,
        //     0,702.67,347.11,
        //     0,0,1;

        Vector3f p2;
        // p2 = utility_.project3dTo2d(p3, K_);
        // cout<<"p2 = "<<p2<<endl<<endl;
        // center_.x = p2(0);
        // center_.y = p2(1);

        p2 = utility_.project3dTo2d(p3, P_);
        cout<<"p2 = "<<p2<<endl<<endl;
        center_.x = p2(0);
        center_.y = p2(1);
    }

    void bbxCallback(const jsk_recognition_msgs::BoundingBoxConstPtr& msg){
        Vector3f p3;
        // cloud frame(x front) to camera frame(z front)
        p3 << -msg->pose.position.y,-msg->pose.position.z,msg->pose.position.x;
        cout<<"p3 = "<<p3<<endl;

        Vector3f p2;
        p2 = utility_.project3dTo2d(p3, P_);
        cout<<"p2 = "<<p2<<endl<<endl;
        center_.x = p2(0);
        center_.y = p2(1);

        //! 计算BBX上下及左右边的中点（点云坐标系）
        float heightLeftCenter_z = msg->pose.position.z;
        float heightLeftCenter_y = msg->pose.position.y + 0.5*msg->dimensions.y;
        float heightLeftCenter_x = msg->pose.position.x;
        Vector3f pp1CamFrame; // 相机坐标系
        pp1CamFrame << -heightLeftCenter_y, -heightLeftCenter_z, heightLeftCenter_x;
        Vector3f pp1PixelFrame; // 图像坐标系
        pp1PixelFrame = utility_.project3dTo2d(pp1CamFrame, P_);
        pp1PixelFrame_.x = pp1PixelFrame(0);
        pp1PixelFrame_.y = pp1PixelFrame(1);

        float heightRightCenter_z = msg->pose.position.z;
        float heightRightCenter_y = msg->pose.position.y - 0.5*msg->dimensions.y;
        float heightRightCenter_x = msg->pose.position.x;
        Vector3f pp2CamFrame; // 相机坐标系
        pp2CamFrame << -heightRightCenter_y, -heightRightCenter_z, heightRightCenter_x;
        Vector3f pp2PixelFrame; // 图像坐标系
        pp2PixelFrame = utility_.project3dTo2d(pp2CamFrame, P_);
        pp2PixelFrame_.x = pp2PixelFrame(0);
        pp2PixelFrame_.y = pp2PixelFrame(1);

        float widthTopCenter_z = msg->pose.position.z + 0.5*msg->dimensions.z;
        float widthTopCenter_y = msg->pose.position.y;
        float widthTopCenter_x = msg->pose.position.x;
        Vector3f pp3CamFrame; // 相机坐标系
        pp3CamFrame << -widthTopCenter_y, -widthTopCenter_z, widthTopCenter_x;
        Vector3f pp3PixelFrame; // 图像坐标系
        pp3PixelFrame = utility_.project3dTo2d(pp3CamFrame, P_);
        pp3PixelFrame_.x = pp3PixelFrame(0);
        pp3PixelFrame_.y = pp3PixelFrame(1);

        float widthBottomCenter_z = msg->pose.position.z - 0.5*msg->dimensions.z;
        float widthBottomCenter_y = msg->pose.position.y;
        float widthBottomCenter_x = msg->pose.position.x;
        Vector3f pp4CamFrame; // 相机坐标系
        pp4CamFrame << -widthBottomCenter_y, -widthBottomCenter_z, widthBottomCenter_x;
        Vector3f pp4PixelFrame; // 图像坐标系
        pp4PixelFrame = utility_.project3dTo2d(pp4CamFrame, P_);
        pp4PixelFrame_.x = pp4PixelFrame(0);
        pp4PixelFrame_.y = pp4PixelFrame(1);

        //! ROI(图像坐标系)
        roiP1_.x = pp1PixelFrame_.x;
        roiP1_.y = pp3PixelFrame_.y;

        roiP2_.x = pp2PixelFrame_.x;
        roiP2_.y = pp4PixelFrame_.y;
    }

private:
    Utility utility_;

    cv::Point2d center_;
    cv::Point2d pp1PixelFrame_, pp2PixelFrame_, pp3PixelFrame_, pp4PixelFrame_;
    cv::Point2i roiP1_, roiP2_;

    // # Intrinsic camera matrix for the raw (distorted) images.
    // #     [fx  0 cx]
    // # K = [ 0 fy cy]
    // #     [ 0  0  1]
    // # Projects 3D points in the camera coordinate frame to 2D pixel
    // # coordinates using the focal lengths (fx, fy) and principal point
    // # (cx, cy).
    Matrix3f K_;

    MatrixXf P_;
};

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

    ros::NodeHandle node("~");

    cout<<"Registration node started."<<endl;
    Registration registration(node);
    // registration.initilization();

    ros::spin();
    cout<<"Registration node end."<<endl;

    return 0;
}


text:
// copyright (c) 2009-2014 the dzcoin core developers
// distributed under the mit software license, see the accompanying
// file copying or http://www.opensource.org/licenses/mit-license.php.

#include "core_io.h"

#include "primitives/block.h"
#include "primitives/transaction.h"
#include "script/script.h"
#include "serialize.h"
#include "streams.h"
#include "univalue/univalue.h"
#include "util.h"
#include "utilstrencodings.h"
#include "version.h"

#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/algorithm/string/replace.hpp>
#include <boost/algorithm/string/split.hpp>
#include <boost/assign/list_of.hpp>

using namespace std;

cscript parsescript(const std::string& s)
{
    cscript result;

    static map<string, opcodetype> mapopnames;

    if (mapopnames.empty())
    {
        for (int op = 0; op <= op_nop10; op++)
        {
            // allow op_reserved to get into mapopnames
            if (op < op_nop && op != op_reserved)
                continue;

            const char* name = getopname((opcodetype)op);
            if (strcmp(name, "op_unknown") == 0)
                continue;
            string strname(name);
            mapopnames[strname] = (opcodetype)op;
            // convenience: op_add and just add are both recognized:
            boost::algorithm::replace_first(strname, "op_", "");
            mapopnames[strname] = (opcodetype)op;
        }
    }

    vector<string> words;
    boost::algorithm::split(words, s, boost::algorithm::is_any_of(" \t\n"), boost::algorithm::token_compress_on);

    for (std::vector<std::string>::const_iterator w = words.begin(); w != words.end(); ++w)
    {
        if (w->empty())
        {
            // empty string, ignore. (boost::split given '' will return one word)
        }
        else if (all(*w, boost::algorithm::is_digit()) ||
            (boost::algorithm::starts_with(*w, "-") && all(string(w->begin()+1, w->end()), boost::algorithm::is_digit())))
        {
            // number
            int64_t n = atoi64(*w);
            result << n;
        }
        else if (boost::algorithm::starts_with(*w, "0x") && (w->begin()+2 != w->end()) && ishex(string(w->begin()+2, w->end())))
        {
            // raw hex data, inserted not pushed onto stack:
            std::vector<unsigned char> raw = parsehex(string(w->begin()+2, w->end()));
            result.insert(result.end(), raw.begin(), raw.end());
        }
        else if (w->size() >= 2 && boost::algorithm::starts_with(*w, "'") && boost::algorithm::ends_with(*w, "'"))
        {
            // single-quoted string, pushed as data. note: this is poor-man's
            // parsing, spaces/tabs/newlines in single-quoted strings won't work.
            std::vector<unsigned char> value(w->begin()+1, w->end()-1);
            result << value;
        }
        else if (mapopnames.count(*w))
        {
            // opcode, e.g. op_add or add:
            result << mapopnames[*w];
        }
        else
        {
            throw runtime_error("script parse error");
        }
    }

    return result;
}

bool decodehextx(ctransaction& tx, const std::string& strhextx)
{
    if (!ishex(strhextx))
        return false;

    vector<unsigned char> txdata(parsehex(strhextx));
    cdatastream ssdata(txdata, ser_network, protocol_version);
    try {
        ssdata >> tx;
    }
    catch (const std::exception&) {
        return false;
    }

    return true;
}

bool decodehexblk(cblock& block, const std::string& strhexblk)
{
    if (!ishex(strhexblk))
        return false;

    std::vector<unsigned char> blockdata(parsehex(strhexblk));
    cdatastream ssblock(blockdata, ser_network, protocol_version);
    try {
        ssblock >> block;
    }
    catch (const std::exception&) {
        return false;
    }

    return true;
}

uint256 parsehashuv(const univalue& v, const string& strname)
{
    string strhex;
    if (v.isstr())
        strhex = v.getvalstr();
    return parsehashstr(strhex, strname);  // note: parsehashstr("") throws a runtime_error
}

uint256 parsehashstr(const std::string& strhex, const std::string& strname)
{
    if (!ishex(strhex)) // note: ishex("") is false
        throw runtime_error(strname+" must be hexadecimal string (not '"+strhex+"')");

    uint256 result;
    result.sethex(strhex);
    return result;
}

vector<unsigned char> parsehexuv(const univalue& v, const string& strname)
{
    string strhex;
    if (v.isstr())
        strhex = v.getvalstr();
    if (!ishex(strhex))
        throw runtime_error(strname+" must be hexadecimal string (not '"+strhex+"')");
    return parsehex(strhex);
}

ext: cpp

max_stars_repo_name: dzcoin/DzCoinMiningAlgorithm

max_issues_repo_name: dzcoin/DzCoinMiningAlgorithm

max_forks_repo_name: dzcoin/DzCoinMiningAlgorithm


text:
/*
    This file is part of Mitsuba, a physically based rendering system.

    Copyright (c) 2007-2014 by Wenzel Jakob and others.

    Mitsuba is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License Version 3
    as published by the Free Software Foundation.

    Mitsuba is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program. If not, see <http://www.gnu.org/licenses/>.
*/

#include <mitsuba/core/properties.h>
#include <mitsuba/core/netobject.h>
#include <mitsuba/core/track.h>

/* Keep the boost::variant includes outside of properties.h,
   since they noticeably add to the overall compile times */
#include <boost/variant.hpp>

MTS_NAMESPACE_BEGIN

typedef boost::variant<
    bool, int64_t, Float, Point, Vector, Transform, AnimatedTransform *,
    Spectrum, std::string, Properties::Data> ElementData;

struct PropertyElement {
    ElementData data;
    mutable bool queried;
};

#define DEFINE_PROPERTY_ACCESSOR(Type, BaseType, TypeName, ReadableName) \
    void Properties::set##TypeName(const std::string &name, const Type &value, bool warnDuplicates) { \
        if (hasProperty(name) && warnDuplicates) \
            SLog(EWarn, "Property \"%s\" was specified multiple times!", name.c_str()); \
        (*m_elements)[name].data = (BaseType) value; \
        (*m_elements)[name].queried = false; \
    } \
    \
    Type Properties::get##TypeName(const std::string &name) const { \
        std::map<std::string, PropertyElement>::const_iterator it = m_elements->find(name); \
        if (it == m_elements->end()) \
            SLog(EError, "Property \"%s\" has not been specified!", name.c_str()); \
        const BaseType *result = boost::get<BaseType>(&it->second.data); \
        if (!result) \
            SLog(EError, "The property \"%s\" has the wrong type (expected <" #ReadableName ">). The " \
                    "complete property record is :\n%s", name.c_str(), toString().c_str()); \
        it->second.queried = true; \
        return (Type) *result; \
    } \
    \
    Type Properties::get##TypeName(const std::string &name, const Type &defVal) const { \
        std::map<std::string, PropertyElement>::const_iterator it = m_elements->find(name); \
        if (it == m_elements->end()) \
            return defVal; \
        const BaseType *result = boost::get<BaseType>(&it->second.data); \
        if (!result) \
            SLog(EError, "The property \"%s\" has the wrong type (expected <" #ReadableName ">). The " \
                    "complete property record is :\n%s", name.c_str(), toString().c_str()); \
        it->second.queried = true; \
        return (Type) *result; \
    }

DEFINE_PROPERTY_ACCESSOR(bool, bool, Boolean, boolean)
DEFINE_PROPERTY_ACCESSOR(int64_t, int64_t, Long, integer)
DEFINE_PROPERTY_ACCESSOR(int, int64_t, Integer, integer)
DEFINE_PROPERTY_ACCESSOR(size_t, int64_t, Size, integer)
DEFINE_PROPERTY_ACCESSOR(Float, Float, Float, float)
DEFINE_PROPERTY_ACCESSOR(Point, Point, Point, point)
DEFINE_PROPERTY_ACCESSOR(Vector, Vector, Vector, vector)
DEFINE_PROPERTY_ACCESSOR(Transform, Transform, Transform, transform)
DEFINE_PROPERTY_ACCESSOR(Spectrum, Spectrum, Spectrum, spectrum)
DEFINE_PROPERTY_ACCESSOR(std::string, std::string, String, string)
DEFINE_PROPERTY_ACCESSOR(Properties::Data, Properties::Data, Data, data)

void Properties::setAnimatedTransform(const std::string &name, const AnimatedTransform *value, bool warnDuplicates) {
    if (hasProperty(name)) {
        AnimatedTransform **old = boost::get<AnimatedTransform *>(&((*m_elements)[name].data));
        if (old)
            (*old)->decRef();
        if (warnDuplicates)
            SLog(EWarn, "Property \"%s\" was specified multiple times!", name.c_str());
    }
    (*m_elements)[name].data = (AnimatedTransform *) value;
    (*m_elements)[name].queried = false;
    value->incRef();
}

ref<const AnimatedTransform> Properties::getAnimatedTransform(const std::string &name) const {
    std::map<std::string, PropertyElement>::const_iterator it = m_elements->find(name);
    if (it == m_elements->end())
        SLog(EError, "Property \"%s\" missing", name.c_str());
    const AnimatedTransform * const * result1 = boost::get<AnimatedTransform *>(&it->second.data);
    const Transform *result2 = boost::get<Transform>(&it->second.data);

    if (!result1 && !result2)
        SLog(EError, "The property \"%s\" has the wrong type (expected <animation> or <transform>). The "
                "complete property record is :\n%s", name.c_str(), toString().c_str());
    it->second.queried = true;

    if (result1)
        return *result1;
    else
        return new AnimatedTransform(*result2);
}

ref<const AnimatedTransform> Properties::getAnimatedTransform(const std::string &name, const AnimatedTransform *defVal) const {
    std::map<std::string, PropertyElement>::const_iterator it = m_elements->find(name);
    if (it == m_elements->end())
        return defVal;
    AnimatedTransform * const * result1 = boost::get<AnimatedTransform *>(&it->second.data);
    const Transform *result2 = boost::get<Transform>(&it->second.data);

    if (!result1 && !result2)
        SLog(EError, "The property \"%s\" has the wrong type (expected <animation> or <transform>). The "
                "complete property record is :\n%s", name.c_str(), toString().c_str());

    it->second.queried = true;

    if (result1)
        return *result1;
    else
        return new AnimatedTransform(*result2);
}

ref<const AnimatedTransform> Properties::getAnimatedTransform(const std::string &name, const Transform &defVal) const {
    std::map<std::string, PropertyElement>::const_iterator it = m_elements->find(name);
    if (it == m_elements->end())
        return new AnimatedTransform(defVal);

    AnimatedTransform * const * result1 = boost::get<AnimatedTransform *>(&it->second.data);
    const Transform *result2 = boost::get<Transform>(&it->second.data);

    if (!result1 && !result2)
        SLog(EError, "The property \"%s\" has the wrong type (expected <animation> or <transform>). The "
                "complete property record is :\n%s", name.c_str(), toString().c_str());
    it->second.queried = true;

    if (result1)
        return *result1;
    else
        return new AnimatedTransform(*result2);
}

namespace {
    class TypeVisitor : public boost::static_visitor<Properties::EPropertyType> {
    public:
        Properties::EPropertyType operator()(const bool &) const              { return Properties::EBoolean; }
        Properties::EPropertyType operator()(const int64_t &) const           { return Properties::EInteger; }
        Properties::EPropertyType operator()(const Float &) const             { return Properties::EFloat; }
        Properties::EPropertyType operator()(const Point &) const             { return Properties::EPoint; }
        Properties::EPropertyType operator()(const Vector &) const            { return Properties::EVector; }
        Properties::EPropertyType operator()(const Transform &) const         { return Properties::ETransform; }
        Properties::EPropertyType operator()(const AnimatedTransform *) const { return Properties::EAnimatedTransform; }
        Properties::EPropertyType operator()(const Spectrum &) const          { return Properties::ESpectrum; }
        Properties::EPropertyType operator()(const std::string &) const       { return Properties::EString; }
        Properties::EPropertyType operator()(const Properties::Data &) const  { return Properties::EData; }
    };

    class EqualityVisitor : public boost::static_visitor<bool> {
    public:
        EqualityVisitor(const ElementData *ref) : ref(ref) { }

        bool operator()(const bool &v) const              { const bool *v2 = boost::get<bool>(ref); return v2 ? (v == *v2) : false; }
        bool operator()(const int64_t &v) const           { const int64_t *v2 = boost::get<int64_t>(ref); return v2 ? (v == *v2) : false; }
        bool operator()(const Float &v) const             { const Float *v2 = boost::get<Float>(ref); return v2 ? (v == *v2) : false; }
        bool operator()(const Point &v) const             { const Point *v2 = boost::get<Point>(ref); return v2 ? (v == *v2) : false; }
        bool operator()(const Vector &v) const            { const Vector *v2 = boost::get<Vector>(ref); return v2 ? (v == *v2) : false; }
        bool operator()(const Transform &v) const         { const Transform *v2 = boost::get<Transform>(ref); return v2 ? (v == *v2) : false; }
        bool operator()(const AnimatedTransform *v) const { AnimatedTransform * const *v2 = boost::get<AnimatedTransform*>(ref); return v2 ? (v == *v2) : false; }
        bool operator()(const Spectrum &v) const          { const Spectrum *v2 = boost::get<Spectrum>(ref); return v2 ? (v == *v2) : false; }
        bool operator()(const std::string &v) const       { const std::string *v2 = boost::get<std::string>(ref); return v2 ? (v == *v2) : false; }
        bool operator()(const Properties::Data &v) const  { const Properties::Data *v2 = boost::get<Properties::Data>(ref); return v2 ? (v == *v2) : false; }
    private:
        const ElementData *ref;
    };

    class StringVisitor : public boost::static_visitor<void> {
    public:
        StringVisitor(std::ostringstream &oss, bool quote) : oss(oss), quote(quote) { }

        void operator()(const bool &v) const              { oss << (v ? "true" : "false"); }
        void operator()(const int64_t &v) const           { oss << v; }
        void operator()(const Float &v) const             { oss << v; }
        void operator()(const Point &v) const             { oss << v.toString(); }
        void operator()(const Vector &v) const            { oss << v.toString(); }
        void operator()(const Transform &v) const         { oss << v.toString(); }
        void operator()(const AnimatedTransform *v) const { oss << ((Object *) v)->toString(); }
        void operator()(const Spectrum &v) const          { oss << v.toString(); }
        void operator()(const std::string &v) const       { oss << (quote ? "\"" : "") << v << (quote ? "\"" : ""); }
        void operator()(const Properties::Data &v) const  { oss << v.ptr << " (size=" << v.size << ")"; }
    private:
        std::ostringstream &oss;
        bool quote;
    };
}

Properties::Properties()
: m_id("unnamed") {
    m_elements = new std::map<std::string, PropertyElement>();
}

Properties::Properties(const std::string &pluginName)
: m_pluginName(pluginName), m_id("unnamed") {
    m_elements = new std::map<std::string, PropertyElement>();
}

Properties::Properties(const Properties &props)
: m_pluginName(props.m_pluginName), m_id(props.m_id) {
    m_elements = new std::map<std::string, PropertyElement>(*props.m_elements);

    for (std::map<std::string, PropertyElement>::iterator it = m_elements->begin();
            it != m_elements->end(); ++it) {
        AnimatedTransform **trafo = boost::get<AnimatedTransform *>(&(*it).second.data);
        if (trafo)
            (*trafo)->incRef();
    }
}

Properties::~Properties() {
    for (std::map<std::string, PropertyElement>::iterator it = m_elements->begin();
            it != m_elements->end(); ++it) {
        AnimatedTransform **trafo = boost::get<AnimatedTransform *>(&(*it).second.data);
        if (trafo)
            (*trafo)->decRef();
    }

    delete m_elements;
}

void Properties::operator=(const Properties &props) {
    for (std::map<std::string, PropertyElement>::iterator it = m_elements->begin();
            it != m_elements->end(); ++it) {
        AnimatedTransform **trafo = boost::get<AnimatedTransform *>(&(*it).second.data);
        if (trafo)
            (*trafo)->decRef();
    }

    m_pluginName = props.m_pluginName;
    m_id = props.m_id;
    *m_elements = *props.m_elements;

    for (std::map<std::string, PropertyElement>::iterator it = m_elements->begin();
            it != m_elements->end(); ++it) {
        AnimatedTransform **trafo = boost::get<AnimatedTransform *>(&(*it).second.data);
        if (trafo)
            (*trafo)->incRef();
    }
}

bool Properties::hasProperty(const std::string &name) const {
    return m_elements->find(name) != m_elements->end();
}

bool Properties::removeProperty(const std::string &name) {
    std::map<std::string, PropertyElement>::iterator it = m_elements->find(name);
    if (it == m_elements->end())
        return false;
    AnimatedTransform **trafo = boost::get<AnimatedTransform *>(&(*it).second.data);
    if (trafo)
        (*trafo)->decRef();
    m_elements->erase(it);
    return true;
}

std::vector<std::string> Properties::getUnqueried() const {
    std::map<std::string, PropertyElement>::const_iterator it = m_elements->begin();
    std::vector<std::string> result;

    for (; it != m_elements->end(); ++it) {
        if (!(*it).second.queried)
            result.push_back((*it).first);
    }

    return result;
}

Properties::EPropertyType Properties::getType(const std::string &name) const {
    std::map<std::string, PropertyElement>::const_iterator it = m_elements->find(name);
    if (it == m_elements->end())
        SLog(EError, "Property \"%s\" has not been specified!", name.c_str());

    return boost::apply_visitor(TypeVisitor(), it->second.data);
}

std::string Properties::getAsString(const std::string &name, const std::string &defVal) const {
    if (m_elements->find(name) == m_elements->end())
        return defVal;
    return getAsString(name);
}

std::string Properties::getAsString(const std::string &name) const {
    std::map<std::string, PropertyElement>::const_iterator it = m_elements->find(name);
    if (it == m_elements->end())
        SLog(EError, "Property \"%s\" has not been specified!", name.c_str());

    std::ostringstream oss;
    StringVisitor strVisitor(oss, false);
    boost::apply_visitor(strVisitor, it->second.data);
    it->second.queried = true;

    return oss.str();
}

std::string Properties::toString() const {
    std::map<std::string, PropertyElement>::const_iterator it = m_elements->begin();
    std::ostringstream oss;
    StringVisitor strVisitor(oss, true);

    oss << "Properties[" << endl
        << "  pluginName = \"" << m_pluginName << "\"," << endl
        << "  id = \"" << m_id << "\"," << endl
        << "  elements = {" << endl;
    while (it != m_elements->end()) {
        oss << "    \"" << (*it).first << "\" -> ";
        const ElementData &data = (*it).second.data;
        boost::apply_visitor(strVisitor, data);
        if (++it != m_elements->end())
            oss << ",";
        oss << endl;
    }
    oss << "  }" << endl
        << "]" << endl;
    return oss.str();
}

void Properties::markQueried(const std::string &name) const {
    std::map<std::string, PropertyElement>::const_iterator it = m_elements->find(name);
    if (it == m_elements->end())
        return;
    it->second.queried = true;
}

bool Properties::wasQueried(const std::string &name) const {
    std::map<std::string, PropertyElement>::const_iterator it = m_elements->find(name);
    if (it == m_elements->end())
        SLog(EError, "Could not find parameter \"%s\"!", name.c_str());
    return it->second.queried;
}

void Properties::putPropertyNames(std::vector<std::string> &results) const {
    for (std::map<std::string, PropertyElement>::const_iterator it = m_elements->begin();
            it != m_elements->end(); ++it)
        results.push_back((*it).first);
}

void Properties::copyAttribute(const Properties &properties,
    const std::string &sourceName, const std::string &targetName) {
    std::map<std::string, PropertyElement>::const_iterator it = properties.m_elements->find(sourceName);
    if (it == properties.m_elements->end())
        SLog(EError, "copyAttribute(): Could not find parameter \"%s\"!", sourceName.c_str());
    m_elements->operator[](targetName) = it->second;
}

bool Properties::operator==(const Properties &p) const {
    if (m_pluginName != p.m_pluginName || m_id != p.m_id || m_elements->size() != p.m_elements->size())
        return false;

    std::map<std::string, PropertyElement>::const_iterator it = m_elements->begin();
    for (; it != m_elements->end(); ++it) {
        const PropertyElement &first = it->second;
        const PropertyElement &second = (*p.m_elements)[it->first];

        if (!boost::apply_visitor(EqualityVisitor(&first.data), second.data))
            return false;
    }

    return true;
}

void Properties::merge(const Properties &p) {
    std::map<std::string, PropertyElement>::const_iterator it = p.m_elements->begin();
    for (; it != p.m_elements->end(); ++it)
        (*m_elements)[it->first] = it->second;
}

ConfigurableObject::ConfigurableObject(Stream *stream, InstanceManager *manager)
 : SerializableObject(stream, manager) {
}

void ConfigurableObject::setParent(ConfigurableObject *parent) {
}

void ConfigurableObject::configure() {
}

void ConfigurableObject::serialize(Stream *stream, InstanceManager *manager) const {
    if (!getClass()->isSerializable())
        Log(EError, "Error: trying to serialize an instance of type '%s', which does "
            "not have full serialization support!", getClass()->getName().c_str());
}

void ConfigurableObject::addChild(const std::string &name, ConfigurableObject *child) {
    SLog(EError, "ConfigurableObject::addChild(\"%s\", %s) not implemented in \"%s\"",
        name.c_str(), child->toString().c_str(), toString().c_str());
}

void NetworkedObject::serialize(Stream *stream, InstanceManager *manager) const {
    ConfigurableObject::serialize(stream, manager);
}

void NetworkedObject::bindUsedResources(ParallelProcess *proc) const {
}

void NetworkedObject::wakeup(ConfigurableObject *,
    std::map<std::string, SerializableObject *> &) {
}

MTS_IMPLEMENT_CLASS(ConfigurableObject, true, SerializableObject)
MTS_IMPLEMENT_CLASS(NetworkedObject, true, ConfigurableObject)
MTS_NAMESPACE_END

max_stars_repo_name: anadodik/sdmm-mitsuba

max_issues_repo_name: anadodik/sdmm-mitsuba

max_forks_repo_name: anadodik/sdmm-mitsuba


text:
// Program that can extract features from an image and dump them to a file
//
// Author: Mark Desnoyer (markd@cmu.edu)
// Date: June 2010

#include <boost/filesystem.hpp>
#include <boost/scoped_ptr.hpp>
#include <boost/shared_ptr.hpp>
#include "opencv2/core/core.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/features2d/features2d.hpp"
#include <gflags/gflags.h>
#include <iostream>
#include <fstream>
#include <ros/ros.h>
#include <string>

#include "cv_blobs/BlobResult-Inline.h"
#include "cv_blobs/Blob.h"
#include "ImageDescriptor-Inl.h"
#include "ImageDescriptorGenerator-Inl.h"
#include "SIFTDescriptorGenerator.h"
#include "ImageDescriptorGeneratorFlags.h"

using namespace species_id;
using namespace std;
using namespace boost;
using namespace cv;
using namespace cv_blobs;
namespace fs = boost::filesystem;

// -------- Define the command line options  ------------

// The input and output locations
DEFINE_string(input, "", "Input image file to get the features of");
DEFINE_string(output, "","File to output the image descriptor to. "
              "If this is a "
              "blob image, multiple files will be created suffixed by "
              "indicies.");

int main(int argc, char *argv[]) {
  google::SetUsageMessage("Program that extracts features from an image "
                          "and prints them in ascii format to a file.");
  google::ParseCommandLineFlags(&argc, &argv, true);

  // Figure out the keypoint detector and descriptors to use
  VerifyDescriptorFlags();
  scoped_ptr<FeatureDetector> keyGenerator(ChooseFeatureDetector());
  scoped_ptr<ImageDescriptorGenerator<float> > descGenerator(
    ChooseImageDescriptor(keyGenerator.get()));
  ImageDescriptorINRIASerializer<float> serializer;

  // Now open up the input image
  ROS_INFO_STREAM("Extracting descriptors from " << FLAGS_input);
  vector<ImageRegion> masks;
  string imageFn;
  bool isBlobFile = FLAGS_input.rfind(".blob") != string::npos;
  if (isBlobFile) {
    // The file is a blob serialization
    BlobResultSerializer<int> blobReader;
    fstream blobStream(FLAGS_input.c_str(), ios::in);
    shared_ptr<BlobResult<int> > blobs =
      blobReader.Deserialize(blobStream, &imageFn,
                             fs::path(FLAGS_input).parent_path().string());

    for (int i = 0; i < blobs->nBlobs(); ++i) {
      masks.push_back(ImageRegion(*(blobs->GetBlob(i).ToImageRegion())));
    }
  } else {
    // The file is an actual image
    imageFn = FLAGS_input;
  }

  Mat image = imread(imageFn);
  if (image.empty()) {
    ROS_FATAL_STREAM("Could not read the image at file: " << imageFn);
  }

  // Next, create the descriptors of the image
  vector<shared_ptr<
    ImageDescriptorGenerator<float>::DescriptorCollection> >
    descriptors;
  descGenerator->ExtractUsingMasks(image, masks, &descriptors);

  // Finally, print out the descriptors
  for (unsigned int i = 0; i < descriptors.size(); ++i) {
    string outputFn(FLAGS_output);
    if (isBlobFile) {
      outputFn += '.' + lexical_cast<string>(i);
    } else {
      ROS_ASSERT(i == 0);
    }
    // Open the output file to write to
    fstream fileOut(outputFn.c_str(), ios::out | ios::trunc);
    ROS_INFO_STREAM("Writing descriptors to: " << outputFn);

    serializer.Write(fileOut, *(descriptors[i]));
  }

}

ext: cc


text:
#define BOOST_AUTO_TEST_MAIN
#include <boost/test/auto_unit_test.hpp>
#include <boost/test/unit_test_suite.hpp>
#include <boost/test/floating_point_comparison.hpp>
#include <boost/test/test_tools.hpp>

// These rely on boost includes
#include "container_test.h"
#include "vector_test.h"
#include "matrix_test.h"
#include "quaternion_test.h"

BOOST_AUTO_TEST_SUITE(tiny_types);

BOOST_AUTO_TEST_CASE(default_types_testing)
{
  container_test::run<1,1>();
  container_test::run<2,2>();
  container_test::run<4,4>();
  container_test::run<8,8>();
  container_test::run<8,1>();
  container_test::run<1,8>();

  vector_test::run<1>();
  vector_test::run<2>();
  vector_test::run<3>();
  vector_test::run<4>();
  vector_test::run<6>();

  matrix_test::run<1,1>();
  matrix_test::run<2,2>();
  matrix_test::run<3,3>();
  matrix_test::run<4,4>();
  matrix_test::run<6,6>();
  matrix_test::run<3,4>();
  matrix_test::run<4,3>();

  quaternion_test::run();
}

BOOST_AUTO_TEST_SUITE_END();

max_stars_repo_name: diku-dk/PROX

max_issues_repo_name: erleben/matchstick

max_forks_repo_name: erleben/matchstick


text:
/*=============================================================================
    Copyright (c) 2002 2004 2006 Joel de Guzman
    Copyright (c) 2004 Eric Niebler
    http://spirit.sourceforge.net/

    Use, modification and distribution is subject to the Boost Software
    License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
    http://www.boost.org/LICENSE_1_0.txt)
=============================================================================*/
#include "./actions_class.hpp"
#include "../block.hpp"
#include "../doc_info.hpp"
#include "./post_process.hpp"
#include "./utils.hpp"
#include <boost/spirit/iterator/position_iterator.hpp>
#include <boost/program_options.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/filesystem/operations.hpp>
#include <boost/ref.hpp>

#include <stdexcept>
#include <fstream>
#include <iostream>
#include <vector>

#if (defined(BOOST_MSVC) && (BOOST_MSVC <= 1310))
#pragma warning(disable:4355)
#endif

#define QUICKBOOK_VERSION "Quickbook Version 1.4"

namespace quickbook
{
    using namespace boost::spirit;
    namespace fs = boost::filesystem;
    tm* current_time; // the current time
    tm* current_gm_time; // the current UTC time
    bool debug_mode; // for quickbook developers only
    unsigned qbk_major_version = 0;
    unsigned qbk_minor_version = 0;
    unsigned qbk_version_n = 0; // qbk_major_version * 100 + qbk_minor_version
    bool ms_errors = false; // output errors/warnings as if for VS
    std::vector<std::string> include_path;

    ///////////////////////////////////////////////////////////////////////////
    //
    //  Parse a file
    //
    ///////////////////////////////////////////////////////////////////////////
    int
    parse(char const* filein_, actions& actor, bool ignore_docinfo)
    {
        using std::cerr;
        using std::vector;
        using std::string;

        std::string storage;
        int err = detail::load(filein_, storage);
        if (err != 0)
            return err;

        typedef position_iterator<std::string::const_iterator> iterator_type;
        iterator_type first(storage.begin(), storage.end(), filein_);
        iterator_type last(storage.end(), storage.end());

        doc_info_grammar<actions> l(actor);
        parse_info<iterator_type> info = parse(first, last, l);

        if (info.hit || ignore_docinfo)
        {
            pre(actor.out, actor, ignore_docinfo);

            block_grammar<actions> g(actor);
            info = parse(info.hit ? info.stop : first, last, g);
            if (info.full)
            {
                post(actor.out, actor, ignore_docinfo);
            }
        }

        if (!info.full)
        {
            file_position const pos = info.stop.get_position();
            detail::outerr(pos.file,pos.line)
                << "Syntax Error near column " << pos.column << ".\n";
            return 1;
        }

        return 0;
    }

    static int
    parse(char const* filein_, fs::path const& outdir, string_stream& out, bool ignore_docinfo = false)
    {
        actions actor(filein_, outdir, out);
        bool r = parse(filein_, actor);
        if (actor.section_level != 0)
            detail::outwarn(filein_,1)
                << "Warning missing [endsect] detected at end of file."
                << std::endl;
        return r;
    }

    static int
    parse(
        char const* filein_
      , char const* fileout_
      , int indent
      , int linewidth
      , bool pretty_print)
    {
        int result = 0;
        std::ofstream fileout(fileout_);
        fs::path outdir = fs::path(fileout_, fs::native).branch_path();
        if (outdir.empty())
            outdir = ".";
        if (pretty_print)
        {
            string_stream buffer;
            result = parse(filein_, outdir, buffer);
            if (result == 0)
            {
                post_process(buffer.str(), fileout, indent, linewidth);
            }
        }
        else
        {
            string_stream buffer;
            result = parse(filein_, outdir, buffer);
            fileout << buffer.str();
        }
        return result;
    }
}

///////////////////////////////////////////////////////////////////////////
//
//  Main program
//
///////////////////////////////////////////////////////////////////////////
int
main(int argc, char* argv[])
{
    try
    {
        using boost::program_options::options_description;
        using boost::program_options::variables_map;
        using boost::program_options::store;
        using boost::program_options::parse_command_line;
        using boost::program_options::command_line_parser;
        using boost::program_options::notify;
        using boost::program_options::value;
        using boost::program_options::positional_options_description;

        // First thing, the filesystem should record the current working directory.
        boost::filesystem::initial_path();

        options_description desc("Allowed options");
        desc.add_options()
            ("help", "produce help message")
            ("version", "print version string")
            ("no-pretty-print", "disable XML pretty printing")
            ("indent", value<int>(), "indent spaces")
            ("linewidth", value<int>(), "line width")
            ("input-file", value<std::string>(), "input file")
            ("output-file", value<std::string>(), "output file")
            ("debug", "debug mode (for developers)")
            ("ms-errors", "use Microsoft Visual Studio style error & warn message format")
            ("include-path,I", value< std::vector<std::string> >(), "include path")
        ;

        positional_options_description p;
        p.add("input-file", -1);

        variables_map vm;
        int indent = -1;
        int linewidth = -1;
        bool pretty_print = true;
        store(command_line_parser(argc, argv).options(desc).positional(p).run(), vm);
        notify(vm);

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

        if (vm.count("version"))
        {
            std::cout << QUICKBOOK_VERSION << std::endl;
            return 0;
        }

        if (vm.count("ms-errors"))
            quickbook::ms_errors = true;

        if (vm.count("no-pretty-print"))
            pretty_print = false;

        if (vm.count("indent"))
            indent = vm["indent"].as<int>();

        if (vm.count("linewidth"))
            linewidth = vm["linewidth"].as<int>();

        if (vm.count("debug"))
        {
            static tm timeinfo;
            timeinfo.tm_year = 2000 - 1900;
            timeinfo.tm_mon = 12 - 1;
            timeinfo.tm_mday = 20;
            timeinfo.tm_hour = 12;
            timeinfo.tm_min = 0;
            timeinfo.tm_sec = 0;
            timeinfo.tm_isdst = -1;
            mktime(&timeinfo);
            quickbook::current_time = &timeinfo;
            quickbook::current_gm_time = &timeinfo;
            quickbook::debug_mode = true;
        }
        else
        {
            time_t t = std::time(0);
            static tm lt = *localtime(&t);
            static tm gmt = *gmtime(&t);
            quickbook::current_time = <
            quickbook::current_gm_time = &gmt;
            quickbook::debug_mode = false;
        }

        if (vm.count("include-path"))
        {
            quickbook::include_path = vm["include-path"].as< std::vector<std::string> >();
        }

        if (vm.count("input-file"))
        {
            std::string filein = vm["input-file"].as<std::string>();
            std::string fileout;

            if (vm.count("output-file"))
            {
                fileout = vm["output-file"].as<std::string>();
            }
            else
            {
                fileout = quickbook::detail::remove_extension(filein.c_str());
                fileout += ".xml";
            }

            std::cout << "Generating Output File: "
                << fileout
                << std::endl;

            return quickbook::parse(filein.c_str(), fileout.c_str(), indent, linewidth, pretty_print);
        }
        else
        {
            quickbook::detail::outerr("",0) << "Error: No filename given" << std::endl;
        }
    }

    catch(std::exception& e)
    {
        quickbook::detail::outerr("",0) << "Error: " << e.what() << "\n";
        return 1;
    }

    catch(...)
    {
        quickbook::detail::outerr("",0) << "Error: Exception of unknown type caught\n";
    }

    return 0;
}


text:
/*
 * Copyright (c) 2011-2013 libbitcoin developers (see AUTHORS)
 *
 * This file is part of libbitcoin.
 *
 * libbitcoin is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License with
 * additional permissions to the one published by the Free Software
 * Foundation, either version 3 of the License, or (at your option)
 * any later version. For more information see LICENSE.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
#ifndef LIBBITCOIN_NET_CHANNEL_HPP
#define LIBBITCOIN_NET_CHANNEL_HPP

#include <boost/asio.hpp>
#include <boost/array.hpp>
#include <boost/utility.hpp>
#include <boost/asio/streambuf.hpp>
#include <atomic>
#include <cstdint>
#include <memory>
#include <mutex>
#include <stack>

#include <bitcoin/network/network.hpp>
#include <bitcoin/network/shared_const_buffer.hpp>
#include <bitcoin/primitives.hpp>
#include <bitcoin/format.hpp>
#include <bitcoin/satoshi_serialize.hpp>
#include <bitcoin/utility/assert.hpp>
#include <bitcoin/utility/logger.hpp>
#include <bitcoin/utility/serializer.hpp>
#include <bitcoin/utility/subscriber.hpp>

namespace libbitcoin {

template <typename Message>
data_chunk create_raw_message(const Message& packet)
{
    data_chunk payload(satoshi_raw_size(packet));
    satoshi_save(packet, payload.begin());
    // Make the header packet and serialise it
    header_type head;
    head.magic = magic_value();
    head.command = satoshi_command(packet);
    head.payload_length = payload.size();
    head.checksum = generate_sha256_checksum(payload);
    data_chunk raw_header(satoshi_raw_size(head));
    satoshi_save(head, raw_header.begin());
    // Construct completed packet with header + payload
    data_chunk whole_message = raw_header;
    extend_data(whole_message, payload);
    // Probably not the right place for this
    // Networking output in an exporter
    log_debug(LOG_NETWORK) << "s: " << head.command
        << " (" << payload.size() << " bytes)";
    return whole_message;
}

class channel_loader_module_base
{
public:
    virtual ~channel_loader_module_base() {}
    virtual void attempt_load(const data_chunk& stream) const = 0;
    virtual const std::string lookup_symbol() const = 0;
};

class channel_stream_loader
{
public:
    ~channel_stream_loader();
    void add(channel_loader_module_base* module);
    void load_lookup(const std::string& symbol,
        const data_chunk& stream) const;
private:
    typedef std::vector<channel_loader_module_base*> module_list;

    module_list modules_;
};

class channel_proxy
  : public std::enable_shared_from_this<channel_proxy>
{
public:
    typedef std::function<void (const std::error_code&)> send_handler;

    typedef std::function<void (const std::error_code&,
        const version_type&)> receive_version_handler;

    typedef std::function<void (const std::error_code&,
        const verack_type&)> receive_verack_handler;

    typedef std::function<void (const std::error_code&,
        const address_type&)> receive_address_handler;

    typedef std::function<void (const std::error_code&,
        const get_address_type&)> receive_get_address_handler;

    typedef std::function<void (const std::error_code&,
        const inventory_type&)> receive_inventory_handler;

    typedef std::function<void (const std::error_code&,
        const get_data_type&)> receive_get_data_handler;

    typedef std::function<void (const std::error_code&,
        const get_blocks_type&)> receive_get_blocks_handler;

    typedef std::function<void (const std::error_code&,
        const transaction_type&)> receive_transaction_handler;

    typedef std::function<void (const std::error_code&,
        const block_type&)> receive_block_handler;

    typedef std::function<void (const std::error_code&,
        const header_type&, const data_chunk&)> receive_raw_handler;

    typedef std::function<void (const std::error_code&)> stop_handler;

    channel_proxy(threadpool& pool, socket_ptr socket);
    ~channel_proxy();

    channel_proxy(const channel_proxy&) = delete;
    void operator=(const channel_proxy&) = delete;

    void start();
    void stop();
    bool stopped() const;

    // List of bitcoin messages
    // version
    // verack
    // addr
    // getaddr
    // inv
    // getdata
    // getblocks
    // tx
    // block
    // getheaders   [unused]
    // headers      [unused]
    // checkorder   [deprecated]
    // submitorder  [deprecated]
    // reply        [deprecated]
    // ping         [internal]
    // alert        [not supported]

    template <typename Message>
    void send(const Message& packet, send_handler handle_send)
    {
        if (stopped_)
            handle_send(error::service_stopped);
        else
        {
            auto this_ptr = shared_from_this();
            strand_.post(
                [this, this_ptr, packet, handle_send]
                {
                    do_send_common(create_raw_message(packet),
                        handle_send);
                });
        }
    }
    void send_raw(const header_type& packet_header,
        const data_chunk& payload, send_handler handle_send);

    void subscribe_version(receive_version_handler handle_receive);
    void subscribe_verack(receive_verack_handler handle_receive);
    void subscribe_address(receive_address_handler handle_receive);
    void subscribe_get_address(receive_get_address_handler handle_receive);
    void subscribe_inventory(receive_inventory_handler handle_receive);
    void subscribe_get_data(receive_get_data_handler handle_receive);
    void subscribe_get_blocks(receive_get_blocks_handler handle_receive);
    void subscribe_transaction(receive_transaction_handler handle_receive);
    void subscribe_block(receive_block_handler handle_receive);
    void subscribe_raw(receive_raw_handler handle_receive);

    void subscribe_stop(stop_handler handle_stop);
    std::string get_remote_endpoint();

private:
    typedef subscriber<const std::error_code&, const version_type&>
        version_subscriber_type;
    typedef subscriber<const std::error_code&, const verack_type&>
        verack_subscriber_type;
    typedef subscriber<const std::error_code&, const address_type&>
        address_subscriber_type;
    typedef subscriber<const std::error_code&, const get_address_type&>
        get_address_subscriber_type;
    typedef subscriber<const std::error_code&, const inventory_type&>
        inventory_subscriber_type;
    typedef subscriber<const std::error_code&, const get_data_type&>
        get_data_subscriber_type;
    typedef subscriber<const std::error_code&, const get_blocks_type&>
        get_blocks_subscriber_type;
    typedef subscriber<const std::error_code&, const transaction_type&>
        transaction_subscriber_type;
    typedef subscriber<const std::error_code&, const block_type&>
        block_subscriber_type;

    typedef subscriber<const std::error_code&,
        const header_type&, const data_chunk&> raw_subscriber_type;
    typedef subscriber<const std::error_code&> stop_subscriber_type;

    void do_send_raw(const header_type& packet_header,
        const data_chunk& payload, send_handler handle_send);
    void do_send_common(const data_chunk& whole_message,
        send_handler handle_send);

    template <typename Message, typename Callback, typename SubscriberPtr>
    void generic_subscribe(Callback handle_message,
        SubscriberPtr message_subscribe)
    {
        // Subscribing must be immediate. We cannot switch thread contexts
        if (stopped_)
            handle_message(error::service_stopped, Message());
        else
            message_subscribe->subscribe(handle_message);
    }

    void read_header();
    void read_checksum(const header_type& header_msg);
    void read_payload(const header_type& header_msg);

    void handle_read_header(const boost::system::error_code& ec,
        size_t bytes_transferred);
    void handle_read_checksum(const boost::system::error_code& ec,
        size_t bytes_transferred, header_type& header_msg);
    void handle_read_payload(const boost::system::error_code& ec,
        size_t bytes_transferred, const header_type& header_msg);

    // Calls the send handler after a successful send, translating
    // the boost error_code to std::error_code
    void call_handle_send(const boost::system::error_code& ec,
        send_handler handle_send);

    void handle_timeout(const boost::system::error_code& ec);
    void handle_heartbeat(const boost::system::error_code& ec);

    void set_timeout(const boost::posix_time::time_duration timeout);
    void set_heartbeat(const boost::posix_time::time_duration timeout);
    void reset_timers();

    bool problems_check(const boost::system::error_code& ec);
    void stop_impl();
    void clear_subscriptions();

    io_service::strand strand_;
    socket_ptr socket_;
    // We keep the service alive for lifetime rules
    boost::asio::deadline_timer timeout_, heartbeat_;
    std::atomic<bool> stopped_;

    channel_stream_loader loader_;

    // Header minus checksum is 4 + 12 + 4 = 20 bytes
    static constexpr size_t header_chunk_size = 20;
    // Checksum size is 4 bytes
    static constexpr size_t header_checksum_size = 4;

    boost::array<uint8_t, header_chunk_size> inbound_header_;
    boost::array<uint8_t, header_checksum_size> inbound_checksum_;
    std::vector<uint8_t> inbound_payload_;

    // We should be using variadic templates for these
    version_subscriber_type::ptr version_subscriber_;
    verack_subscriber_type::ptr verack_subscriber_;
    address_subscriber_type::ptr address_subscriber_;
    get_address_subscriber_type::ptr get_address_subscriber_;
    inventory_subscriber_type::ptr inventory_subscriber_;
    get_data_subscriber_type::ptr get_data_subscriber_;
    get_blocks_subscriber_type::ptr get_blocks_subscriber_;
    transaction_subscriber_type::ptr transaction_subscriber_;
    block_subscriber_type::ptr block_subscriber_;

    raw_subscriber_type::ptr raw_subscriber_;
    stop_subscriber_type::ptr stop_subscriber_;
};

class channel
{
public:
    typedef std::shared_ptr<channel_proxy> channel_proxy_ptr;

    channel(channel_proxy_ptr proxy);
    ~channel();

    void stop();
    bool stopped() const;

    template <typename Message>
    void send(const Message& packet,
        channel_proxy::send_handler handle_send)
    {
        channel_proxy_ptr proxy = weak_proxy_.lock();
        if (!proxy)
            handle_send(error::service_stopped);
        else
            proxy->send(packet, handle_send);
    }

    void send_raw(const header_type& packet_header,
        const data_chunk& payload, channel_proxy::send_handler handle_send);

    void subscribe_version(
        channel_proxy::receive_version_handler handle_receive);
    void subscribe_verack(
        channel_proxy::receive_verack_handler handle_receive);
    void subscribe_address(
        channel_proxy::receive_address_handler handle_receive);
    void subscribe_get_address(
        channel_proxy::receive_get_address_handler handle_receive);
    void subscribe_inventory(
        channel_proxy::receive_inventory_handler handle_receive);
    void subscribe_get_data(
        channel_proxy::receive_get_data_handler handle_receive);
    void subscribe_get_blocks(
        channel_proxy::receive_get_blocks_handler handle_receive);
    void subscribe_transaction(
        channel_proxy::receive_transaction_handler handle_receive);
    void subscribe_block(
        channel_proxy::receive_block_handler handle_receive);
    void subscribe_raw(
        channel_proxy::receive_raw_handler handle_receive);

    void subscribe_stop(
        channel_proxy::stop_handler handle_stop);
    std::string get_remote_endpoint();

private:
    std::weak_ptr<channel_proxy> weak_proxy_;
};

} // namespace libbitcoin

#endif

ext: hpp

max_stars_repo_name: mousewu/bcclient

max_issues_repo_name: mousewu/bcclient

max_forks_repo_name: mousewu/bcclient


text:
#include <iostream>

/*Enable following line to use Boost threads */
#define USE_BOOST

#ifdef USE_BOOST
    #include <boost/thread.hpp>
    #define THRD boost::thread
    #define USING_THRD_LIB "Using Boost Threads"
#else
    #include <thread>
    #define THRD std::thread
    #define USING_THRD_LIB "Using Std Threads"
#endif

class Task
{
public:
    void execute(std::string command)
    {
        for(int i = 0; i < 5; i++)
        {
            std::cout<<command<<" :: "<<i<<std::endl;
        }
    }

    static void stMemFn(std::string command)
    {
        for(int i = 0; i < 5; i++)
        {
            std::cout<<command<<" :: "<<i<<std::endl;
        }
    }
};

int main()
{
    std::cout << USING_THRD_LIB << std::endl;
    Task * taskPtr = new Task();
    // Create a thread using member function
    THRD th(&Task::execute, taskPtr, "Task w/ Member Function");
    th.join();
    delete taskPtr;

    // Create a thread using static function
    THRD th1(&Task::stMemFn, "Task w/ Static Function");
    th1.join();
    return 0;
}


text:
#include <iostream>
#include <boost/python.hpp>
#include "pyprx/planning/planners/planner_py.hpp"
// #include "pyprx/planning/planners/hyb_aorrt2_stride_py.hpp"
#include "pyprx/planning/planners/rrt_py.hpp"
#include "pyprx/planning/planners/sst_py.hpp"
#include "pyprx/planning/planners/dirt_py.hpp"

using namespace boost::python;
void pyprx_planning_planners_py()
{
	pyprx_planning_planners_planner_py();
	pyprx_planning_planners_rrt_py();
	pyprx_planning_planners_sst_py();
	pyprx_planning_planners_dirt_py();
   	// pyprx_planning_planners_hyb_aorrt2_stride_py();
}


text:
// Copyright (c) 2020-2021 Antony Polukhin
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#include <boost/pfr/core.hpp>

#include <memory>

#include <boost/core/lightweight_test.hpp>

struct unique_ptrs {
    std::unique_ptr<int> p1;
    std::unique_ptr<int> p2;
};

void test_get_rvalue() {
    unique_ptrs x {
        std::make_unique<int>(42),
        std::make_unique<int>(43),
    };

    auto p = boost::pfr::get<0>(std::move(x));
    BOOST_TEST_EQ(*p, 42);
}

int main() {
    test_get_rvalue();

    return boost::report_errors();
}


text:
#include <iostream>
#include <future>
#include <fstream>
#include <map>
#include <cstring>
#include <boost/filesystem.hpp>

using namespace boost::filesystem;

class scheduler_t {
        std::vector<std::packaged_task<bool()> > v_task;
        std::vector<std::packaged_task<bool()> >::iterator iter;
    public:
        void add( std::packaged_task<bool()> & _task ) {
            v_task.push_back( std::move(_task) );
        }
        void run() {
            for(iter = v_task.begin(); iter != v_task.end(); iter++) {
                (*iter)();
            }
        }
        scheduler_t() {}
        ~scheduler_t() {}
};


text:
#include <boost/test/unit_test.hpp>
#include "instruments/histogram.hpp"
#include "instruments/timer.hpp"
#include <chrono>

BOOST_AUTO_TEST_CASE(histogram_test){
	metrics::instruments::histogram h;
	using metrics::instruments::scoped_timer;
	scoped_timer<>::duration local_duration;
	scoped_timer<>([&](const scoped_timer<>::duration& time){local_duration = time;});
}

max_stars_repo_name: andrew-murray/cpp-metrics

max_issues_repo_name: andrew-murray/cpp-metrics

max_forks_repo_name: andrew-murray/cpp-metrics


text:
//               Copyright Marek Dalewski 2017
// Distributed under the Boost Software License, Version 1.0.
//        (See accompanying file LICENSE.md or copy at
//           http://www.boost.org/LICENSE_1_0.txt)

#include <commander/detail__type_traits/is_character_like.hpp>

#include <boost/test/unit_test.hpp>

#include "character_helpers.hpp"

BOOST_AUTO_TEST_CASE( is_character_like )
{
    namespace comd = commander::detail;

    static_assert( comd::is_character_like<             bool  >::value);
    static_assert( comd::is_character_like<const        bool  >::value);
    static_assert( comd::is_character_like<             bool& >::value);
    static_assert( comd::is_character_like<const        bool& >::value);
    static_assert( comd::is_character_like<             bool&&>::value);
    static_assert( comd::is_character_like<const        bool&&>::value);
    static_assert( comd::is_character_like<             char  >::value);
    static_assert( comd::is_character_like<const        char  >::value);
    static_assert( comd::is_character_like<             char& >::value);
    static_assert( comd::is_character_like<const        char& >::value);
    static_assert( comd::is_character_like<             char&&>::value);
    static_assert( comd::is_character_like<const        char&&>::value);
    static_assert( comd::is_character_like<           int8_t  >::value);
    static_assert( comd::is_character_like<const      int8_t  >::value);
    static_assert( comd::is_character_like<           int8_t& >::value);
    static_assert( comd::is_character_like<const      int8_t& >::value);
    static_assert( comd::is_character_like<           int8_t&&>::value);
    static_assert( comd::is_character_like<const      int8_t&&>::value);
    static_assert( comd::is_character_like<          uint8_t  >::value);
    static_assert( comd::is_character_like<const     uint8_t  >::value);
    static_assert( comd::is_character_like<          uint8_t& >::value);
    static_assert( comd::is_character_like<const     uint8_t& >::value);
    static_assert( comd::is_character_like<          uint8_t&&>::value);
    static_assert( comd::is_character_like<const     uint8_t&&>::value);
    static_assert( comd::is_character_like<          int16_t  >::value);
    static_assert( comd::is_character_like<const     int16_t  >::value);
    static_assert( comd::is_character_like<          int16_t& >::value);
    static_assert( comd::is_character_like<const     int16_t& >::value);
    static_assert( comd::is_character_like<          int16_t&&>::value);
    static_assert( comd::is_character_like<const     int16_t&&>::value);
    static_assert( comd::is_character_like<         uint16_t  >::value);
    static_assert( comd::is_character_like<const    uint16_t  >::value);
    static_assert( comd::is_character_like<         uint16_t& >::value);
    static_assert( comd::is_character_like<const    uint16_t& >::value);
    static_assert( comd::is_character_like<         uint16_t&&>::value);
    static_assert( comd::is_character_like<const    uint16_t&&>::value);
    static_assert( comd::is_character_like<         char16_t  >::value);
    static_assert( comd::is_character_like<const    char16_t  >::value);
    static_assert( comd::is_character_like<         char16_t& >::value);
    static_assert( comd::is_character_like<const    char16_t& >::value);
    static_assert( comd::is_character_like<         char16_t&&>::value);
    static_assert( comd::is_character_like<const    char16_t&&>::value);
    static_assert( comd::is_character_like<          int32_t  >::value);
    static_assert( comd::is_character_like<const     int32_t  >::value);
    static_assert( comd::is_character_like<          int32_t& >::value);
    static_assert( comd::is_character_like<const     int32_t& >::value);
    static_assert( comd::is_character_like<          int32_t&&>::value);
    static_assert( comd::is_character_like<const     int32_t&&>::value);
    static_assert( comd::is_character_like<         uint32_t  >::value);
    static_assert( comd::is_character_like<const    uint32_t  >::value);
    static_assert( comd::is_character_like<         uint32_t& >::value);
    static_assert( comd::is_character_like<const    uint32_t& >::value);
    static_assert( comd::is_character_like<         uint32_t&&>::value);
    static_assert( comd::is_character_like<const    uint32_t&&>::value);
    static_assert( comd::is_character_like<         char32_t  >::value);
    static_assert( comd::is_character_like<const    char32_t  >::value);
    static_assert( comd::is_character_like<         char32_t& >::value);
    static_assert( comd::is_character_like<const    char32_t& >::value);
    static_assert( comd::is_character_like<         char32_t&&>::value);
    static_assert( comd::is_character_like<const    char32_t&&>::value);
    static_assert( comd::is_character_like<          wchar_t  >::value);
    static_assert( comd::is_character_like<const     wchar_t  >::value);
    static_assert( comd::is_character_like<          wchar_t& >::value);
    static_assert( comd::is_character_like<const     wchar_t& >::value);
    static_assert( comd::is_character_like<          wchar_t&&>::value);
    static_assert( comd::is_character_like<const     wchar_t&&>::value);
    static_assert( comd::is_character_like<          int64_t  >::value);
    static_assert( comd::is_character_like<const     int64_t  >::value);
    static_assert( comd::is_character_like<          int64_t& >::value);
    static_assert( comd::is_character_like<const     int64_t& >::value);
    static_assert( comd::is_character_like<          int64_t&&>::value);
    static_assert( comd::is_character_like<const     int64_t&&>::value);
    static_assert( comd::is_character_like<         uint64_t  >::value);
    static_assert( comd::is_character_like<const    uint64_t  >::value);
    static_assert( comd::is_character_like<         uint64_t& >::value);
    static_assert( comd::is_character_like<const    uint64_t& >::value);
    static_assert( comd::is_character_like<         uint64_t&&>::value);
    static_assert( comd::is_character_like<const    uint64_t&&>::value);
    static_assert( comd::is_character_like<            float  >::value);
    static_assert( comd::is_character_like<const       float  >::value);
    static_assert( comd::is_character_like<            float& >::value);
    static_assert( comd::is_character_like<const       float& >::value);
    static_assert( comd::is_character_like<            float&&>::value);
    static_assert( comd::is_character_like<const       float&&>::value);
    static_assert( comd::is_character_like<           double  >::value);
    static_assert( comd::is_character_like<const      double  >::value);
    static_assert( comd::is_character_like<           double& >::value);
    static_assert( comd::is_character_like<const      double& >::value);
    static_assert( comd::is_character_like<           double&&>::value);
    static_assert( comd::is_character_like<const      double&&>::value);
    static_assert( comd::is_character_like<      long double  >::value);
    static_assert( comd::is_character_like<const long double  >::value);
    static_assert( comd::is_character_like<      long double& >::value);
    static_assert( comd::is_character_like<const long double& >::value);
    static_assert( comd::is_character_like<      long double&&>::value);
    static_assert( comd::is_character_like<const long double&&>::value);

    static_assert( comd::is_character_like<      some_char  >::value);
    static_assert( comd::is_character_like<const some_char  >::value);
    static_assert( comd::is_character_like<      some_char& >::value);
    static_assert( comd::is_character_like<const some_char& >::value);
    static_assert( comd::is_character_like<      some_char&&>::value);
    static_assert( comd::is_character_like<const some_char&&>::value);

    static_assert(!comd::is_character_like<      non_char_constr  >::value);
    static_assert(!comd::is_character_like<const non_char_constr  >::value);
    static_assert(!comd::is_character_like<      non_char_constr& >::value);
    static_assert(!comd::is_character_like<const non_char_constr& >::value);
    static_assert(!comd::is_character_like<      non_char_constr&&>::value);
    static_assert(!comd::is_character_like<const non_char_constr&&>::value);

    static_assert(!comd::is_character_like<      non_const_comp_char  >::value);
    static_assert(!comd::is_character_like<const non_const_comp_char  >::value);
    static_assert(!comd::is_character_like<      non_const_comp_char& >::value);
    static_assert(!comd::is_character_like<const non_const_comp_char& >::value);
    static_assert(!comd::is_character_like<      non_const_comp_char&&>::value);
    static_assert(!comd::is_character_like<const non_const_comp_char&&>::value);

    static_assert(!comd::is_character_like<      non_char  >::value);
    static_assert(!comd::is_character_like<const non_char  >::value);
    static_assert(!comd::is_character_like<      non_char& >::value);
    static_assert(!comd::is_character_like<const non_char& >::value);
    static_assert(!comd::is_character_like<      non_char&&>::value);
    static_assert(!comd::is_character_like<const non_char&&>::value);
}

BOOST_AUTO_TEST_CASE( is_character_like_v )
{
    namespace comd = commander::detail;

    static_assert( comd::is_character_like_v<             bool  >);
    static_assert( comd::is_character_like_v<const        bool  >);
    static_assert( comd::is_character_like_v<             bool& >);
    static_assert( comd::is_character_like_v<const        bool& >);
    static_assert( comd::is_character_like_v<             bool&&>);
    static_assert( comd::is_character_like_v<const        bool&&>);
    static_assert( comd::is_character_like_v<             char  >);
    static_assert( comd::is_character_like_v<const        char  >);
    static_assert( comd::is_character_like_v<             char& >);
    static_assert( comd::is_character_like_v<const        char& >);
    static_assert( comd::is_character_like_v<             char&&>);
    static_assert( comd::is_character_like_v<const        char&&>);
    static_assert( comd::is_character_like_v<           int8_t  >);
    static_assert( comd::is_character_like_v<const      int8_t  >);
    static_assert( comd::is_character_like_v<           int8_t& >);
    static_assert( comd::is_character_like_v<const      int8_t& >);
    static_assert( comd::is_character_like_v<           int8_t&&>);
    static_assert( comd::is_character_like_v<const      int8_t&&>);
    static_assert( comd::is_character_like_v<          uint8_t  >);
    static_assert( comd::is_character_like_v<const     uint8_t  >);
    static_assert( comd::is_character_like_v<          uint8_t& >);
    static_assert( comd::is_character_like_v<const     uint8_t& >);
    static_assert( comd::is_character_like_v<          uint8_t&&>);
    static_assert( comd::is_character_like_v<const     uint8_t&&>);
    static_assert( comd::is_character_like_v<          int16_t  >);
    static_assert( comd::is_character_like_v<const     int16_t  >);
    static_assert( comd::is_character_like_v<          int16_t& >);
    static_assert( comd::is_character_like_v<const     int16_t& >);
    static_assert( comd::is_character_like_v<          int16_t&&>);
    static_assert( comd::is_character_like_v<const     int16_t&&>);
    static_assert( comd::is_character_like_v<         uint16_t  >);
    static_assert( comd::is_character_like_v<const    uint16_t  >);
    static_assert( comd::is_character_like_v<         uint16_t& >);
    static_assert( comd::is_character_like_v<const    uint16_t& >);
    static_assert( comd::is_character_like_v<         uint16_t&&>);
    static_assert( comd::is_character_like_v<const    uint16_t&&>);
    static_assert( comd::is_character_like_v<         char16_t  >);
    static_assert( comd::is_character_like_v<const    char16_t  >);
    static_assert( comd::is_character_like_v<         char16_t& >);
    static_assert( comd::is_character_like_v<const    char16_t& >);
    static_assert( comd::is_character_like_v<         char16_t&&>);
    static_assert( comd::is_character_like_v<const    char16_t&&>);
    static_assert( comd::is_character_like_v<          int32_t  >);
    static_assert( comd::is_character_like_v<const     int32_t  >);
    static_assert( comd::is_character_like_v<          int32_t& >);
    static_assert( comd::is_character_like_v<const     int32_t& >);
    static_assert( comd::is_character_like_v<          int32_t&&>);
    static_assert( comd::is_character_like_v<const     int32_t&&>);
    static_assert( comd::is_character_like_v<         uint32_t  >);
    static_assert( comd::is_character_like_v<const    uint32_t  >);
    static_assert( comd::is_character_like_v<         uint32_t& >);
    static_assert( comd::is_character_like_v<const    uint32_t& >);
    static_assert( comd::is_character_like_v<         uint32_t&&>);
    static_assert( comd::is_character_like_v<const    uint32_t&&>);
    static_assert( comd::is_character_like_v<         char32_t  >);
    static_assert( comd::is_character_like_v<const    char32_t  >);
    static_assert( comd::is_character_like_v<         char32_t& >);
    static_assert( comd::is_character_like_v<const    char32_t& >);
    static_assert( comd::is_character_like_v<         char32_t&&>);
    static_assert( comd::is_character_like_v<const    char32_t&&>);
    static_assert( comd::is_character_like_v<          wchar_t  >);
    static_assert( comd::is_character_like_v<const     wchar_t  >);
    static_assert( comd::is_character_like_v<          wchar_t& >);
    static_assert( comd::is_character_like_v<const     wchar_t& >);
    static_assert( comd::is_character_like_v<          wchar_t&&>);
    static_assert( comd::is_character_like_v<const     wchar_t&&>);
    static_assert( comd::is_character_like_v<          int64_t  >);
    static_assert( comd::is_character_like_v<const     int64_t  >);
    static_assert( comd::is_character_like_v<          int64_t& >);
    static_assert( comd::is_character_like_v<const     int64_t& >);
    static_assert( comd::is_character_like_v<          int64_t&&>);
    static_assert( comd::is_character_like_v<const     int64_t&&>);
    static_assert( comd::is_character_like_v<         uint64_t  >);
    static_assert( comd::is_character_like_v<const    uint64_t  >);
    static_assert( comd::is_character_like_v<         uint64_t& >);
    static_assert( comd::is_character_like_v<const    uint64_t& >);
    static_assert( comd::is_character_like_v<         uint64_t&&>);
    static_assert( comd::is_character_like_v<const    uint64_t&&>);
    static_assert( comd::is_character_like_v<            float  >);
    static_assert( comd::is_character_like_v<const       float  >);
    static_assert( comd::is_character_like_v<            float& >);
    static_assert( comd::is_character_like_v<const       float& >);
    static_assert( comd::is_character_like_v<            float&&>);
    static_assert( comd::is_character_like_v<const       float&&>);
    static_assert( comd::is_character_like_v<           double  >);
    static_assert( comd::is_character_like_v<const      double  >);
    static_assert( comd::is_character_like_v<           double& >);
    static_assert( comd::is_character_like_v<const      double& >);
    static_assert( comd::is_character_like_v<           double&&>);
    static_assert( comd::is_character_like_v<const      double&&>);
    static_assert( comd::is_character_like_v<      long double  >);
    static_assert( comd::is_character_like_v<const long double  >);
    static_assert( comd::is_character_like_v<      long double& >);
    static_assert( comd::is_character_like_v<const long double& >);
    static_assert( comd::is_character_like_v<      long double&&>);
    static_assert( comd::is_character_like_v<const long double&&>);

    static_assert( comd::is_character_like_v<      some_char  >);
    static_assert( comd::is_character_like_v<const some_char  >);
    static_assert( comd::is_character_like_v<      some_char& >);
    static_assert( comd::is_character_like_v<const some_char& >);
    static_assert( comd::is_character_like_v<      some_char&&>);
    static_assert( comd::is_character_like_v<const some_char&&>);

    static_assert(!comd::is_character_like_v<      non_char_constr  >);
    static_assert(!comd::is_character_like_v<const non_char_constr  >);
    static_assert(!comd::is_character_like_v<      non_char_constr& >);
    static_assert(!comd::is_character_like_v<const non_char_constr& >);
    static_assert(!comd::is_character_like_v<      non_char_constr&&>);
    static_assert(!comd::is_character_like_v<const non_char_constr&&>);

    static_assert(!comd::is_character_like_v<      non_const_comp_char  >);
    static_assert(!comd::is_character_like_v<const non_const_comp_char  >);
    static_assert(!comd::is_character_like_v<      non_const_comp_char& >);
    static_assert(!comd::is_character_like_v<const non_const_comp_char& >);
    static_assert(!comd::is_character_like_v<      non_const_comp_char&&>);
    static_assert(!comd::is_character_like_v<const non_const_comp_char&&>);

    static_assert(!comd::is_character_like_v<      non_char  >);
    static_assert(!comd::is_character_like_v<const non_char  >);
    static_assert(!comd::is_character_like_v<      non_char& >);
    static_assert(!comd::is_character_like_v<const non_char& >);
    static_assert(!comd::is_character_like_v<      non_char&&>);
    static_assert(!comd::is_character_like_v<const non_char&&>);
}

max_stars_repo_name: daishe/commander

max_issues_repo_name: daishe/commander

max_forks_repo_name: daishe/commander


text:
#include "vtkboneAIMWriter.h"
#include "vtkObjectFactory.h"
#include "vtkPointData.h"
#include "vtkDataArray.h"
#include "vtkMath.h"
#include "vtkImageData.h"
#include "vtkCellData.h"
#include "vtkInformation.h"
#include "vtkSmartPointer.h"
#include "AimIO/AimIO.h"
#include <sstream>
#include <string>
#include <time.h>
#include <boost/format.hpp>

using boost::format;
using std::string;
using std::ostringstream;

//-----------------------------------------------------------------------
// Private Utility Stuff

inline int roundFloat (const float x)
{
  return floor (x+0.5f);
}

vtkStandardNewMacro (vtkboneAIMWriter);

//-----------------------------------------------------------------------
vtkboneAIMWriter::vtkboneAIMWriter()
{
  this->FileName = NULL;
  this->NewProcessingLog = 1; // Default is to add the base AIM log info
  this->ProcessingLog = NULL;
}

//----------------------------------------------------------------------------
vtkboneAIMWriter::~vtkboneAIMWriter()
{
  this->SetFileName(0);   // Frees memory
  this->SetProcessingLog(0);   // Frees memory
}

//----------------------------------------------------------------------------
void vtkboneAIMWriter::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os,indent);
  os << indent << "FileName: " << this->FileName << "\n";
  os << indent << "NewProcessingLog: " << this->NewProcessingLog << "\n";
  os << indent << "ProcessingLog: "
     << (this->ProcessingLog ? this->ProcessingLog : "(none)") << "\n";
}

//----------------------------------------------------------------------------
void vtkboneAIMWriter::AppendToLog (const char* s)
{
  // Could be more efficient.  But this will never segfault or leak memory.
  this->SetProcessingLog ((string(ProcessingLog) + s).c_str());
}

//----------------------------------------------------------------------------
void vtkboneAIMWriter::WriteData()
{
  AimIO::AimFile writer;

  // // Do not call any deallocation functions on image!  It does not own its data!!!
  // D3AnyImage image;
  // D3InitAny(image,D1Tundef);
  // D3int          dim,off,pos;
  // D3float        el_size_mm;
  // int            status;
  // int            dimension[3];
  // double          origin[3], spacing[3], conversionError[3];
  // time_t        rawtime;
  // struct        tm *timeinfo;
  // int position[3];

  vtkImageData *temp_input= vtkImageData::SafeDownCast(this->GetInput());

  this->UpdateProgress(.01);

  // Now we are going to make sure that the image data is on the points.
  // The offset is strange: it will be 0,0,0 for data centered at pixel
  // centers with corner offset 0,0,0 (it should be 0.5,0.5,0.5).
  // Despite this strange offset, it all works out in the end.
  int     dimension[3];
  double  origin[3];
  double  spacing[3];
  vtkSmartPointer<vtkImageData> input = vtkSmartPointer<vtkImageData>::New();
  temp_input->GetSpacing(spacing);
  temp_input->GetOrigin(origin);
  temp_input->GetDimensions(dimension);
  if (temp_input->GetPointData()->GetScalars())
    {
    input->ShallowCopy(temp_input);
    input->SetOrigin(origin[0] - 0.5*spacing[0],
                     origin[1] - 0.5*spacing[1],
                     origin[2] - 0.5*spacing[2]);
    }
  else if (temp_input->GetCellData()->GetScalars())
    {
    input->SetSpacing(spacing);
    input->SetOrigin(origin);
    input->SetDimensions(dimension[0] - 1,
                         dimension[1] - 1,
                         dimension[2] - 1);
    input->GetPointData()->SetScalars(temp_input->GetCellData()->GetScalars());
    }
  else
    {
    vtkErrorMacro(<<"Could not get data from input.");
    return;
    }

  vtkDebugMacro(<<"Writing AIM file...");

  if (!this->FileName)
    {
      vtkErrorMacro(<<"An output filename must be specified.");
      return;
    }
  writer.filename = this->FileName;

  // Do this again - they may have changed.
  input->GetDimensions(dimension);
  input->GetSpacing(spacing);
  input->GetOrigin(origin);

  writer.dimensions[0] = dimension[0];
  writer.dimensions[1] = dimension[1];
  writer.dimensions[2] = dimension[2];

  writer.position[0] = roundFloat(origin[0]/spacing[0]);
  writer.position[1] = roundFloat(origin[1]/spacing[1]);
  writer.position[2] = roundFloat(origin[2]/spacing[2]);

  double conversionError[3];
  conversionError[0] = spacing[0]*writer.position[0] - origin[0];
  conversionError[1] = spacing[1]*writer.position[1] - origin[1];
  conversionError[2] = spacing[2]*writer.position[2] - origin[2];

  writer.element_size[0] = spacing[0];
  writer.element_size[1] = spacing[1];
  writer.element_size[2] = spacing[2];

  // if (fabs(conversionError[0]) > 0.000001 ||
  //     fabs(conversionError[1]) > 0.000001 ||
  //     fabs(conversionError[2]) > 0.000001) {
  //
  //       vtkWarningMacro(<<"\n  Possible error when calculating AIM position from image origin."
  //                         "\n  SPACING * POSITION - ORIGIN = ERROR"
  //                         "\n    X: "
  //                       << spacing[0] << " * "
  //                       << position[0] << " - "
  //                       << origin[0] << " = "
  //                       << conversionError[0] << " "
  //                       << (fabs(conversionError[0]) > 0.0000001 ? "<- error?" : "")
  //                       << "\n    Y: "
  //                       << spacing[1] << " * "
  //                       << position[1] << " - "
  //                       << origin[1] << " = "
  //                       << conversionError[1] << " "
  //                       << (fabs(conversionError[1]) > 0.0000001 ? "<- error?" : "")
  //                       << "\n    Z: "
  //                       << spacing[2] << " * "
  //                       << position[2] << " - "
  //                       << origin[2] << " = "
  //                       << conversionError[2] << " "
  //                       << (fabs(conversionError[2]) > 0.0000001 ? "<- error?" : "")
  //                         );
  // }

  time_t rawtime;
  time (&rawtime);
  struct tm *timeinfo = localtime(&rawtime);
  this->UpdateProgress(.05);

  // Note: This is a dummy log, and it is important that certain parameters be set so that other
  // Scanco software can properly read the data.  For example, 'mu_scaling' and 'patient name'.
  if (this->NewProcessingLog) {
    ostringstream newLog;
    newLog << "! \n";
    newLog << "! Processing Log \n";
    newLog << "! \n";
    newLog << "!-------------------------------------------------------------------------------\n";
    newLog << "Created by                    vtkboneAIMWriter\n";
    newLog << format("%-30s%-50s\n") % "Time" % asctime(timeinfo);
    newLog << "Original file                 DK0:[MICROCT.DATA.00000062.00001080]C0001021.ISQ\n";
    newLog << "!-------------------------------------------------------------------------------\n";
    newLog << "Site                                                1\n";
    newLog << "Scanner ID                                       5001\n";
    newLog << "Scanner type                                        9\n";
    newLog << "Position Slice 1 [um]                          120000\n";
    newLog << "No. samples                                      1536\n";
    newLog << "No. projections per 180                           750\n";
    newLog << "Scan Distance [um]                             777952\n";
    newLog << "Integration time [us]                          100000\n";
    newLog << "Reference line [um]                                 0\n";
    newLog << "Reconstruction-Alg.                                 3\n";
    newLog << "Energy [V]                                      77400\n";
    newLog << "Intensity [uA]                                   7000\n";
    newLog << "!-------------------------------------------------------------------------------\n";
    newLog << "Mu_Scaling                                       8192\n";
    newLog << "Calibration Data              77kVp, BH: 1200 mg HA/ccm, Scaling 8192           \n";
    newLog << "Calib. default unit type      2 (Density)                                       \n";
    newLog << "Density: unit                 mg HA/ccm                                         \n";
    // newLog << "Density: slope                         1.44113599e+03\n";
    // newLog << "Density: intercept                    -3.56445007e+02\n";
    // newLog << "HU: mu water                                  0.24640\n";
    newLog << "Density: slope                         8.19200000e+03\n";
    newLog << "Density: intercept                     0.00000000e+00\n";
    newLog << "HU: mu water                                  0.24640\n";
    //newLog << "!-------------------------------------------------------------------------------\n";
    //newLog << "Parameter (before) name       Linear Attenuation                                \n";
    //newLog << "Parameter units               [1/cm]                                            \n";
    //newLog << "Minimum value                                 0.00000\n";
    //newLog << "Maximum value                            20000.00000\n";
    //newLog << "Average value                                 0.38143\n";
    //newLog << "Standard deviation                            0.21346\n";
    //newLog << "Scaled by factor                                 8192\n";
    //newLog << "Minimum data value                         -852.00000\n";
    //newLog << "Maximum data value                        10717.00000\n";
    //newLog << "Average data value                         3124.65381\n";
    //newLog << "Standard data deviation                    1748.67932\n";
    //newLog << "!-------------------------------------------------------------------------------\n";
    //newLog << "Procedure:                    D3P_Std_FloatNormMax_M()                          \n";
    //newLog << "! \n";
    //newLog << "max                                         127.00000\n";
    //newLog << "! \n";
    //newLog << "Parameter name                Thickness                                         \n";
    //newLog << "Parameter units               [mm]                                              \n";
    //newLog << "!    Zeros not counted. DT type assumed\n";
    //newLog << "Minimum value                                 0.00000\n";
    //newLog << "Maximum value                               127.00000\n";
    //newLog << "Average value                                 0.23753\n";
    //newLog << "Standard deviation                            0.05602\n";
    //newLog << "Scaled by factor                             12.19512\n";
    //newLog << "Minimum data value                            0.00000\n";
    //newLog << "Maximum data value                            4.00000\n";
    //newLog << "Average data value                            2.89675\n";
    //newLog << "Standard data deviation                       0.68320\n";
    // newLog << "!-------------------------------------------------------------------------------\n";

    if (ProcessingLog)
      {
      newLog << ProcessingLog;
      }

    SetProcessingLog(newLog.str().c_str());

  }

  writer.processing_log = ProcessingLog;

  this->UpdateProgress(.1);

  writer.version = AimIO::AIMFILE_VERSION_20;;

  // Write the image
  vtkDataArray* data = input->GetPointData()->GetScalars();
  switch (data->GetDataType())
    {
    case VTK_CHAR:
      writer.WriteImageData ((char*)(data->WriteVoidPointer(0,0)));
      break;
    case VTK_SHORT:
      writer.WriteImageData ((short*)(data->WriteVoidPointer(0,0)));
      break;
    case VTK_FLOAT:
      writer.WriteImageData ((float*)(data->WriteVoidPointer(0,0)));
      break;
    default:
      vtkErrorMacro(<<"Input must be of type VTK_CHAR, VTK_SHORT or VTK_FLOAT.");
      return;
    }

  this->UpdateProgress(1.0);

  return;
}

//----------------------------------------------------------------------------
vtkImageData* vtkboneAIMWriter::GetInput()
{
  return vtkImageData::SafeDownCast(this->Superclass::GetInput());
}

vtkImageData* vtkboneAIMWriter::GetInput(int port)
{
  return vtkImageData::SafeDownCast(this->Superclass::GetInput(port));
}

int vtkboneAIMWriter::FillInputPortInformation(int,
                                           vtkInformation *info)
{
  info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkImageData");
  return 1;
}

ext: cxx