text:
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/calib3d/calib3d.hpp>
#include <algorithm>
#include <boost/timer.hpp>

#include "myslam/config.h"
#include "myslam/visual_odometry.h"

namespace myslam
{

VisualOdometry::VisualOdometry() : state_(INITIALIZING), ref_(nullptr), curr_(nullptr), map_(new Map), num_lost_(0), num_inliers_(0)
{
    num_of_features_ = Config::get<int>("number_of_features");
    scale_factor_ = Config::get<double>("scale_factor");
    level_pyramid_ = Config::get<int>("level_pyramid");
    match_ratio_ = Config::get<float>("match_ratio");
    max_num_lost_ = Config::get<float>("max_num_lost");
    min_inliers_ = Config::get<int>("min_inliers");
    key_frame_min_rot = Config::get<double>("keyframe_rotation");
    key_frame_min_trans = Config::get<double>("keyframe_translation");
    orb_ = cv::ORB::create(num_of_features_, scale_factor_, level_pyramid_);
}

VisualOdometry::~VisualOdometry()
{
}

bool VisualOdometry::addFrame(Frame::Ptr frame)
{
    switch (state_)
    {
    case INITIALIZING:
    {
        state_ = OK;
        ref_ = curr_ = frame;
        map_->insertKeyFrame(frame);
        extractKeyPoints();
        computeDescriptors();
        setRef3DPoints();
        break;
    }
    case OK:
    {
        curr_ = frame;
        extractKeyPoints();
        computeDescriptors();
        featureMatching();
        poseEstimationPnP();
        if (checkEstimatedPose())
        {
            curr_->T_c_w_ = T_c_r_estimated_ * ref_->T_c_w_; //T_cw=T_cr*T_rw
            ref_ = curr_;
            setRef3DPoints();
            num_lost_ = 0;
            if (checkKeyFrame())
                addKeyFrame();
        }
        else
        {
            num_lost_++;
            if (num_lost_ > max_num_lost_)
                state_ = LOST;
            return false;
        }
        break;
    }
    case LOST:
    {
        cout << "vo has lost" << endl;
        break;
    }
    }
    return true;
}

void VisualOdometry::extractKeyPoints()
{
    orb_->detect(curr_->color_, keypoints_curr_);
}

void VisualOdometry::computeDescriptors()
{
    orb_->compute(curr_->color_, keypoints_curr_, descriptors_curr_);
}

void VisualOdometry::featureMatching()
{
    vector<cv::DMatch> matches;
    cv::BFMatcher matcher(cv::NORM_HAMMING);
    matcher.match(descriptors_ref_, descriptors_curr_, matches);

    //定义lambda函数，从matches里，按照其中元素的cv::DMatch.distance找到最小距离的元素
    //得到它的最小距离
    float min_dis = std::min_element(
                        matches.begin(), matches.end(),
                        [](const cv::DMatch &m1, const cv::DMatch &m2) {
                            return m1.distance < m2.distance;
                        })
                        ->distance;

    feature_matches_.clear();

    // 找到距离合适的匹配
    // 距离小于30或min_dis的match_ratio倍，算匹配上
    for (cv::DMatch &m : matches)
    {
        if (m.distance < max<float>(min_dis * match_ratio_, 30.0))
        {
            feature_matches_.push_back(m);
        }
    }
    cout << "good matches:" << feature_matches_.size() << endl;
}

void VisualOdometry::setRef3DPoints()
{
    pts_3d_ref_.clear();
    descriptors_ref_ = Mat();
    //调用它的时候，已经把curr_赋给ref_了，所以此时res_实际上是curr_。
    // 找当前帧所有关键点，看能不能有深度，有的话计算相机坐标系的三维坐标，
    // 并且把由深度的描述子保留给ref_。
    // 但其实，把ref和curr统一是不是更好？
    for (size_t i = 0; i < keypoints_curr_.size(); i++)
    {
        double d = ref_->findDepth(keypoints_curr_[i]);
        if (d > 0)
        {
            //cout<<keypoints_curr_[i].pt.x<<' '<<keypoints_curr_[i].pt.y<<' '<<d<<' ';
            Vector3d p_cam=ref_->camera_->pixel2camera(
                Vector2d(keypoints_curr_[i].pt.x,keypoints_curr_[i].pt.y),d);
            pts_3d_ref_.push_back(cv::Point3f(p_cam(0, 0), p_cam(1, 0), p_cam(2, 0)));
            //cout<<p_cam(0, 0)<<' '<<p_cam(1, 0)<<' '<<p_cam(2, 0)<<endl;
            descriptors_ref_.push_back(descriptors_curr_.row(i));
        }
    }
}

void VisualOdometry::poseEstimationPnP()
{
    vector<cv::Point3f> pts3d;
    vector<cv::Point2f> pts2d;
    // query是要匹配的描述子，train是被匹配的描述子
    for (cv::DMatch m : feature_matches_)
    {
        pts3d.push_back(pts_3d_ref_[m.queryIdx]);
        pts2d.push_back(keypoints_curr_[m.trainIdx].pt);
    }
    // 内参
    Mat K = (cv::Mat_<double>(3, 3) << ref_->camera_->fx_, 0, ref_->camera_->cx_,
             0, ref_->camera_->fy_, ref_->camera_->cy_,
             0, 0, 1);
    //输出
    Mat rvec, tvec, inliers;
    cv::solvePnPRansac(pts3d, pts2d, K, Mat(), rvec, tvec, false, 100, 4.0, 0.99, inliers);
    num_inliers_ = inliers.rows;
    cout << "pnp inliers:" << num_inliers_ << endl;
    T_c_r_estimated_ = SE3(
        SO3(rvec.at<double>(0,0), rvec.at<double>(1,0), rvec.at<double>(2,0)),
        Vector3d( tvec.at<double>(0,0), tvec.at<double>(1,0), tvec.at<double>(2,0))
    );
}

bool VisualOdometry::checkEstimatedPose()
{
    if (num_inliers_ < min_inliers_)
    {
        cout << "reject because inlier is too small:" << num_inliers_ << endl;
        return false;
    }
    Sophus::Vector6d d = T_c_r_estimated_.log();
    if (d.norm() > 5.0)
    {
        cout << "reject because motion is too large:" << d.norm() << endl;
        return false;
    }
    return true;
}

bool VisualOdometry::checkKeyFrame()
{
    Sophus::Vector6d d = T_c_r_estimated_.log();
    Vector3d trans = d.head<3>();
    Vector3d rot = d.tail<3>();
    if (rot.norm() > key_frame_min_rot || trans.norm() > key_frame_min_trans)
        return true;
    return false;
}

void VisualOdometry::addKeyFrame()
{
    cout << "adding a key frame" << endl;
    map_->insertKeyFrame(curr_);
}

} // namespace myslam

max_stars_repo_name: linmeeka/slambook

max_issues_repo_name: linmeeka/slambook

max_forks_repo_name: linmeeka/slambook


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * File:   main.cpp
 * Author: osboxes
 *
 * Created on 08 June 2017, 12:18
 */

#include <cstdlib>
#include "main.h"
#include <iostream>
#include <boost/algorithm/string.hpp>

void print_version();

void print_version(){

    std::cout<<"Version :"<<VERSION_MAJOR<<"."<<VERSION_MINOR<<"."<<VERSION_PATCH<<std::endl;
}

void initLogger(){
    std::vector<spdlog::sink_ptr> sinks;
    //enable logger in async mode with queue size
    spdlog::set_async_mode(8192);
    sinks.push_back(std::make_shared<spdlog::sinks::ansicolor_stdout_sink_mt>());

    //toggles file logger
#ifdef FILE_LOGGER
    //check file exist or create it
    if(!Common::fexists(LOGGER_FILE_PATH)){
        std::cout<<"file not exists"<<std::endl;
        std::vector<std::string> strs;
        boost::split(strs,LOGGER_FILE_PATH,boost::is_any_of("/"));
        strs.pop_back();
        std::string path="";
        for(auto &s:strs){
            path.append(s).append("/");
        }
        Common::dcreate(path);
        Common::fcreate(LOGGER_FILE_PATH);
    }
    sinks.push_back(std::make_shared<spdlog::sinks::rotating_file_sink_mt>(LOGGER_FILE_PATH,23, 59));
 #endif

    auto combined_logger = std::make_shared<spdlog::logger>(loggerName, begin(sinks), end(sinks));
    combined_logger->set_level(spdlog::level::info);
    spdlog::register_logger(combined_logger);
    combined_logger->info("Hello spd");

}
void initSystem(){

    //enable logger
    auto logger = spdlog::get(loggerName);
    logger->info("System Initiated ...");
    logger->debug("System Initiated ...");
    logger->error("System Initiated ...");

}

void cleanup(){
    spdlog::drop_all();
}

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

    print_version();
    initLogger();
    std::cout<<"Hello Hubble"<<std::endl;

    initSystem();
    cleanup();
    return 0;
}

ext: cpp

max_stars_repo_name: nikhilvs/BaseCppCmakeProject

max_issues_repo_name: nikhilvs/BaseCppCmakeProject

max_forks_repo_name: nikhilvs/BaseCppCmakeProject


text:
#include <boost/multiprecision/cpp_int.hpp>
#include <iostream>
#include <set>

using namespace std;
using boost::multiprecision::cpp_int;

int main(int argc, char *argv[]) {
	// Sets only hold unique integers, making it the perfect container.
	set<cpp_int> numbers;
	for(cpp_int a = 2; a < 101; a++) {
		for(int b = 2; b < 101; b++) {
			numbers.emplace(boost::multiprecision::pow(a, b));
		}
	}
	cout << numbers.size() << endl;
	return 0;
}

max_stars_repo_name: kitegi/Edmonton

max_issues_repo_name: kitegi/Edmonton

max_forks_repo_name: kitegi/Edmonton


text:
#include "desktop-opencv.hpp"
#include "loop.hpp"
#include "recorder.hpp"
#include <algorithm>
#include <fmo/processing.hpp>
#include <fmo/region.hpp>
#include <iostream>
#include <boost/range/adaptor/reversed.hpp>

DebugVisualizer::DebugVisualizer(Status& s) : mStats(60) {
    mStats.reset(15.f);
//    s.window.setBottomLine("[esc] quit | [space] pause | [enter] step | [,][.] jump 10 frames");
}

void DebugVisualizer::process(Status& s, const fmo::Region& frame, const Evaluator* evaluator,
                                   const EvalResult& evalResult, fmo::Algorithm& algorithm) {
    mStats.tick();
    // float fpsLast = mStats.getLastFps();

    // draw the debug image provided by the algorithm
    fmo::copy(algorithm.getDebugImage(mLevel, mShowIM, mShowLM, mAdd), mVis);
    // s.window.print(s.inputName);
    // s.window.print("frame: " + std::to_string(s.inFrameNum));
    // s.window.print("fps: " + std::to_string(fpsLast));

    // get pixel coordinates of detected objects
    algorithm.getOutput(mOutputCache, false);
    mObjectPoints.clear();
    for (auto& detection : mOutputCache.detections) {
        mObjectPoints.emplace_back();
        detection->getPoints(mObjectPoints.back());
    }
    mDetections = mOutputCache.detections.size();

    // draw detected points vs. ground truth
    if (evaluator != nullptr) {
        s.window.print(evalResult.str());
        auto& gt = evaluator->gt().get(s.outFrameNum);
        fmo::pointSetMerge(begin(mObjectPoints), end(mObjectPoints), mPointsCache);
        fmo::pointSetMerge(begin(gt), end(gt), mGtPointsCache);
        drawPointsGt(mPointsCache, mGtPointsCache, mVis);
        s.window.setTextColor(good(evalResult.eval) ? Colour::green() : Colour::red());
    } else {
        drawPoints(mPointsCache, mVis, Colour::lightMagenta());
    }
}

void DebugVisualizer::processKeyboard(Status& s, const fmo::Region& frame) {
    // process keyboard input
    bool step = false;
    do {
        auto command = s.window.getCommand(s.paused);
        if (command == Command::PAUSE) s.paused = !s.paused;
        if (command == Command::PAUSE_FIRST) mPauseFirst = !mPauseFirst;
        if (mPauseFirst && mDetections > 0 && mPreviousDet == mDetections) {
            s.paused = !s.paused;
            mPreviousDet = 0;
            mDetections = 0;
        }
        if (command == Command::STEP) step = true;
        if (command == Command::QUIT) s.quit = true;
        if (command == Command::SCREENSHOT) fmo::save(mVis, "screenshot.png");
        if (command == Command::LEVEL0) mLevel = 0;
        if (command == Command::LEVEL1) mLevel = 1;
        if (command == Command::LEVEL2) mLevel = 2;
        if (command == Command::LEVEL3) mLevel = 3;
        if (command == Command::LEVEL4) mLevel = 4;
        if (command == Command::LEVEL5) mLevel = 5;
        if (command == Command::SHOW_IM) mShowIM = !mShowIM;
        if (command == Command::LOCAL_MAXIMA) mShowLM = !mShowLM;
        if (command == Command::SHOW_NONE) mAdd = 0;
        if (command == Command::DIFF) mAdd = 1;
        if (command == Command::BIN_DIFF) mAdd = 2;
        if (command == Command::DIST_TRAN) mAdd = 3;

        if (!s.haveCamera()) {
            if (command == Command::JUMP_BACKWARD) {
                s.paused = false;
                s.args.frame = std::max(1, s.inFrameNum - 10);
                s.reload = true;
            }
            if (command == Command::JUMP_FORWARD) {
                s.paused = false;
                s.args.frame = s.inFrameNum + 10;
            }
        }
    } while (s.paused && !step && !s.quit);
    mPreviousDet = mDetections;
}

void DebugVisualizer::visualize(Status& s, const fmo::Region& frame, const Evaluator* evaluator,
                                const EvalResult& evalResult, fmo::Algorithm& algorithm) {
    this->process(s,frame,evaluator,evalResult,algorithm);
    // display
    s.window.display(mVis);
    this->processKeyboard(s,frame);
}

// UTIA Demo
UTIADemoVisualizer::UTIADemoVisualizer(Status &s) : vis1(s) {
    s.window.setTopLine("Fast Moving Objects Detection");
    this->vis1.mode = 2;
}

void UTIADemoVisualizer::visualize(Status& s, const fmo::Region& frame, const Evaluator* evaluator,
                                  const EvalResult& evalResult, fmo::Algorithm& algorithm) {
    this->vis1.process(s,frame,algorithm);
    if(mLastDetectedImage.data() == nullptr) fmo::copy(frame,mLastDetectedImage);
    if(mMaxDetectedImage.data() == nullptr) fmo::copy(frame,mMaxDetectedImage);
    if (this->mPreviousDetections*this->vis1.mNumberDetections > 0) {
        fmo::copy(this->vis1.mVis, mLastDetectedImage);
    }
    if(this->vis1.mOffsetFromMaxDetection == 0) {
        fmo::copy(this->vis1.mVis, mMaxDetectedImage);
        this->mOffsetFromMax = 0;
    } else this->mOffsetFromMax++;

    if(this->vis1.mode == 2)
        s.window.visTable = true;
    else
        s.window.visTable = false;

    // put best players
    auto &playerName = s.inputString;
    int stringSize = 10;
    if((int)playerName.size() < stringSize)
        playerName = playerName + std::string(stringSize-playerName.size(), ' ');
    if((int)playerName.size() > stringSize)
        playerName = playerName.substr(0,stringSize);

    // if (vis1.mMaxSpeed > 0) {
    //     float spnow = std::round(vis1.mMaxSpeed*100)/100;

    //     bool putitthere = true;
    //     for(auto &el : s.window.mTable) {
    //         if(std::abs(el.first - spnow) < 0.001 && el.second.compare(playerName) == 0) {
    //             putitthere = false;
    //             break;
    //         }
    //     }

    //     if(putitthere) {
    //         if(s.window.mTable.size() < 10) {
    //             s.window.mTable.push_back(std::make_pair(spnow, playerName));
    //         } else {
    //             auto &lastel = s.window.mTable[s.window.mTable.size()-1];
    //             if(spnow > lastel.first) {
    //                 lastel = std::make_pair(spnow, playerName);
    //             }
    //         }
    //     }
    // }
    // std::sort(s.window.mTable.begin(), s.window.mTable.end(), std::greater <>());

    // if(s.window.visTable) {
    //     std::string pref;
    //     for (int ik = 0; ik < (int)s.window.mTable.size(); ++ik) {
    //         auto &el = s.window.mTable[ik];
    //         if(ik < 9)
    //            pref = " ";
    //         else
    //            pref = "";

    //         s.window.print(pref+std::to_string(ik+1)+". "+el.second+": "+std::to_string(el.first).substr(0,4) + " km/h");
    //     }
    // }
    s.window.display(this->vis1.mVis);

    this->vis1.processKeyboard(s,frame);
    this->mPreviousDetections = this->vis1.mNumberDetections;
    mLastMode = this->vis1.mode;
}

// TUT Demo

TUTDemoVisualizer::TUTDemoVisualizer(Status &s) : vis1(s) {
    try {
        input.emplace_back(VideoInput::makeFromFile("../data/webcam/circle_back_res.avi"));
        input.emplace_back(VideoInput::makeFromFile("../data/webcam/counting_all_res.avi"));
        input.emplace_back(VideoInput::makeFromFile("../data/webcam/floorball_res.avi"));
    } catch(const std::exception& e) {
        input.clear();
        try {
            input.emplace_back(VideoInput::makeFromFile("data/webcam/circle_back_res.avi"));
            input.emplace_back(VideoInput::makeFromFile("data/webcam/counting_all_res.avi"));
            input.emplace_back(VideoInput::makeFromFile("data/webcam/floorball_res.avi"));
        } catch(const std::exception& e) {

        }
    }
    s.window.setTopLine("Fast Moving Objects Detection");
    this->mRecord = !s.args.noRecord;
    if(this->mRecord)
        this->vis1.mRecordAnnotations = false;
//    input.emplace_back(VideoInput::makeFromCamera(0));
}

void TUTDemoVisualizer::visualize(Status& s, const fmo::Region& frame, const Evaluator* evaluator,
                                  const EvalResult& evalResult, fmo::Algorithm& algorithm) {
    if (!this->vis1.mManual && this->mRecord)
        this->vis1.mManual = std::make_unique<ManualRecorder>(s.args.recordDir, frame.format(),
                                                              frame.dims(), 30);
    this->vis1.process(s,frame,algorithm);
    if(mLastDetectedImage.data() == nullptr) fmo::copy(frame,mLastDetectedImage);
    if(mMaxDetectedImage.data() == nullptr) fmo::copy(frame,mMaxDetectedImage);
    if (this->mPreviousDetections*this->vis1.mNumberDetections > 0) {
        fmo::copy(this->vis1.mVis, mLastDetectedImage);
    }
    if(this->vis1.mOffsetFromMaxDetection == 0) {
        fmo::copy(this->vis1.mVis, mMaxDetectedImage);
        this->mOffsetFromMax = 0;
    } else this->mOffsetFromMax++;

    if(this->vis1.mode == 0) {
        mVis.resize(fmo::Format::BGR,fmo::Dims{2*frame.wrap().cols,2*frame.wrap().rows});
        cv::Mat out = mVis.wrap();
        imgs.clear();
        fmo::Region nextframe;
        int cntr = 0;
        for (auto &in : input) {
            nextframe = in->receiveFrame();
            if (nextframe.data() == nullptr) {
                in->restart();
                nextframe = in->receiveFrame();
            }
            imgs.push_back(nextframe.wrap());
            cntr++;
        }
        for (int i = cntr; i < 4; ++i) {
            imgs.push_back(this->vis1.mVis.wrap());
        }
        fmo::imgridfull(imgs, out, 2, 2);
        s.window.display(mVis);
    } else if(this->vis1.mode == 1) {
        s.window.display(this->vis1.mVis);
    } else if(this->vis1.mode == 2) {
        mVis.resize(fmo::Format::BGR,fmo::Dims{2*frame.wrap().cols,2*frame.wrap().rows});
        cv::Mat out = mVis.wrap();
        imgs.clear();
        imgs.push_back(frame.wrap());

        fmo::copy(algorithm.getDebugImage(1, true, false, 1), mTempDebug);
        cv::Mat temp = mTempDebug.wrap();
        cv::resize(temp,temp,frame.wrap().size.operator()());
        imgs.push_back(temp);

        fmo::copy(algorithm.getDebugImage(1, true, true, 3), mTemp2Debug);
        cv::Mat temp2 = mTemp2Debug.wrap();
        cv::resize(temp2,temp2,frame.wrap().size.operator()());
        imgs.push_back(temp2);

        imgs.push_back(this->vis1.mVis.wrap());
        fmo::imgridfull(imgs, out, 2, 2);
        s.window.display(mVis);
    } else if(this->vis1.mode == 3) {
        if (mLastMode != this->vis1.mode) {
            fmo::copy(frame, mVis);
        } else
            fmo::copy(mLastDetectedImage,mVis);
        cv::Mat out = mVis.wrap();
        fmo::putcorner(frame.wrap(), out);
        s.window.display(mVis);
    } else if(this->vis1.mode == 4) {
        if(mLastMode != this->vis1.mode)
            fmo::copy(frame,mVis);
        else
            fmo::copy(mMaxDetectedImage,mVis);
        cv::Mat out = mVis.wrap();
        fmo::putcorner(frame.wrap(), out);
        s.window.display(mVis);
    }
    this->vis1.processKeyboard(s,frame);
    this->mPreviousDetections = this->vis1.mNumberDetections;
    mLastMode = this->vis1.mode;
}

// DEMO

DemoVisualizer::DemoVisualizer(Status& s) : mStats(60) {
    mStats.reset(15.f);
    updateHelp(s);
}

void DemoVisualizer::updateHelp(Status& s) {
    if (!mShowHelp) {
        s.window.setBottomLine("");
    } else {
        std::ostringstream oss;
        oss << "[esc] quit";

        if (mAutomatic) {
            oss << " | [m] manual mode | [e] forced event";
        } else {
            oss << " | [a] automatic mode | [r] start/stop recording";
        }

        if (s.sound) {
            oss << " | [s] disable sound";
        } else {
            oss << " | [s] enable sound";
        }

        s.window.setBottomLine(oss.str());
    }
}

void DemoVisualizer::printStatus(Status& s, int fpsEstimate) const {
    bool recording;
    if (mAutomatic) {
//        s.window.print("automatic mode");
        recording = mAutomatic->isRecording();
    } else {
//        s.window.print("manual mode");
        recording = bool(mManual);
    }

    bool kmh = true;
    std::string meas = kmh ? " km/h" : " mph";
    float fctr = kmh ? 1 : 0.621371;

    // s.window.print(recording ? "recording" : "not recording");
    s.window.print("Detections: " + std::to_string(mMaxDetections));
    for (unsigned int i = 0; i < mSpeeds.size(); ++i) {
        s.window.print("Speed " + std::to_string(i+1) + " : " + std::to_string(std::round(mSpeeds[i]*fctr * 100)/100).substr(0,4) + meas);
    }
    Colour clr = Colour::lightRed();
    s.window.print("Max speed: " + std::to_string(std::round(mMaxSpeed*fctr * 100)/100).substr(0,4) + meas, clr);

    // s.window.print("fps: " + std::to_string(fpsEstimate));
//    s.window.print("[?] for help");

    s.window.setTextColor(recording ? Colour::lightRed() : Colour::lightGray());
}

void DemoVisualizer::onDetection(const Status& s, const fmo::Algorithm::Detection& detection) {
    // register a new event after a time without detections
    if (s.outFrameNum - mLastDetectFrame > EVENT_GAP_FRAMES) {
        if (s.sound) {
            // make some noise
            std::cout << char(7);
        }
        mEventsDetected++;
        mSegments.clear();
        for(auto& c : mCurves) {
            delete c;
        }
        mCurves.clear();
    }
    mLastDetectFrame = s.outFrameNum;

    // don't add a segment if there is no previous center
    if (detection.object.curve != nullptr) {
        fmo::SCurve *c = detection.object.curve->clone();
        c->scale = detection.object.scale;
        mCurves.push_back(c);
        float radiusCm = s.args.radius; // floorball = 3.6; tennis = 3.27
        float sp = 0;
        float fpsReal = 29.97;
        if(s.args.fps != -1) fpsReal = s.args.fps;

        if(s.args.p2cm == -1)
            sp = detection.object.velocity * 3600* fpsReal * radiusCm * 1e-5;
        else {
            float len = detection.object.velocity * (detection.object.radius+1.5);
            // std::cout << len << std::endl;
            sp = len * s.args.p2cm * fpsReal *3600 * 1e-5;
        }
        mSpeeds.push_back(sp);

        if(mLastSpeeds.size() > MAX_SPEED_FRAMES) {
            mLastSpeeds[MAX_SPEED_FRAMES-1].first = MAX_SPEED_TIME;
            mLastSpeeds[MAX_SPEED_FRAMES-1].second = sp;
        } else {
            mLastSpeeds.push_back(std::make_pair(MAX_SPEED_TIME, sp));
        }

        std::sort(mLastSpeeds.begin(), mLastSpeeds.end(), std::greater <>());
    } else if (detection.predecessor.haveCenter()) {
        fmo::Bounds segment = {detection.predecessor.center, detection.object.center};
        mSegments.push_back(segment);
        // std::cout << "-----------------------------\n";
    }

    float mSpeedNow = 0;
    for(auto& elv : mLastSpeeds) {
        if(elv.first > 0) {
            elv.first--;
            if(elv.second > mSpeedNow) mSpeedNow = elv.second;
        }
    }

    if(detection.object.curve != nullptr) mMaxSpeed = mSpeedNow;

    // make sure to keep the number of segments bounded in case there's a long event
    if (mSegments.size() > MAX_SEGMENTS) {
        mSegments.erase(begin(mSegments), begin(mSegments) + (mSegments.size() / 2));
    }
    int maxCurves = 20;
    for (int i = 0; i < int(mCurves.size()) - maxCurves; ++i)
    {
        delete mCurves[0];
        mCurves.erase(mCurves.begin());
    }
}

void DemoVisualizer::drawSegments(fmo::Image& im) {
    cv::Mat mat = im.wrap();
    auto color = Colour::magenta();
    float thickness = 8;
    for (auto& segment : mSegments) {
        color.b = std::max(color.b, uint8_t(color.b + 2));
        color.g = std::max(color.g, uint8_t(color.g + 1));
        color.r = std::max(color.r, uint8_t(color.r + 4));
        cv::Scalar cvColor(color.b, color.g, color.r);
        cv::Point pt1{segment.min.x, segment.min.y};
        cv::Point pt2{segment.max.x, segment.max.y};
        cv::line(mat, pt1, pt2, cvColor, thickness);
    }
    for (auto& curve : mCurves) {
        color.b = std::max(color.b, uint8_t(color.b + 2));
        color.g = std::max(color.g, uint8_t(color.g + 1));
        color.r = std::max(color.r, uint8_t(color.r + 4));
        cv::Scalar cvColor(color.b, color.g, color.r);

        curve->drawSmooth(mat, cvColor, thickness);
    }
}

void DemoVisualizer::process(Status& s, const fmo::Region& frame, fmo::Algorithm& algorithm) {
    // estimate FPS
    if (s.outFrameNum < mLastDetectFrame) {
        mEventsDetected = s.outFrameNum;
        mSegments.clear();
        for(auto& c : mCurves) {
            delete c;
        }
        mCurves.clear();
    }

    // decrease last speeds
    for(auto& elv : mLastSpeeds) {
        if(elv.first > 0) {
            elv.first--;
        }
    }
    //

    mStats.tick();
    auto fpsEstimate = [this]() { return std::round(mStats.quantilesHz().q50); };

    // get detections
    algorithm.getOutput(mOutput, true);
    mNumberDetections = mOutput.detections.size();
    if(mNumberDetections > 0)     mSpeeds.clear();

    if (mNumberDetections > mMaxDetections) {
        mMaxDetections = mNumberDetections;
        mOffsetFromMaxDetection = 0;
    } else {
        mOffsetFromMaxDetection++;
    }
    if (mOffsetFromMaxDetection > 10*30 && mNumberDetections > 0) {
        mOffsetFromMaxDetection = 0;
        mMaxDetections = mNumberDetections;
    }

    // draw input image as background
    fmo::copy(frame, mVis);

    // iterate over detected fast-moving objects
    for (auto& detection : mOutput.detections) { onDetection(s, *detection); }

    drawSegments(mVis);
    printStatus(s,fpsEstimate());
}

void DemoVisualizer::processKeyboard(Status& s, const fmo::Region& frame) {
    // record frames
    if (mAutomatic) {
        bool event = mForcedEvent || !mOutput.detections.empty();
        if (mRecordAnnotations) {
            mAutomatic->frame(mVis, event);
        } else {
            mAutomatic->frame(frame, event);
        }
    } else if (mManual) {
        if (mRecordAnnotations) {
            mManual->frame(mVis);
        } else {
            mManual->frame(frame);
        }
    }
    mForcedEvent = false;

    bool step = false;
    // process keyboard input
    do {
        auto command = s.window.getCommand(false);
        if (command == Command::PAUSE) { s.paused = !s.paused; }
        if (command == Command::INPUT) {
            uint nPlayers = 10;
            int stringSize = 10;
            bool visTable = s.window.visTable;
            s.window.visTable = false;
            float spnow = std::round(mMaxSpeed*100)/100;

            // std::getline(std::cin, s.inputString);
            // system("zenity  --title  \"Gimme some text!\" --entry --text \"Enter your text here\"");
            // s.inputString = "Denis";

            if(s.window.mTable.size() >= nPlayers) {
                auto &lastel = s.window.mTable[s.window.mTable.size()-1];
                if(spnow <= lastel.first) {
                    s.window.setCenterLine("Sorry, not in top "+std::to_string(nPlayers), "");
                    s.window.display(mVis);
                    cv::waitKey(500);
                    s.window.visTable = visTable;
                    s.window.setCenterLine("", "");
                    s.window.display(mVis);
                    continue;
                }
            }

            s.window.setCenterLine("Input player's name", "");
            s.window.display(mVis);

            char keyCode = ' ';
            std::vector<char> vec;
            while(keyCode != 13 && keyCode != '\n' && keyCode != 10) {
                // std::cout << (int) keyCode << std::endl;
                if(keyCode != ' ') {
                    if(keyCode == 127 || keyCode == 8) {
                        if(vec.size() > 0)
                            vec.pop_back();
                    } else {
                        vec.push_back(keyCode);
                    }
                    std::string str(vec.begin(), vec.end());
                    s.window.setCenterLine("Input player's name", str);
                    s.window.display(mVis);
                }
                keyCode = cv::waitKey(0);
            }
            s.window.setCenterLine("","");
            s.window.display(mVis);
            std::string str(vec.begin(), vec.end());
            s.inputString = str;

            auto &playerName = s.inputString;
            if((int)playerName.size() < stringSize)
                playerName = playerName + std::string(stringSize-playerName.size(), ' ');
            if((int)playerName.size() > stringSize)
                playerName = playerName.substr(0,stringSize);

            if(s.window.mTable.size() < nPlayers) {
                s.window.mTable.push_back(std::make_pair(spnow, playerName));
            } else {
                auto &lastel = s.window.mTable[s.window.mTable.size()-1];
                if(spnow > lastel.first) {
                    lastel = std::make_pair(spnow, playerName);
                }
            }
            std::sort(s.window.mTable.begin(), s.window.mTable.end(), std::greater <>());
            s.window.visTable = visTable;
        }
        if (command == Command::STEP) step = true;
        if (command == Command::QUIT) { s.quit = true; mManual.reset(nullptr); }
        if (command == Command::SHOW_HELP) {
            mShowHelp = !mShowHelp;
            updateHelp(s);
        }
        if (command == Command::AUTOMATIC_MODE) {
            if (mManual) { mManual.reset(nullptr); }
            if (!mAutomatic) {
                mAutomatic = std::make_unique<AutomaticRecorder>(s.args.recordDir, frame.format(),
                                                                 frame.dims(), 30);
                updateHelp(s);
            }
        }
        if (command == Command::FORCED_EVENT) { mForcedEvent = true; }
        if (command == Command::MANUAL_MODE) {
            if (mAutomatic) {
                mAutomatic.reset(nullptr);
                updateHelp(s);
            }
        }
        if (command == Command::RECORD_GRAPHICS) mRecordAnnotations = !mRecordAnnotations;
        if (command == Command::RECORD) {
            if (mManual) {
                mManual.reset(nullptr);
            } else if (!mAutomatic) {
                mManual = std::make_unique<ManualRecorder>(s.args.recordDir, frame.format(),
                                                           frame.dims(), 30);
            }
        }
        if (command == Command::PLAY_SOUNDS) { s.sound = !s.sound; }
        if (command == Command::LEVEL0) mode = 0;
        if (command == Command::LEVEL1) mode = 1;
        if (command == Command::LEVEL2) mode = 2;
        if (command == Command::LEVEL3) mode = 3;
        if (command == Command::LEVEL4) mode = 4;
    } while (s.paused && !s.quit && !step);
}

void DemoVisualizer::visualize(Status& s, const fmo::Region& frame, const Evaluator*,
                               const EvalResult&, fmo::Algorithm& algorithm) {

    this->process(s,frame,algorithm);
    s.window.display(mVis);
    this->processKeyboard(s,frame);
}

RemovalVisualizer::RemovalVisualizer(Status& s) : mStats(60) {
    mStats.reset(15.f);
    // s.window.setBottomLine("[esc] quit | [space] pause | [enter] step | [,][.] jump 10 frames");
}

void RemovalVisualizer::visualize(Status& s, const fmo::Region& frame, const Evaluator*,
                                const EvalResult&, fmo::Algorithm& algorithm) {
    mEventsDetected++;

    // estimate FPS
    mStats.tick();
    // float fpsLast = mStats.getLastFps();
    auto fpsEstimate = [this]() { return std::round(mStats.quantilesHz().q50); };

    // get the background provided by the algorithm
    fmo::copy(frame, mCurrent);

    // swap frames
    mFrames[4].swap(mFrames[3]);
    mFrames[3].swap(mFrames[2]);
    mFrames[2].swap(mFrames[1]);
    mFrames[1].swap(mFrames[0]);
    mFrames[0].swap(mCurrent);

    fmo::Image &vis = mFrames[std::min(0-algorithm.getOutputOffset(),mEventsDetected-1)];
    fmo::Image &bg  = mFrames[std::min(mEventsDetected-1,4)];

    // s.window.print(s.inputName);
    // s.window.print(mManual ? "recording" : "not recording");
    // s.window.print("frame: " + std::to_string(s.inFrameNum));
    // s.window.print("fps: " + std::to_string(fpsLast));
    s.window.setTextColor(mManual ? Colour::lightRed() : Colour::lightGray());

    // get pixel coordinates of detected objects
    algorithm.getOutput(mOutputCache, false);
    mObjectPoints.clear();
    for (auto& detection : mOutputCache.detections) {
        mObjectPoints.emplace_back();
        detection->getPoints(mObjectPoints.back());
    }
    fmo::pointSetMerge(begin(mObjectPoints), end(mObjectPoints), mPointsCache);

    // replace detected points by the background
    removePoints(mPointsCache, vis, bg);

    // record frames
    if (mManual) {
        mManual->frame(vis);
    }

    // display
    s.window.display(vis);

    // process keyboard input
    bool step = false;
    do {
        auto command = s.window.getCommand(s.paused);
        if (command == Command::PAUSE) s.paused = !s.paused;
        if (command == Command::STEP) step = true;
        if (command == Command::QUIT) s.quit = true;
        if (command == Command::SCREENSHOT) fmo::save(vis, "screenshot.png");

        if (!s.haveCamera()) {
            if (command == Command::JUMP_BACKWARD) {
                s.paused = false;
                s.args.frame = std::max(1, s.inFrameNum - 10);
                s.reload = true;
            }
            if (command == Command::JUMP_FORWARD) {
                s.paused = false;
                s.args.frame = s.inFrameNum + 10;
            }
        }
        if (command == Command::RECORD) {
            if (mManual) {
                mManual.reset(nullptr);
            } else {
                mManual = std::make_unique<ManualRecorder>(s.args.recordDir, frame.format(),
                                                           frame.dims(), fpsEstimate());
            }
        }
    } while (s.paused && !step && !s.quit);
}

max_stars_repo_name: rozumden/fmo-android

max_issues_repo_name: rozumden/fmo-android

max_forks_repo_name: rozumden/fmo-android


text:
#pragma once

#include <boost/thread/future.hpp>

#include "abstract_server_task.hpp"

namespace opossum {

class SQLPipeline;

struct CreatePipelineResult {
  std::shared_ptr<SQLPipeline> sql_pipeline;
  std::optional<std::pair<std::string, std::string>> load_table;
};

// This task is used to parse an SQL string from a client and wrap it in an SQLPipeline. It is a separate task and not
// "inlined" because parsing can be a potentially expensive task on long strings and we want to reduce the computational
// load on the main server thread to a miminum.
class CreatePipelineTask : public AbstractServerTask<std::unique_ptr<CreatePipelineResult>> {
 public:
  explicit CreatePipelineTask(std::string sql, bool allow_load_table = false)
      : _sql(sql), _allow_load_table(allow_load_table) {}

 protected:
  void _on_execute() override;

  // This is a slightly hacky way of loading tables via the network interface. We don't support CREATE TABLE yet, so we
  // have to get data into the DB by loading it from a file. If we cannot parse the incoming SQL string, we try to
  // interpret it as a LOAD <file-name> <table-name> command. If this doesn't work, we pass on the parse error.
  bool _is_load_table();

  const std::string _sql;
  const bool _allow_load_table;

  std::string _file_name;
  std::string _table_name;
};

}  // namespace opossum

ext: hpp

max_stars_repo_name: nilsthamm/hyrise

max_issues_repo_name: nilsthamm/hyrise

max_forks_repo_name: nilsthamm/hyrise


text:
/*=========================================================================
 *
 *  Copyright David Doria 2012 daviddoria@gmail.com
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0.txt
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *=========================================================================*/

#ifndef InpaintingVisitor_HPP
#define InpaintingVisitor_HPP

#include "Visitors/InpaintingVisitors/InpaintingVisitorParent.h"

// STL
#include <memory>

// Concepts
#include "Concepts/DescriptorVisitorConcept.hpp"

// Accept criteria
#include "ImageProcessing/BoundaryEnergy.h"

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

// Submodules
#include <ITKHelpers/ITKHelpers.h>
#include <BoostHelpers/BoostHelpers.h>
#include <ITKVTKHelpers/ITKVTKHelpers.h>
#include <Utilities/Debug/Debug.h>

/**
 * This is a visitor that complies with the InpaintingVisitorConcept. It forwards
 * initialize_vertex and discover_vertex, the only two functions that need to know about
 * the descriptor type, to a visitor that models DescriptorVisitorConcept.
 * The visitor needs to know the patch size of the patch to be inpainted because it uses
 * this size to traverse the inpainted region to update the boundary.
 *
 * 'TImage' is provided a default value so that if 'image' is not passed to the constructor
 * the value is not required to be specified (because we don't have an image to operate on anyway).
 */
template <typename TGraph, typename TBoundaryNodeQueue,
          typename TDescriptorVisitor, typename TAcceptanceVisitor, typename TPriority>
class InpaintingVisitor : public InpaintingVisitorParent<TGraph>, public Debug
{
  BOOST_CONCEPT_ASSERT((DescriptorVisitorConcept<TDescriptorVisitor, TGraph>));

  typedef typename boost::graph_traits<TGraph>::vertex_descriptor VertexDescriptorType;

  /** The mask indicating the region to inpaint. */
  Mask* MaskImage;

  /** A queue to use to determine which patch to inpaint next. */
  std::shared_ptr<TBoundaryNodeQueue> BoundaryNodeQueue;

  /** A function to determine the priority of each target patch. */
  std::shared_ptr<TPriority> PriorityFunction;

  /** A visitor to do patch descriptor specific operations. */
  std::shared_ptr<TDescriptorVisitor> DescriptorVisitor;

  /** A visitor to perform specified actions when a match is accepted. */
  std::shared_ptr<TAcceptanceVisitor> AcceptanceVisitor;

  /** The radius of the patches to use to inpaint the image. */
  const unsigned int PatchHalfWidth;

  /** How many patches have been finished so far. */
  unsigned int NumberOfFinishedPatches = 0;

  /** As the image is inpainted, this flag determines if new source patches can be created from patches which are now valid. */
  bool AllowNewPatches = false;

  /** The full region (the mask and image should both be this size). */
  itk::ImageRegion<2> FullRegion;

  /** Track which nodes have been used as source nodes. */
  typedef std::set<itk::Index<2>, itk::Index<2>::LexicographicCompare> UsedNodesSetType;
  UsedNodesSetType UsedNodesSet;

  /** Track which pixels have been used as source pixels. */
  typedef itk::Image<bool, 2> CopiedPixelsImageType;
  CopiedPixelsImageType::Pointer CopiedPixelsImage;

  /** Track where pixels have been copied from. */
  typedef itk::Image<itk::Index<2>, 2> SourcePixelMapImageType;
  SourcePixelMapImageType::Pointer SourcePixelMapImage;

public:

  CopiedPixelsImageType* GetCopiedPixelsImage()
  {
    return this->CopiedPixelsImage;
  }

  SourcePixelMapImageType* GetSourcePixelMapImage()
  {
    return this->SourcePixelMapImage;
  }

  UsedNodesSetType* GetUsedNodesSetPointer()
  {
    return &this->UsedNodesSet;
  }

  void SetAllowNewPatches(const bool allowNewPatches)
  {
    this->AllowNewPatches = allowNewPatches;
  }

  /** Constructor. Everything must be specified in this constructor. (There is no default constructor). */
  InpaintingVisitor(Mask* const mask,
                    std::shared_ptr<TBoundaryNodeQueue> boundaryNodeQueue,
                    std::shared_ptr<TDescriptorVisitor> descriptorVisitor,
                    std::shared_ptr<TAcceptanceVisitor> acceptanceVisitor,
                    std::shared_ptr<TPriority> const priorityFunction,
                    const unsigned int patchHalfWidth,
                    const std::string& visitorName = "InpaintingVisitor") :
    InpaintingVisitorParent<TGraph>(visitorName),
    MaskImage(mask), BoundaryNodeQueue(boundaryNodeQueue), PriorityFunction(priorityFunction),
    DescriptorVisitor(descriptorVisitor), AcceptanceVisitor(acceptanceVisitor),
    PatchHalfWidth(patchHalfWidth)
  {
    this->FullRegion = this->MaskImage->GetLargestPossibleRegion();

    this->CopiedPixelsImage = CopiedPixelsImageType::New();
    this->CopiedPixelsImage->SetRegions(this->FullRegion);
    this->CopiedPixelsImage->Allocate();
    this->CopiedPixelsImage->FillBuffer(false);

    this->SourcePixelMapImage = SourcePixelMapImageType::New();
    this->SourcePixelMapImage->SetRegions(this->FullRegion);
    this->SourcePixelMapImage->Allocate();
    itk::Index<2> dummyIndex = {{-1, -1}};
    this->SourcePixelMapImage->FillBuffer(dummyIndex);

    // Initialize by setting all valid pixels to their own index
    itk::ImageRegionIteratorWithIndex<SourcePixelMapImageType>
        sourcePixelMapImageIterator(this->SourcePixelMapImage, this->FullRegion);
    while(!sourcePixelMapImageIterator.IsAtEnd())
    {
      if(this->MaskImage->IsValid(sourcePixelMapImageIterator.GetIndex()))
      {
        this->SourcePixelMapImage->SetPixel(sourcePixelMapImageIterator.GetIndex(),
                                            sourcePixelMapImageIterator.GetIndex());
      }

      ++sourcePixelMapImageIterator;
    }
  }

  void InitializeVertex(VertexDescriptorType v) const override
  {
    this->DescriptorVisitor->InitializeVertex(v);
  }

  void DiscoverVertex(VertexDescriptorType v) override
  {
    this->DescriptorVisitor->DiscoverVertex(v);
  }

  void PotentialMatchMade(VertexDescriptorType target, VertexDescriptorType source) override
  {
//    std::cout << "InpaintingVisitor::PotentialMatchMade: target " << target[0] << " " << target[1]
//              << " source: " << source[0] << " " << source[1] << std::endl;

    if(!this->MaskImage->IsValid(ITKHelpers::CreateIndex(source)))
    {
      std::stringstream ss;
      ss << "InpaintingVisitor::PotentialMatchMade: Potential source pixel " << source[0] << " " << source[1] << " is not valid in the mask!";
      throw std::runtime_error(ss.str());
    }

    if(!this->MaskImage->HasHoleNeighbor(ITKHelpers::CreateIndex(target)))
    {
      std::stringstream ss;
      ss << "InpaintingVisitor::PotentialMatchMade: Potential target pixel " << target[0] << " " << target[1]
         << " does not have a hole neighbor (which means it is not on the boundary)!";
      throw std::runtime_error(ss.str());
    }
  }

  bool AcceptMatch(VertexDescriptorType target, VertexDescriptorType source) const override
  {
    float energy = 0.0f;
    return AcceptanceVisitor->AcceptMatch(target, source, energy);
  }

  /** The mask is inpainted with ValidValue in this function. */
  void FinishVertex(VertexDescriptorType targetNode, VertexDescriptorType sourceNode) override
  {
    // Mark this pixel and the area around it as filled, and mark the mask in this region as filled.
    // Determine the new boundary, and setup the nodes in the boundary queue.

//    std::cout << "InpaintingVisitor::FinishVertex()" << std::endl;

    // Construct the region around the vertex
    itk::Index<2> indexToFinish = ITKHelpers::CreateIndex(targetNode);

    // Mark this node as having been used as a source node.
    this->UsedNodesSet.insert(indexToFinish);

    itk::ImageRegion<2> regionToFinishFull =
        ITKHelpers::GetRegionInRadiusAroundPixel(indexToFinish, this->PatchHalfWidth);

    // Copy this region so that we can change (crop) the regionToFinish and still have a copy of the original region
    itk::ImageRegion<2> regionToFinish = regionToFinishFull;

    // Make sure the region is entirely inside the image
    // (because we allow target patches to not be entirely inside the image to handle the case where
    // the hole boundary is near the image boundary)
    regionToFinish.Crop(this->FullRegion);

    itk::Index<2> sourceRegionCenter = ITKHelpers::CreateIndex(sourceNode);
    itk::ImageRegion<2> sourceRegion =
        ITKHelpers::GetRegionInRadiusAroundPixel(sourceRegionCenter, this->PatchHalfWidth);

    sourceRegion = ITKHelpers::CropRegionAtPosition(sourceRegion, this->MaskImage->GetLargestPossibleRegion(),
                                                    regionToFinishFull);

    // Mark all pixels that were copied (in the hole region of the source patch) as having been used.
//    std::cout << "InpaintingVisitor::FinishVertex() mark pixels as used" << std::endl;
    itk::ImageRegionConstIteratorWithIndex<SourcePixelMapImageType> sourcePatchIterator(this->SourcePixelMapImage,
                                                                                sourceRegion);
    itk::ImageRegionConstIteratorWithIndex<Mask> targetPatchIterator(this->MaskImage, regionToFinish);
    while(!sourcePatchIterator.IsAtEnd())
    {
      if(targetPatchIterator.Get() == this->MaskImage->GetHoleValue())
      {
        this->CopiedPixelsImage->SetPixel(sourcePatchIterator.GetIndex(), true); // Mark this pixel as used

        // Save the location from which this pixel came. We want to use the index value in the SourcePixelMapImage,
        // because the value might not equal the current index in the case where new patches are allowed.
        this->SourcePixelMapImage->SetPixel(targetPatchIterator.GetIndex(),
                                            sourcePatchIterator.Get());
      }

      ++sourcePatchIterator;
      ++targetPatchIterator;
    }

    if(this->DebugImages)
    {
      if(this->DebugLevel > 1)
      {
        ITKHelpers::WriteBoolImage(this->CopiedPixelsImage,
                                   Helpers::GetSequentialFileName("CopiedPixels",
                                                                  this->NumberOfFinishedPatches, "png", 3));
        ITKHelpers::WriteImage(this->MaskImage,
                               Helpers::GetSequentialFileName("Mask_Before",
                                                              this->NumberOfFinishedPatches, "png", 3));
      }
    }

    // Mark all the pixels in this region as filled in the mask.
//    std::cout << "InpaintingVisitor::FinishVertex() fill the mask" << std::endl;
    ITKHelpers::SetRegionToConstant(this->MaskImage, regionToFinish,
                                    this->MaskImage->GetValidValue());

    // Write an image of where the source and target patch were in this iteration.
//    if(this->DebugImages && this->Image)
//    {
//      typename TImage::PixelType red;
//      red.Fill(0);
//      red[0] = 255;

//      typename TImage::PixelType green;
//      green.Fill(0);
//      green[1] = 255;

//      typename TImage::Pointer patchesCopiedImage = TImage::New();
//      ITKHelpers::DeepCopy(this->Image, patchesCopiedImage.GetPointer());
//      ITKHelpers::OutlineRegion(patchesCopiedImage.GetPointer(), regionToFinish, red);

//      ITKHelpers::OutlineRegion(patchesCopiedImage.GetPointer(), sourceRegion, green);

//      ITKHelpers::WriteRGBImage(patchesCopiedImage.GetPointer(), Helpers::GetSequentialFileName("PatchesCopied", this->NumberOfFinishedPatches, "png", 3));

//      if(this->DebugLevel > 1)
//      {
//        ITKHelpers::WriteImage(this->MaskImage, Helpers::GetSequentialFileName("Mask_After", this->NumberOfFinishedPatches, "png", 3));
//      }
//    }

    // Update the priority function. This must be done AFTER the mask is filled,
    // as some of the Priority functors only compute things on the hole boundary, or only
    // use data from the valid region of the image (indicated by valid pixels in the mask).
//    std::cout << "InpaintingVisitor::FinishVertex() update priority" << std::endl;
    this->PriorityFunction->Update(sourceNode, targetNode, this->NumberOfFinishedPatches);
//    std::cout << "InpaintingVisitor::FinishVertex() finish update priority" << std::endl;
    // Initialize (if requested) all vertices in the newly filled region because they may now be valid source nodes.
    // (You may not want to do this in some cases (i.e. if the descriptors needed cannot be
    // computed on newly filled regions))

    if(this->AllowNewPatches)
    {
//      std::cout << "Initializing new vertices..." << std::endl;
      itk::ImageRegionConstIteratorWithIndex<Mask> gridIterator(this->MaskImage, regionToFinish);
      while(!gridIterator.IsAtEnd())
      {
        VertexDescriptorType v = Helpers::ConvertFrom<VertexDescriptorType, itk::Index<2> >(gridIterator.GetIndex());

        InitializeVertex(v);
        ++gridIterator;
      }
    }

    // Add pixels that are on the new boundary to the queue, and mark other pixels as not in the queue.
//    std::cout << "InpaintingVisitor::FinishVertex() iterator" << std::endl;
    itk::ImageRegionConstIteratorWithIndex<Mask> imageIterator(this->MaskImage, regionToFinish);
//    std::cout << "InpaintingVisitor::FinishVertex() finish iterator" << std::endl;

    typedef typename TBoundaryNodeQueue::HandleType HandleType;

    // Naive, unparallelizable way
//    while(!imageIterator.IsAtEnd())
//    {
//      VertexDescriptorType v = Helpers::ConvertFrom<VertexDescriptorType, itk::Index<2> >(imageIterator.GetIndex());

//      if(this->MaskImage->HasHoleNeighbor(imageIterator.GetIndex()))
//      {
//        float priority = this->PriorityFunction->ComputePriority(imageIterator.GetIndex());
//        this->BoundaryNodeQueue.push_or_update(v, priority);
//      }
//      else
//      {
//        this->BoundaryNodeQueue.mark_as_invalid(v);
//      }

//      ++imageIterator;
//    }

    // Parallelizable way - collect the pixels that need their priority computed
//    std::cout << "InpaintingVisitor::FinishVertex() Parallelizable way" << std::endl;
    typedef std::vector<itk::Index<2> > IndexVectorType;
    IndexVectorType pixelsToCompute;
    while(!imageIterator.IsAtEnd())
    {
      VertexDescriptorType v = Helpers::ConvertFrom<VertexDescriptorType, itk::Index<2> >(imageIterator.GetIndex());

      if(this->MaskImage->GetPixel(imageIterator.GetIndex()) == this->MaskImage->GetValidValue() &&
         this->MaskImage->HasHoleNeighbor(imageIterator.GetIndex()))
      {
        pixelsToCompute.push_back(imageIterator.GetIndex());
      }
      else
      {
        this->BoundaryNodeQueue->mark_as_invalid(v);
      }

      ++imageIterator;
    }

//    std::cout << "InpaintingVisitor::FinishVertex() update queue" << std::endl;
    #pragma omp parallel for
    for(IndexVectorType::const_iterator pixelIterator = pixelsToCompute.begin();
        pixelIterator < pixelsToCompute.end(); ++pixelIterator)
    {
      VertexDescriptorType v = Helpers::ConvertFrom<VertexDescriptorType, itk::Index<2> >(*pixelIterator);
      float priority = this->PriorityFunction->ComputePriority(*pixelIterator);
      #pragma omp critical // There are weird crashes without this guard
      this->BoundaryNodeQueue->push_or_update(v, priority);
    }

    // std::cout << "FinishVertex after traversing finishing region there are "
    //           << BoostHelpers::CountValidQueueNodes(BoundaryNodeQueue, BoundaryStatusMap)
    //           << " valid nodes in the queue." << std::endl;

    // Sometimes pixels that are not in the finishing region that were boundary pixels are no longer
    // boundary pixels after the filling. Check for these.
    // E.g. (H=hole, B=boundary, V=valid, Q=query, F=filled, N=new boundary,
    // R=old boundary pixel that needs to be removed because it is no longer on the boundary)
    // Before filling

    /* V V V B H H H H
     * V V V B H H H H
     * V V V B H H H H
     * V V V B B Q B B
     * V V V V V V V V
     */
    // After filling

    /* V V V B H H H H
     * V V V B H H H H
     * V V V B F F F H
     * V V V B F F F B
     * V V V V F F F V
     */
    // New boundary
    /* V V V B H H H H
     * V V V B H H H H
     * V V V B N N N H
     * V V V R F F N B
     * V V V V F F F V
     */

    // Expand the region
//    std::cout << "InpaintingVisitor::FinishVertex() expand" << std::endl;
    itk::ImageRegion<2> expandedRegion =
        ITKHelpers::GetRegionInRadiusAroundPixel(indexToFinish, PatchHalfWidth + 1);
    // Make sure the region is entirely inside the image (to allow for target regions near the image boundary)
    expandedRegion.Crop(this->FullRegion);
    std::vector<itk::Index<2> > boundaryPixels =
        ITKHelpers::GetBoundaryPixels(expandedRegion);
//    std::cout << "InpaintingVisitor::FinishVertex() boundary pixels" << std::endl;
    for(unsigned int i = 0; i < boundaryPixels.size(); ++i)
    {
      // the region (the entire image) can be omitted, as this function automatically checks if the pixels are inside the image
      if(!this->MaskImage->HasHoleNeighbor(boundaryPixels[i]))
      {
        VertexDescriptorType v =
            Helpers::ConvertFrom<VertexDescriptorType, itk::Index<2> >(boundaryPixels[i]);

        put(this->BoundaryNodeQueue->BoundaryStatusMap, v, false);
      }
    }

    // std::cout << "FinishVertex after removing stale nodes outside finishing region there are "
    //               << BoostHelpers::CountValidQueueNodes(BoundaryNodeQueue, BoundaryStatusMap)
    //               << " valid nodes in the queue." << std::endl;

    this->NumberOfFinishedPatches++;

//    std::cout << "Leave InpaintingVisitor::FinishVertex()" << std::endl;
  } // end FinishVertex

  void InpaintingComplete() const
  {
    std::cout << "Inpainting complete!" << std::endl;
    // We prefer to write the final image in the calling function, as there we will know what type it is (i.e. do we need to convert back to RGB? etc.)
  }

}; // end InpaintingVisitor

#endif

max_stars_repo_name: jingtangliao/ff

max_issues_repo_name: jingtangliao/ff

max_forks_repo_name: jingtangliao/ff


text:
/// \file   transfer.cpp
///
/// \brief  A transfer message moves one or properties from one agent to
///         another. The message is specialised for fungible and infungible
///         property types, as it will apply the appropriate datastructure
///         to hold these properties.
///
/// \authors    Maarten P. Scholl
/// \date       2018-06-04
/// \copyright  Copyright 2017-2019 The Institute for New Economic Thinking,
/// Oxford Martin School, University of Oxford
///
///             Licensed under the Apache License, Version 2.0 (the "License");
///             you may not use this file except in compliance with the License.
///             You may obtain a copy of the License at
///
///                 http://www.apache.org/licenses/LICENSE-2.0
///
///             Unless required by applicable law or agreed to in writing,
///             software distributed under the License is distributed on an "AS
///             IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
///             express or implied. See the License for the specific language
///             governing permissions and limitations under the License.
///
///             You may obtain instructions to fulfill the attribution
///             requirements in CITATION.cff
///
#include <esl/interaction/transfer.hpp>

#include <boost/serialization/export.hpp>
#include <boost/serialization/shared_ptr.hpp>

//BOOST_CLASS_EXPORT(esl::interaction::transfer)

max_stars_repo_name: rht/ESL

max_issues_repo_name: rht/ESL

max_forks_repo_name: vishalbelsare/ESL


text:
//
// Copyright (c) 2013-2017 Vinnie Falco (vinnie dot falco at gmail dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//

//[http_example_get

#include <beast/core.hpp>
#include <beast/http.hpp>
#include <boost/asio.hpp>
#include <boost/lexical_cast.hpp>
#include <iostream>
#include <string>

int main()
{
    // Normal boost::asio setup
    std::string const host = "www.example.com";
    boost::asio::io_service ios;
    boost::asio::ip::tcp::resolver r{ios};
    boost::asio::ip::tcp::socket sock{ios};
    boost::asio::connect(sock,
        r.resolve(boost::asio::ip::tcp::resolver::query{host, "http"}));

    // Send HTTP request using beast
    beast::http::request<beast::http::string_body> req;
    req.method(beast::http::verb::get);
    req.target("/");
    req.version = 11;
    req.insert(beast::http::field::host, host + ":" +
        boost::lexical_cast<std::string>(sock.remote_endpoint().port()));
    req.insert(beast::http::field::user_agent, "Beast");
    req.prepare();
    beast::http::write(sock, req);

    // Receive and print HTTP response using beast
    beast::flat_buffer b;
    beast::http::response<beast::http::dynamic_body> res;
    beast::http::read(sock, b, res);
    std::cout << res << std::endl;
}

//]

max_stars_repo_name: vinniefalco/rippled

max_issues_repo_name: vinniefalco/rippled

max_forks_repo_name: vinniefalco/rippled


text:
/**
 * @file upwindfinitevolume_main.cc
 * @brief NPDE homework UpwindFiniteVolume code
 * @author Philipp Egg
 * @date 08.09.2020
 * @copyright Developed at ETH Zurich
 */

#include <lf/assemble/assemble.h>
#include <lf/geometry/geometry.h>
#include <lf/io/gmsh_reader.h>
#include <lf/mesh/hybrid2d/hybrid2d.h>
#include <lf/mesh/mesh.h>
#include <lf/refinement/refinement.h>

#include <Eigen/Core>
#include <Eigen/SparseCore>
#include <Eigen/SparseLU>
#include <cmath>
#include <iostream>
#include <memory>
#include <vector>

#include "upwindfinitevolume.h"

int main() {
  /* SAM_LISTING_BEGIN_1 */
#if SOLUTION
  // Read in mesh
  auto mesh_factory = std::make_unique<lf::mesh::hybrid2d::MeshFactory>(2);
  lf::io::GmshReader reader(std::move(mesh_factory),
                            CURRENT_SOURCE_DIR "/mesh.msh");

  std::shared_ptr<lf::mesh::Mesh> mesh_p = reader.mesh();

  double eps = 1e-6;

  auto v = [](Eigen::Vector2d x) -> Eigen::Vector2d {
    return Eigen::Vector2d(1, 0.5 - x[1]);
  };

  auto u = [](Eigen::Vector2d x) -> double {
    return std::sin(4 * M_PI * x[1]) * std::exp(-x[0]);
  };

  auto f = [&u, eps](Eigen::Vector2d x) -> double {
    return eps * (1.0 - 16.0 * M_PI * M_PI) * u(x) - 2 * u(x) +
           (0.5 - x[1]) * 4 * M_PI * std::cos(4.0 * M_PI * x[1]) *
               std::exp(-x[0]);
  };

  // Convergence study
  auto mesh_seq_p{
      lf::refinement::GenerateMeshHierarchyByUniformRefinemnt(mesh_p, 6)};
  int num_meshes = mesh_seq_p->NumLevels();

  std::vector<double> vec_l2error;
  std::vector<double> vec_Ndofs;
  for (int level = 0; level < num_meshes; ++level) {
    // Get the current mesh
    auto cur_mesh = mesh_seq_p->getMesh(level);

    // Create a DOF Hander for the current mesh
    const lf::assemble::UniformFEDofHandler cur_dofh(
        cur_mesh, {{lf::base::RefEl::kPoint(), 1},
                   {lf::base::RefEl::kSegment(), 0},
                   {lf::base::RefEl::kTria(), 0},
                   {lf::base::RefEl::kQuad(), 0}});
    int N_dofs = cur_dofh.NumDofs();

    lf::assemble::COOMatrix<double> A(N_dofs, N_dofs);
    UpwindFiniteVolume::ElementMatrixProvider my_mat_provider(v, eps);
    lf::assemble::AssembleMatrixLocally(0, cur_dofh, cur_dofh, my_mat_provider,
                                        A);

    Eigen::VectorXd phi(N_dofs);
    phi.setZero();
    UpwindFiniteVolume::ElementVectorProvider my_vec_provider(f);
    lf::assemble::AssembleVectorLocally(0, cur_dofh, my_vec_provider, phi);

    // Dirichlet boundary condition
    auto bd_flags{lf::mesh::utils::flagEntitiesOnBoundary(cur_mesh, 2)};
    auto my_selector = [&cur_dofh, &u, &bd_flags](unsigned int dof_idx) {
      if (bd_flags(cur_dofh.Entity(dof_idx))) {
        const lf::mesh::Entity &entity{cur_dofh.Entity(dof_idx)};
        const lf::geometry::Geometry *geo_p = entity.Geometry();
        const Eigen::MatrixXd corners = lf::geometry::Corners(*geo_p);
        Eigen::Vector2d corner = corners.col(0);
        return std::make_pair(true, u(corner));
      } else {
        return std::make_pair(false, 42.0);
      }
    };
    lf::assemble::FixFlaggedSolutionComponents<double>(my_selector, A, phi);

    const Eigen::SparseMatrix<double> A_crs = A.makeSparse();

    // Numerical Solution
    Eigen::SparseLU<Eigen::SparseMatrix<double>> solver;
    solver.compute(A_crs);
    if (solver.info() != Eigen::Success) {
      printf("Decomposition Failed.\n");
    }
    Eigen::VectorXd sol_vec = solver.solve(phi);

    // Exact Solution
    Eigen::VectorXd exact_sol(N_dofs);
    for (int i = 0; i < N_dofs; ++i) {
      const lf::mesh::Entity &entity{cur_dofh.Entity(i)};
      const lf::geometry::Geometry *geo_p = entity.Geometry();
      const Eigen::MatrixXd corners = lf::geometry::Corners(*geo_p);
      exact_sol[i] = u(corners.col(0));
    }

    // L2 Error
    double l2_error = (sol_vec - exact_sol).norm() / N_dofs;
    vec_l2error.push_back(l2_error);
    vec_Ndofs.push_back(N_dofs);
  }

  for (int i = 0; i < vec_l2error.size(); ++i) {
    if (i > 0) {
      double conv_rate =
          (std::log(vec_l2error.at(i - 1)) - std::log(vec_l2error.at(i))) /
          (std::log(vec_Ndofs.at(i)) - std::log(vec_Ndofs.at(i - 1)));
      std::cout << "N_dofs: " << vec_Ndofs.at(i)
                << "; L2 Error: " << vec_l2error.at(i)
                << "; Conv. rate: " << conv_rate << std::endl;
    } else {
      std::cout << "N_dofs: " << vec_Ndofs.at(i)
                << "; L2 Error: " << vec_l2error.at(i) << std::endl;
    }
  }
  /* SAM_LISTING_END_1 */

#else
  //====================
  // Your code goes here
  //====================
#endif
  return 0;
}

ext: cc


text:
// Copyright (c) 2020, Ryohei Sasaki
// All rights reserved.
//
// Software License Agreement (BSD License 2.0)
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
//  * Redistributions of source code must retain the above copyright
//    notice, this list of conditions and the following disclaimer.
//  * Redistributions in binary form must reproduce the above
//    copyright notice, this list of conditions and the following
//    disclaimer in the documentation and/or other materials provided
//    with the distribution.
//  * Neither the name of {copyright_holder} nor the names of its
//    contributors may be used to endorse or promote products derived
//    from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#ifndef KALMAN_FILTER_LOCALIZATION__EKF_LOCALIZATION_COMPONENT_HPP_
#define KALMAN_FILTER_LOCALIZATION__EKF_LOCALIZATION_COMPONENT_HPP_

#if __cplusplus
extern "C" {
#endif

// The below macros are taken from https://gcc.gnu.org/wiki/Visibility and from
// demos/composition/include/composition/visibility_control.h at https://github.com/ros2/demos
#if defined _WIN32 || defined __CYGWIN__
  #ifdef __GNUC__
    #define KFL_EKFL_EXPORT __attribute__ ((dllexport))
    #define KFL_EKFL_IMPORT __attribute__ ((dllimport))
  #else
    #define KFL_EKFL_EXPORT __declspec(dllexport)
    #define KFL_EKFL_IMPORT __declspec(dllimport)
  #endif
  #ifdef KFL_EKFL_BUILDING_DLL
    #define KFL_EKFL_PUBLIC KFL_EKFL_EXPORT
  #else
    #define KFL_EKFL_PUBLIC KFL_EKFL_IMPORT
  #endif
  #define KFL_EKFL_PUBLIC_TYPE KFL_EKFL_PUBLIC
  #define KFL_EKFL_LOCAL
#else
  #define KFL_EKFL_EXPORT __attribute__ ((visibility("default")))
  #define KFL_EKFL_IMPORT
  #if __GNUC__ >= 4
    #define KFL_EKFL_PUBLIC __attribute__ ((visibility("default")))
    #define KFL_EKFL_LOCAL  __attribute__ ((visibility("hidden")))
  #else
    #define KFL_EKFL_PUBLIC
    #define KFL_EKFL_LOCAL
  #endif
  #define KFL_EKFL_PUBLIC_TYPE
#endif

#if __cplusplus
}  // extern "C"
#endif

#include <kalman_filter_localization/ekf.hpp>

#include <rclcpp/rclcpp.hpp>
#include <geometry_msgs/msg/pose_stamped.hpp>
#include <geometry_msgs/msg/transform.hpp>
#include <geometry_msgs/msg/transform_stamped.hpp>
#include <geometry_msgs/msg/vector3_stamped.hpp>
#include <sensor_msgs/msg/imu.hpp>
#include <nav_msgs/msg/odometry.hpp>
#include <tf2/transform_datatypes.h>
#include <tf2/convert.h>
#include <tf2/LinearMath/Matrix3x3.h>
#include <tf2_eigen/tf2_eigen.h>
#include <tf2_ros/buffer.h>
#include <tf2_ros/transform_listener.h>
#include <tf2_geometry_msgs/tf2_geometry_msgs.h>
#include <tf2_sensor_msgs/tf2_sensor_msgs.h>

#include <rclcpp_components/register_node_macro.hpp>

#include <Eigen/Core>

#include <string>

namespace kalman_filter_localization
{
class EkfLocalizationComponent : public rclcpp::Node
{
public:
  KFL_EKFL_PUBLIC
  explicit EkfLocalizationComponent(const rclcpp::NodeOptions & options);

private:
  std::string reference_frame_id_;
  std::string robot_frame_id_;
  std::string initial_pose_topic_;
  std::string imu_topic_;
  std::string odom_topic_;
  std::string gnss_pose_topic_;
  int pub_period_;

  double var_imu_w_;
  double var_imu_acc_;
  double var_gnss_xy_;
  double var_gnss_z_;
  Eigen::Vector3d var_gnss_;
  double var_odom_xyz_;
  Eigen::Vector3d var_odom_;
  bool use_gnss_;
  bool use_odom_;

  bool initial_pose_recieved_{false};

  geometry_msgs::msg::PoseStamped current_pose_;
  rclcpp::Time current_stamp_;

  EKFEstimator ekf_;

  rclcpp::Subscription<geometry_msgs::msg::PoseStamped>::SharedPtr sub_initial_pose_;
  rclcpp::Subscription<sensor_msgs::msg::Imu>::SharedPtr sub_imu_;
  rclcpp::Subscription<nav_msgs::msg::Odometry>::SharedPtr sub_odom_;
  rclcpp::Subscription<geometry_msgs::msg::PoseStamped>::SharedPtr sub_gnss_pose_;
  rclcpp::Publisher<geometry_msgs::msg::PoseStamped>::SharedPtr current_pose_pub_;
  rclcpp::TimerBase::SharedPtr timer_;
  rclcpp::Clock clock_;
  tf2_ros::Buffer tfbuffer_;
  tf2_ros::TransformListener listener_;
  void predictUpdate(const sensor_msgs::msg::Imu imu_msg);
  void measurementUpdate(
    const geometry_msgs::msg::PoseStamped pose_msg,
    const Eigen::Vector3d variance);
  void broadcastPose();

  geometry_msgs::msg::PoseStamped current_pose_odom_;
  Eigen::Matrix4d previous_odom_mat_{Eigen::Matrix4d::Identity()};

  enum STATE
  {
    X  = 0, Y = 1, Z = 2,
    VX = 3, VY = 4, VZ = 5,
    QX = 6, QY = 7, QZ = 8, QW = 9,
  };
};
}  // namespace kalman_filter_localization

#endif  // KALMAN_FILTER_LOCALIZATION__EKF_LOCALIZATION_COMPONENT_HPP_


text:
#include "conditional_algorithm.h"

#include <Eigen/Dense>

#include "base_algorithm.h"
#include "src/collectors/base_collector.h"
#include "src/mixings/conditional_mixing.h"

void ConditionalAlgorithm::initialize() {
  BaseAlgorithm::initialize();
  cond_mixing = std::dynamic_pointer_cast<ConditionalMixing>(mixing);
}

//! \param grid Grid of points in matrix form to evaluate the density on
//! \param coll Collector containing the algorithm chain
Eigen::MatrixXd ConditionalAlgorithm::eval_lpdf(
    BaseCollector *const collector, const Eigen::MatrixXd &grid,
    const Eigen::MatrixXd &hier_covariates /*= Eigen::MatrixXd(0, 0)*/,
    const Eigen::MatrixXd &mix_covariates /*= Eigen::MatrixXd(0, 0)*/) {
  return Eigen::MatrixXd::Zero(1, 1);  // TODO
}

max_stars_repo_name: ricardaxel/bayesmix

max_issues_repo_name: ricardaxel/bayesmix

max_forks_repo_name: ricardaxel/bayesmix


text:
/*  $Id$
 *
 *  Copyright 2010 Anders Wallin (anders.e.e.wallin "at" gmail.com)
 *
 *  This file is part of OpenCAMlib.
 *
 *  OpenCAMlib is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  OpenCAMlib 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 OpenCAMlib.  If not, see <http://www.gnu.org/licenses/>.
*/

#ifndef WATERLINE_PY_H
#define WATERLINE_PY_H

#include <boost/python.hpp>
#include <boost/foreach.hpp>

#include "waterline.hpp"

namespace ocl
{

/// Python wrapper for Waterline
class Waterline_py : public Waterline {
    public:
        Waterline_py() : Waterline() {}
        ~Waterline_py() {
            std::cout << "~Waterline_py()\n";
        }
        /// return loop as a list of lists to python
        boost::python::list py_getLoops() const {
            boost::python::list loop_list;
            BOOST_FOREACH( std::vector<Point> loop, this->loops ) {
                boost::python::list point_list;
                BOOST_FOREACH( Point p, loop ) {
                    point_list.append( p );
                }
                loop_list.append(point_list);
            }
            return loop_list;
        }
        /// return a list of yfibers to python
        boost::python::list py_getXFibers() const {
            boost::python::list flist;
            std::vector<Fiber> xfibers = *( subOp[0]->getFibers() );
            BOOST_FOREACH( Fiber f, xfibers ) {
                Fiber_py f2(f);
                flist.append(f2);
            }
            return flist;
        }
        /// return a list of yfibers to python
        boost::python::list py_getYFibers() const {
            boost::python::list flist;
            std::vector<Fiber> yfibers = *( subOp[1]->getFibers() );
            BOOST_FOREACH( Fiber f, yfibers ) {
                Fiber_py f2(f);
                flist.append(f2);
            }
            return flist;
        }

};

} // end namespace

#endif

max_stars_repo_name: JohnyEngine/CNC

max_issues_repo_name: JohnyEngine/CNC

max_forks_repo_name: JohnyEngine/CNC


text:
#pragma once

#include <cmath>

#include <ros/ros.h>
#include <ct/optcon/optcon.h>
#include <lqr_controller/declarations_euler.hpp>
#include <nav_msgs/Odometry.h>
#include <Eigen/Geometry>

namespace LQR {
class LQR_Solver {
  public:
    /*!
     * Constructor.
     * @param nodeHandle the ROS node handle.
     */
    LQR_Solver(ros::NodeHandle& nodeHandle);

    /*!
     * Destructor.
     */
    virtual ~LQR_Solver();

    control_vector_t output;

    ct::core::FeedbackMatrix<nStates, nControls> K_;
    control_vector_t uref_;
    state_vector_t xerror;

   private:

    /*!
     * ROS topic callback method.
     * @param message the received message.
     */
    void topicCallback(const nav_msgs::Odometry::ConstPtr& msg);

    //! ROS node handle.
    ros::NodeHandle& nodeHandle_;

    //! ROS topic subscriber.
    ros::Subscriber subscriber_;

    //! ROS topic name to subscribe to.
    std::string subscriberTopic_;

    //! State and control matrix dimensions
    const size_t state_dim = nStates;
    const size_t control_dim = nControls;

    control_vector_t u_;

    state_matrix_t A_;
    control_gain_matrix_t B_;
    ros::Time callBack_;
    state_vector_t x_;
    state_vector_t xref_;

    ct::optcon::TermQuadratic<nStates, nControls> quadraticCost_;
    ct::optcon::TermQuadratic<nStates, nControls>::state_matrix_t Q_;
    ct::optcon::TermQuadratic<nStates, nControls>::control_matrix_t R_;
    ct::optcon::LQR<nStates, nControls> lqrSolver_;

    state_matrix_t A_quadrotor(const state_vector_t& x, const control_vector_t& u);
    control_gain_matrix_t B_quadrotor(const state_vector_t& x, const control_vector_t& u);
  };

} /* namespace */

max_stars_repo_name: llanesc/lqr-tracking

max_issues_repo_name: llanesc/lqr-tracking

max_forks_repo_name: llanesc/lqr-tracking


text:
#ifndef BOOST_TEXT_DETAIL_SERIALIZATION_HPP
#define BOOST_TEXT_DETAIL_SERIALIZATION_HPP

#include <boost/text/collation_table.hpp>

#include <boost/endian/buffers.hpp>

namespace boost { namespace text { namespace detail {

    enum current_version : int { serialization_version = 0 };

    struct serialized_collation_element_t
    {
        endian::little_uint32_buf_t l1_;
        endian::little_uint16_buf_t l2_;
        endian::little_uint16_buf_t l3_;
        endian::little_uint32_buf_t l4_;
    };

    inline serialized_collation_element_t convert(collation_element ce)
    {
        serialized_collation_element_t retval;
        retval.l1_ = ce.l1_;
        retval.l2_ = ce.l2_;
        retval.l3_ = ce.l3_;
        retval.l4_ = ce.l4_;
        return retval;
    }

    inline collation_element convert(serialized_collation_element_t sce)
    {
        collation_element retval;
        retval.l1_ = sce.l1_.value();
        retval.l2_ = sce.l2_.value();
        retval.l3_ = sce.l3_.value();
        retval.l4_ = sce.l4_.value();
        return retval;
    }

    struct serialized_nonsimple_script_reorder_t
    {
        serialized_collation_element_t first_;
        serialized_collation_element_t last_;
        endian::little_uint32_buf_t lead_byte_;
    };

    inline serialized_nonsimple_script_reorder_t
    convert(nonsimple_script_reorder nsr)
    {
        serialized_nonsimple_script_reorder_t retval;
        retval.first_ = convert(nsr.first_);
        retval.last_ = convert(nsr.last_);
        retval.lead_byte_ = nsr.lead_byte_;
        return retval;
    }

    inline nonsimple_script_reorder
    convert(serialized_nonsimple_script_reorder_t snsr)
    {
        nonsimple_script_reorder retval;
        retval.first_ = convert(snsr.first_);
        retval.last_ = convert(snsr.last_);
        retval.lead_byte_ = snsr.lead_byte_.value();
        return retval;
    }

    struct header_t
    {
        header_t() {}
        header_t(collation_table_data const & table)
        {
            version_ = detail::serialization_version;
            collation_elements_ = int(table.collation_element_vec_.size());
            trie_ = int(table.trie_.size());
            nonsimple_reorders_ = int(table.nonsimple_reorders_.size());
            simple_reorders_ = int(table.simple_reorders_.size());
            have_strength_ = !!table.strength_;
            if (table.strength_)
                strength_ = uint8_t(*table.strength_);
            have_weighting_ = !!table.weighting_;
            if (table.weighting_)
                weighting_ = uint8_t(*table.weighting_);
            have_l2_order_ = !!table.l2_order_;
            if (table.l2_order_)
                l2_order_ = uint8_t(*table.l2_order_);
            have_case_level_ = !!table.case_level_;
            if (table.case_level_)
                case_level_ = uint8_t(*table.case_level_);
            have_case_first_ = !!table.case_first_;
            if (table.case_first_)
                case_first_ = uint8_t(*table.case_first_);
        }

        endian::little_int32_buf_t version_;

        endian::little_int32_buf_t collation_elements_;
        endian::little_int32_buf_t trie_;
        endian::little_int32_buf_t nonsimple_reorders_;
        endian::little_int32_buf_t simple_reorders_;

        endian::little_uint8_buf_t have_strength_;
        endian::little_uint8_buf_t strength_;
        endian::little_uint8_buf_t have_weighting_;
        endian::little_uint8_buf_t weighting_;
        endian::little_uint8_buf_t have_l2_order_;
        endian::little_uint8_buf_t l2_order_;
        endian::little_uint8_buf_t have_case_level_;
        endian::little_uint8_buf_t case_level_;
        endian::little_uint8_buf_t have_case_first_;
        endian::little_uint8_buf_t case_first_;
    };

    void header_to_table(header_t const & header, collation_table_data & table)
    {
        if (header.have_strength_.value())
            table.strength_ = collation_strength(header.strength_.value());
        if (header.have_weighting_.value())
            table.weighting_ = variable_weighting(header.weighting_.value());
        if (header.have_l2_order_.value())
            table.l2_order_ = l2_weight_order(header.l2_order_.value());
        if (header.have_case_level_.value())
            table.case_level_ = case_level(header.case_level_.value());
        if (header.have_case_first_.value())
            table.case_first_ = case_first(header.case_first_.value());
    }

    struct iterator_tag_t
    {};

    template<typename Source>
    struct tag
    {
        using type = iterator_tag_t;
    };

    template<typename Source>
    using tag_t = typename tag<Source>::type;

    template<typename Source, typename T>
    void read_bytes(Source & in, T & x)
    {
        read_bytes(in, x, tag_t<Source>{});
    }

    template<typename T, typename Sink>
    void write_bytes(T const & x, Sink & out)
    {
        write_bytes(x, out, tag_t<Sink>{});
    }

    template<typename Source>
    void read_trie(Source & in, collation_trie_t & trie, int size)
    {
        for (int i = 0; i < size; ++i) {
            endian::little_int32_buf_t key_size;
            read_bytes(in, key_size);
            collation_trie_key<32> key;
            key.size_ = key_size.value();
            for (int j = 0, end = key.size_; j < end; ++j) {
                endian::little_uint32_buf_t cp;
                read_bytes(in, cp);
                key.cps_.values_[j] = cp.value();
            }
            endian::little_uint16_buf_t first;
            read_bytes(in, first);
            endian::little_uint16_buf_t last;
            read_bytes(in, last);
            collation_elements const value{first.value(), last.value()};
            trie.insert(key, value);
        }
    }

    template<typename Sink>
    void write_trie(collation_trie_t const & trie, Sink & out)
    {
        for (auto const & element : trie) {
            endian::little_int32_buf_t key_size;
            key_size = element.key.size_;
            write_bytes(key_size, out);
            for (int j = 0, end = element.key.size_; j < end; ++j) {
                endian::little_uint32_buf_t cp;
                cp = element.key.cps_.values_[j];
                write_bytes(cp, out);
            }
            endian::little_uint16_buf_t first;
            first = element.value.first_;
            write_bytes(first, out);
            endian::little_uint16_buf_t last;
            last = element.value.last_;
            write_bytes(last, out);
        }
    }

    template<typename Source>
    void read_collation_elements(
        Source & in,
        std::vector<collation_element> & collation_element_vec,
        collation_element const *& collation_elements,
        int size)
    {
        if (size) {
            collation_element_vec.resize(size);
            for (int i = 0; i < size; ++i) {
                serialized_collation_element_t sce;
                read_bytes(in, sce);
                collation_element_vec[i] = convert(sce);
            }
        } else {
            collation_elements = collation_elements_ptr();
        }
    }

    template<typename Sink>
    void write_collation_elements(
        std::vector<collation_element> const & collation_element_vec,
        collation_element const * collation_elements,
        Sink & out)
    {
        for (auto ce : collation_element_vec) {
            serialized_collation_element_t const sce = convert(ce);
            write_bytes(sce, out);
        }
    }

    template<typename Source>
    void read_nonsimple_reorders(
        Source & in, nonsimple_reorders_t & nonsimple_reorders, int size)
    {
        nonsimple_reorders.resize(size);
        for (int i = 0; i < size; ++i) {
            serialized_nonsimple_script_reorder_t snsr;
            read_bytes(in, snsr);
            nonsimple_reorders[i] = convert(snsr);
        }
    }

    template<typename Sink>
    void write_nonsimple_reorders(
        nonsimple_reorders_t const & nonsimple_reorders, Sink & out)
    {
        for (auto reorder : nonsimple_reorders) {
            serialized_nonsimple_script_reorder_t const snsr = convert(reorder);
            write_bytes(snsr, out);
        }
    }

    template<typename Source>
    void read_simple_reorders(
        Source & in, std::array<uint32_t, 256> & simple_reorders, int size)
    {
        BOOST_ASSERT(size == 256);
        for (int i = 0; i < size; ++i) {
            endian::little_uint32_buf_t r;
            read_bytes(in, r);
            simple_reorders[i] = r.value();
        }
    }

    template<typename Sink>
    void write_simple_reorders(
        std::array<uint32_t, 256> const & simple_reorders, Sink & out)
    {
        for (auto reorder : simple_reorders) {
            endian::little_uint32_buf_t const r{reorder};
            write_bytes(r, out);
        }
    }

}}}

#endif

max_stars_repo_name: jan-moeller/text

max_issues_repo_name: jan-moeller/text

max_forks_repo_name: jan-moeller/text


text:
#include <boost/python.hpp>

#include "OpenPGP/Encryptions/AES.h"

void AES_init()
{
boost::python::class_<AES, boost::python::bases<SymAlg>>("AES")
    .def(boost::python::init<const std::string &>())
    .def("decrypt", &AES::decrypt)
    .def("blocksize", &AES::blocksize)
    .def("encrypt", &AES::encrypt)
    .def("setkey", &AES::setkey)
    ;
}

max_stars_repo_name: mugwort-rc/pyOpenPGP

max_issues_repo_name: mugwort-rc/pyOpenPGP

max_forks_repo_name: mugwort-rc/pyOpenPGP


text:
/*
 * Copyright 2019 Tom van Dijk, Johannes Kepler University Linz
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef ZLKQ_HPP
#define ZLKQ_HPP

#include <boost/dynamic_bitset.hpp>
#include <vector>

#include "oink.hpp"
#include "solver.hpp"

namespace pg {

/**
 * This is an implementation of Pawel Parys's Zielonka variant
 * as presented by himself on his website.
 * https://www.mimuw.edu.pl/~parys/publications/2018-parity-algorithm.pdf
 *
 * I modified the algorithm to produce a strategy as well.
 */

class ZLKQSolver : public Solver
{
public:
    ZLKQSolver(Oink *oink, Game *game);
    virtual ~ZLKQSolver();

    virtual void run();

    typedef boost::dynamic_bitset<unsigned long long> bitset;

protected:
    int iterations = 0;

    uintqueue Q;
    int *str;

    bitset W0, W1; // current approximation of winning areas

    inline void attractVertices(const int pl, const int v, bitset &Z, bitset &R, bitset &Y);
    void solve(bitset &Subgame, int vtop, int pr, int pe, int po);
};

}

#endif

max_stars_repo_name: mpomarlan/oink

max_issues_repo_name: mpomarlan/oink

max_forks_repo_name: mpomarlan/oink


text:
#include "cam.h"

#include <QGLViewer/camera.h>

#include <QDebug>

#include <boost/shared_ptr.hpp>
#include <luabind/adopt_policy.hpp>

using namespace std;

std::ostream& operator<<(std::ostream& ostream, const Cam& cam) {
  ostream << cam.toString().toAscii().data() << "[ pos: " << "]";

  return ostream;
}

Cam::Cam(QObject *parent) : Camera() {
    setParent(parent);
    // qDebug() << "Cam::Cam()";
//    setUpVector(Vec(0,0,-1), false);
//    setViewDirection(Vec(0,1,0));
}

Cam::~Cam() {
    // qDebug() << "Cam::~Cam()";
}

QString Cam::toString() const {
  return QString("Cam");
}

#include <luabind/operator.hpp>

void Cam::luaBind(lua_State *s) {
  using namespace luabind;

  open(s);

  module(s)
    [
     class_<Camera, boost::shared_ptr<Camera> >("Camera")
          .def(constructor<>())
     ];

  module(s)
    [
     class_<Cam,Camera>("Cam")
          .def(constructor<>())
          .def(constructor<QObject *>())

     .def("setFieldOfView", &Cam::setFieldOfView)
     .def("setHorizontalFieldOfView", &Cam::setHorizontalFieldOfView)

     .property("pos",
               (btVector3(Cam::*)(void))&Cam::getPosition,
               (void(Cam::*)(const btVector3&))&Cam::setPosition)
     .property("look",
               (btVector3(Cam::*)(void))&Cam::getLookAt,
               (void(Cam::*)(const btVector3&))&Cam::setLookAt)
     .def(tostring(const_self))
     ];
}

void Cam::setPosition(const btVector3& v) {
  Camera::setPosition(Vec(v[0], v[1], v[2]));
}

btVector3 Cam::getPosition() const {
  Vec pos = Camera::position();
  return btVector3(pos[0], pos[1], pos[2]);
}

void Cam::setLookAt(const btVector3& v) {
  Camera::lookAt(Vec(v[0], v[1], v[2]));

  _lookAt = v;
}

btVector3 Cam::getLookAt() const {
  return _lookAt;
}


text:
// Copyright 2019 Victor Smirnov
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#pragma once

#include <memoria/core/types.hpp>
#include <boost/mp11.hpp>

#include <type_traits>

namespace memoria {

namespace _ {
    template <typename T> struct ToMp11H;

    template <typename... Type>
    struct ToMp11H<TL<Type...>>: HasType<boost::mp11::mp_list<Type...>> {};

    template <typename T> struct FromMp11H;

    template <typename... Type>
    struct FromMp11H<boost::mp11::mp_list<Type...>>: HasType<TL<Type...>> {};
}

template <typename T>
using ToMp11 = typename _::ToMp11H<T>::Type;

template <typename T>
using FromMp11 = typename _::FromMp11H<T>::Type;

}

max_stars_repo_name: victor-smirnov/memoria

max_issues_repo_name: victor-smirnov/memoria

max_forks_repo_name: victor-smirnov/memoria


text:
/*
@copyright Louis Dionne 2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
 */

#include <boost/hana/ext/boost/fusion/deque.hpp>

#include <boost/hana/assert.hpp>
#include <boost/hana/at.hpp>
#include <boost/hana/concept/sequence.hpp>
#include <boost/hana/core/make.hpp>
#include <boost/hana/equal.hpp>
#include <boost/hana/integral_constant.hpp>
#include <boost/hana/is_empty.hpp>
#include <boost/hana/length.hpp>
#include <boost/hana/not.hpp>
#include <boost/hana/tail.hpp>

#include <laws/base.hpp>

#include <boost/fusion/container/generation/make_deque.hpp>
#include <boost/fusion/container/deque.hpp>
namespace hana = boost::hana;
namespace fusion = boost::fusion;

using hana::test::ct_eq;

struct undefined { };

int main() {
    //////////////////////////////////////////////////////////////////////////
    // make<Deque>
    //////////////////////////////////////////////////////////////////////////
    {
        BOOST_HANA_CONSTANT_CHECK(hana::equal(
            fusion::make_deque(),
            hana::make<hana::ext::boost::fusion::deque_tag>()
        ));

        BOOST_HANA_CONSTANT_CHECK(hana::equal(
            fusion::make_deque(ct_eq<0>{}),
            hana::make<hana::ext::boost::fusion::deque_tag>(ct_eq<0>{})
        ));

        BOOST_HANA_CONSTANT_CHECK(hana::equal(
            fusion::make_deque(ct_eq<0>{}, ct_eq<1>{}),
            hana::make<hana::ext::boost::fusion::deque_tag>(ct_eq<0>{}, ct_eq<1>{})
        ));

        BOOST_HANA_CONSTANT_CHECK(hana::equal(
            fusion::make_deque(ct_eq<0>{}, ct_eq<1>{}, ct_eq<2>{}),
            hana::make<hana::ext::boost::fusion::deque_tag>(ct_eq<0>{}, ct_eq<1>{}, ct_eq<2>{})
        ));
    }

    //////////////////////////////////////////////////////////////////////////
    // tail
    //////////////////////////////////////////////////////////////////////////
    {
        BOOST_HANA_CONSTANT_CHECK(hana::equal(
            hana::tail(fusion::make_deque(ct_eq<0>{})),
            fusion::make_deque()
        ));

        BOOST_HANA_CONSTANT_CHECK(hana::equal(
            hana::tail(fusion::make_deque(ct_eq<0>{}, ct_eq<1>{})),
            fusion::make_deque(ct_eq<1>{})
        ));

        BOOST_HANA_CONSTANT_CHECK(hana::equal(
            hana::tail(fusion::make_deque(ct_eq<0>{}, ct_eq<1>{}, ct_eq<2>{})),
            fusion::make_deque(ct_eq<1>{}, ct_eq<2>{})
        ));

        BOOST_HANA_CONSTANT_CHECK(hana::equal(
            hana::tail(fusion::make_deque(ct_eq<0>{}, ct_eq<1>{}, ct_eq<2>{}, ct_eq<3>{})),
            fusion::make_deque(ct_eq<1>{}, ct_eq<2>{}, ct_eq<3>{})
        ));
    }

    //////////////////////////////////////////////////////////////////////////
    // at
    //////////////////////////////////////////////////////////////////////////
    {
        BOOST_HANA_CONSTANT_CHECK(hana::equal(
            hana::at_c<0>(fusion::make_deque(ct_eq<0>{})),
            ct_eq<0>{}
        ));

        BOOST_HANA_CONSTANT_CHECK(hana::equal(
            hana::at_c<0>(fusion::make_deque(ct_eq<0>{}, ct_eq<1>{})),
            ct_eq<0>{}
        ));
        BOOST_HANA_CONSTANT_CHECK(hana::equal(
            hana::at_c<1>(fusion::make_deque(ct_eq<0>{}, ct_eq<1>{})),
            ct_eq<1>{}
        ));

        BOOST_HANA_CONSTANT_CHECK(hana::equal(
            hana::at_c<0>(fusion::make_deque(ct_eq<0>{}, ct_eq<1>{}, ct_eq<2>{})),
            ct_eq<0>{}
        ));
        BOOST_HANA_CONSTANT_CHECK(hana::equal(
            hana::at_c<1>(fusion::make_deque(ct_eq<0>{}, ct_eq<1>{}, ct_eq<2>{})),
            ct_eq<1>{}
        ));
        BOOST_HANA_CONSTANT_CHECK(hana::equal(
            hana::at_c<2>(fusion::make_deque(ct_eq<0>{}, ct_eq<1>{}, ct_eq<2>{})),
            ct_eq<2>{}
        ));
    }

    //////////////////////////////////////////////////////////////////////////
    // is_empty
    //////////////////////////////////////////////////////////////////////////
    {
        BOOST_HANA_CONSTANT_CHECK(hana::is_empty(
            fusion::make_deque()
        ));

        BOOST_HANA_CONSTANT_CHECK(hana::not_(hana::is_empty(
            fusion::make_deque(undefined{})
        )));

        BOOST_HANA_CONSTANT_CHECK(hana::not_(hana::is_empty(
            fusion::make_deque(undefined{}, undefined{})
        )));
    }

    //////////////////////////////////////////////////////////////////////////
    // length
    //////////////////////////////////////////////////////////////////////////
    {
        BOOST_HANA_CONSTANT_CHECK(hana::equal(
            hana::length(fusion::make_deque()),
            hana::size_c<0>
        ));

        BOOST_HANA_CONSTANT_CHECK(hana::equal(
            hana::length(fusion::make_deque(undefined{})),
            hana::size_c<1>
        ));

        BOOST_HANA_CONSTANT_CHECK(hana::equal(
            hana::length(fusion::make_deque(undefined{}, undefined{})),
            hana::size_c<2>
        ));

        BOOST_HANA_CONSTANT_CHECK(hana::equal(
            hana::length(fusion::make_deque(undefined{}, undefined{}, undefined{})),
            hana::size_c<3>
        ));
    }

    //////////////////////////////////////////////////////////////////////////
    // Sequence
    //////////////////////////////////////////////////////////////////////////
    {
        static_assert(hana::Sequence<hana::ext::boost::fusion::deque_tag>::value, "");
    }
}

max_stars_repo_name: qicosmos/hana

max_issues_repo_name: qicosmos/hana

max_forks_repo_name: qicosmos/hana


text:
/**
 * \file pkey.cpp
 * \author Julien Kauffmann <julien.kauffmann@freelan.org>
 * \brief A PKEY sample file.
 */

#include <cryptoplus/cryptoplus.hpp>
#include <cryptoplus/pkey/pkey.hpp>
#include <cryptoplus/hash/message_digest_context.hpp>
#include <cryptoplus/error/error_strings.hpp>
#include <cryptoplus/file.hpp>

#include <boost/shared_ptr.hpp>

#include <iostream>
#include <string>
#include <cstdio>

#ifdef MSV
#include <openssl/applink.c>
#endif

namespace
{
	int pem_passphrase_callback(char* buf, int buf_len, int rwflag, void*)
	{
		std::cout << "Passphrase (max: " << buf_len << " characters): " << std::flush;
		std::string passphrase;
		std::getline(std::cin, passphrase);

		if (passphrase.empty())
		{
			std::cerr << "Passphrase cannot be empty." << std::endl;
			return 0;
		}

		if (passphrase.size() > static_cast<size_t>(buf_len))
		{
			std::cerr << "Passphrase cannot exceed " << buf_len << " characters." << std::endl;
			return 0;
		}

		if (rwflag != 0)
		{
			std::cout << "Confirm: " << std::flush;
			std::string passphrase_confirmation;
			std::getline(std::cin, passphrase_confirmation);

			if (passphrase_confirmation != passphrase)
			{
				std::cerr << "The two passphrases do not match !" << std::endl;
				return 0;
			}
		}

		std::copy(passphrase.begin(), passphrase.end(), buf);
		return passphrase.size();
	}
}

int main()
{
	cryptoplus::crypto_initializer crypto_initializer;
	cryptoplus::algorithms_initializer algorithms_initializer;
	cryptoplus::error::error_strings_initializer error_strings_initializer;

	std::cout << "PKEY sample" << std::endl;
	std::cout << "===========" << std::endl;
	std::cout << std::endl;

	const std::string private_key_filename = "private_key.pem";
	const std::string certificate_public_key_filename = "certificate_public_key.pem";

	cryptoplus::file private_key_file = cryptoplus::file::open(private_key_filename, "w");
	cryptoplus::file certificate_public_key_file = cryptoplus::file::open(certificate_public_key_filename, "w");

	if (!private_key_file)
	{
		std::cerr << "Unable to open \"" << private_key_filename << "\" for writing." << std::endl;

		return EXIT_FAILURE;
	}

	if (!certificate_public_key_file)
	{
		std::cerr << "Unable to open \"" << certificate_public_key_filename << "\" for writing." << std::endl;

		return EXIT_FAILURE;
	}

	try
	{
		std::cout << "Generating DSA key. This can take some time..." << std::endl;

		cryptoplus::pkey::dsa_key dsa_key = cryptoplus::pkey::dsa_key::generate_private_key(1024, NULL, 0, NULL, NULL);

		std::cout << "Done." << std::endl;

		cryptoplus::pkey::pkey pkey = cryptoplus::pkey::pkey::from_dsa_key(dsa_key);

		std::cout << "Checking that the type is correct: " << (pkey.is_dsa() ? "OK" : "FAILURE") << std::endl;

		pkey.write_private_key_pkcs8(private_key_file, cryptoplus::cipher::cipher_algorithm("AES256"), pem_passphrase_callback);

		std::cout << "Private key written succesfully to \"" << private_key_filename << "\"." << std::endl;

		pkey.write_certificate_public_key(certificate_public_key_file);

		std::cout << "Certificate public key written succesfully to \"" << certificate_public_key_filename << "\"." << std::endl;
	}
	catch (std::exception& ex)
	{
		std::cerr << "Exception: " << ex.what() << std::endl;

		return EXIT_FAILURE;
	}

	certificate_public_key_file = cryptoplus::file();
	private_key_file = cryptoplus::file::open(private_key_filename, "r");

	if (!private_key_file)
	{
		std::cerr << "Unable to open \"" << private_key_filename << "\" for reading." << std::endl;

		return EXIT_FAILURE;
	}

	try
	{
		std::cout << "Trying to read back the private key from \"" << private_key_filename << "\"..." << std::endl;

		cryptoplus::pkey::pkey pkey = cryptoplus::pkey::pkey::from_private_key(private_key_file, pem_passphrase_callback);

		std::cout << "Done." << std::endl;
	}
	catch (std::exception& ex)
	{
		std::cerr << "Exception: " << ex.what() << std::endl;

		return EXIT_FAILURE;
	}

	return EXIT_SUCCESS;
}

max_stars_repo_name: krattai/AEBL

max_issues_repo_name: krattai/AEBL

max_forks_repo_name: krattai/AEBL