text:
//#define INFO
#define TIMER
#define _USE_MATH_DEFINES
#define  NOMINMAX
#include <GL/glew.h>

#include <cuda_gl_interop.h>
#include <cuda_runtime_api.h>

#ifdef __gnu_linux__
#include <sys/types.h>
#include <sys/stat.h>
#elif _WIN32
#include <direct.h>
#else
#error "OS not supported!"
#endif
#include <iostream>
#include <string>
#include <vector>

#include <boost/lexical_cast.hpp>
#include <boost/random.hpp>
#include <boost/generator_iterator.hpp>
#include <boost/scoped_ptr.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/filesystem.hpp>

//#include <opencv2/core/utility.hpp>
#include <opencv2/features2d.hpp>
#include <opencv2/xfeatures2d/nonfree.hpp>
#include <opencv2/xfeatures2d.hpp>
#include <opencv2/core.hpp>
#include <opencv2/cudaimgproc.hpp>
#include <opencv2/cudafilters.hpp>
#include <opencv2/cudaarithm.hpp>
#include <opencv2/cudafeatures2d.hpp>

#include "Utility.hpp"

//camera calibration from a sequence of images
#include <opencv2/cudaarithm.hpp>
#include <OpenNI.h>
#include "Kinect.h"
#include "EigenUtil.hpp"
#include "GLUtil.hpp"
#include "pcl/internal.h"
#include <map>
#include "Camera.h"
#include "IntrinsicAnalysis.cuh"
#include "KeyFrame.h"
#include "VideoSourceKinect.hpp"
#include "TSDF.h"
#include "KinfuTracker.h"

//Qt
#include <QGLViewer/qglviewer.h>
#include "Data4Viewer.h"
#include "DataLive.h"

using namespace std;
using namespace cv;
using namespace Eigen;
using namespace qglviewer;
DataLive::DataLive()
:Data4Viewer(){
	_fVolumeSize = 3.f;
	_nMode = 3;//PLAYING_BACK
	_oniFileName = std::string("x.oni"); // the openni file
	_nStatus = 01;//1 restart; 2 //recording continue 3://pause 4://dump
	_bDisplayImage = false;
	_bLightOn = false;
	_bCapture = false;
	_bTrackingOnly = false;
	_bShowSurfaces = false;
	_bIsCameraPathOn = false;
	_bInitialized = false;
}

void DataLive::loadFromYml(){
	cv::FileStorage cFSRead ( "..//hdr_fusion_main//HDRFusionControl.yml", cv::FileStorage::READ );
	if (!cFSRead.isOpened()) {
		cout << "Load HDRFusionControl failed." <<endl;
		return;
	}
	cFSRead["uResolution"] >> _uResolution;
	cFSRead["uPyrHeight"] >> _uPyrHeight;
	cFSRead["uCubicGridResolution"] >> _vXYZCubicResolution;

	cFSRead["fVolumeSize"] >> _fVolumeSize;
	cFSRead["InitialCamPos"] >> _vInitial_Cam_Pos;
	_Cw = Vector3d(_vInitial_Cam_Pos[0],_vInitial_Cam_Pos[1],_vInitial_Cam_Pos[2]);
	cFSRead["CamParamPathFileName"] >> _cam_param_path;
	cFSRead["Stage"] >> _strStage;
	cFSRead["Result_folder"] >> _result_folder;
	//rendering
	cFSRead["bDisplayImage"] >> _bDisplayImage;
	cFSRead["bLightOn"] >> _bLightOn;
	cFSRead["nMode"] >> _nMode;//1 kinect; 2 recorder; 3 player
	cFSRead["nStatus"] >> _nStatus;

	cFSRead["bCameraPathOn"] >> _bIsCameraPathOn;
	cFSRead["oniFile"] >> _oniFileName;
	cFSRead["LoadVolume"] >> _bLoadVolume;

	cFSRead.release();
}

void DataLive::reset(){
	//for testing different oni files
	_nStatus = 9;
	//store viewing status
	if(_pGL.get()){
		_eimModelViewGL = _pGL->_ModelViewGL;
		_dZoom = _pGL->_dZoom;
		_dXAngle = _pGL->_dXAngle;
		_dYAngle = _pGL->_dYAngle;
	}
	_pGL.reset();
	_pGL.reset( new btl::gl_util::CGLUtil(_uResolution,_uPyrHeight) );

	_pGL->_bDisplayCamera = _bDisplayImage;
	_pGL->_bEnableLighting = _bLightOn;
	_pGL->_bRenderReference = _bRenderReference;
	//_pGL->clearColorDepth();
	_pGL->init();
	_pGL->constructVBOsPBOs();
	{
		//have to be after _pGL->init()
		//recover viewing status
		_pGL->_ModelViewGL = _eimModelViewGL ;
		_pGL->_dZoom = _dZoom;
		_pGL->_dXAngle = _dXAngle;
		_pGL->_dYAngle = _dYAngle;
	}
	//reset shared pointer, notice that the relationship makes a lot of sense

	_pKinect.reset( new btl::kinect::VideoSourceKinect(_uResolution,_uPyrHeight,_Cw,_cam_param_path) );
	switch(_nMode)
	{
		using namespace btl::kinect;
	case VideoSourceKinect::SIMPLE_CAPTURING: //the simple capturing mode of the rgbd camera
		_pKinect->initKinect();
		break;
	case VideoSourceKinect::RECORDING: //record the captured sequence from the camera
		_pKinect->setDumpFileName(_oniFileName);
		_pKinect->initRecorder(_oniFileName);
		break;
	case VideoSourceKinect::PLAYING_BACK: //replay from files
		_pKinect->initPlayer(_oniFileName);
		break;
	}

	//_pDepth            .reset(new btl::kinect::CKeyFrame(_pKinect->_pRGBCamera.get(),_uResolution,_uPyrHeight,_Cw));
	if (true)
		_pVirtualGlobal.reset(new btl::kinect::CKeyFrame(_pKinect->_pRGBCamera.get(), _uResolution, _uPyrHeight, _Cw));
	else
		_pVirtualGlobal.reset(new btl::kinect::CKeyFrame(_pKinect->_pDispCamera.get(), 6, _uPyrHeight, _Cw));
	_pVirtualCameraView.reset(new btl::kinect::CKeyFrame(_pKinect->_pRGBCamera.get(),_uResolution,_uPyrHeight,_Cw));
	_pCameraView2.reset(new btl::kinect::CKeyFrame(_pKinect->_pRGBCamera.get(), _uResolution, _uPyrHeight, _Cw));

	while (!_pKinect->getNextFrame(&_nStatus)){
		;
	}
	//initialize the cubic grids
	_pGlobalMap.reset(new btl::geometry::CTsdfBlock(make_short3(_vXYZCubicResolution[0], _vXYZCubicResolution[1], _vXYZCubicResolution[2]), _fVolumeSize,
						_pKinect->_pRGBCamera->getIntrinsics(0), SO3Group<double>(), Vector3d::Zero()));
	//initialize the tracker
	_pTracker.reset(new btl::geometry::CKinFuTracker(_pKinect->_pCurrFrame.get(), _pGlobalMap, _uResolution, _uPyrHeight));
	_pTracker->_serial_number = _pKinect->_serial_number;
	if (!_pIAVirtual){
		ostringstream directory;
		directory << "..//data//" << _pKinect->_serial_number << "//crf.yml";
		_pIAVirtual.reset(new btl::device::CIntrinsicsAnalysisMult(directory.str(), _pKinect->_pCurrFrame->_agPyrPts[0]->rows, _pKinect->_pCurrFrame->_agPyrPts[0]->cols, .25, 20));
	}

	bool bIsSuccessful = _pTracker->init(_pKinect->_pCurrFrame.get());
	if (!_strStage.compare("Tracking_n_Mapping") ){
		while (!bIsSuccessful){
			_pKinect->getNextFrame(&_nStatus);
			bIsSuccessful = _pTracker->init(_pKinect->_pCurrFrame.get());
		}
	}

	_bCapture = true;
	return;
}

void DataLive::updatePF(){
	//int64 A = getTickCount();
	using btl::kinect::VideoSourceKinect;

	if ( _bCapture ) {
		//load data from video source and model
		if( !_pKinect->getNextFrame(&_nStatus) ) return;
		//for display raw depth
		_pKinect->_pCurrFrame->_agPyrPts[2]->copyTo(_Pts);
		_pKinect->_pCurrFrame->_agPyrNls[2]->copyTo(_Nls);

		_pTracker->tracking(&*_pKinect->_pCurrFrame);
		//_bCapture = false;
	}//if( _bCapture )
	return;
}

max_stars_repo_name: ShudaLi/HDRFusion

max_issues_repo_name: etudemin/HDRFusion

max_forks_repo_name: etudemin/HDRFusion


text:
// This file is distributed under the MIT license.
// See the LICENSE file for details

#include <boost/asio/buffer.hpp>
#include <boost/asio/connect.hpp>
#include <boost/asio/placeholders.hpp>
#include <boost/asio/read.hpp>
#include <boost/asio/write.hpp>

#include "connection.h"
#include "connection_manager.h"

using namespace visionaray::async;

using boost::asio::ip::tcp;

//--------------------------------------------------------------------------------------------------
// connection
//

connection::connection(connection_manager& manager)
    : manager_(manager)
    , socket_(manager.io_service_)
{
#ifndef NDEBUG
    std::cout << "connection::connection [" << (void*)this << "]\n";
#endif
}

connection::~connection()
{
#ifndef NDEBUG
    std::cout << "connection::~connection [" << (void*)this << "]\n";
#endif

#if 0
    close(); // NO!!!
#else
    remove_handler();
#endif
}

void connection::start()
{
}

void connection::stop()
{
}

void connection::set_handler(signal_type::slot_function_type handler)
{
    // Remove existing handler.
    // Only a single handler is currently supported.
    remove_handler();

    slot_ = signal_.connect(handler);
}

void connection::remove_handler()
{
    signal_.disconnect(slot_);
}

void connection::close()
{
    manager_.close(shared_from_this());
}

void connection::write(message_pointer message)
{
    manager_.write(message, shared_from_this());
}

ext: cpp

max_stars_repo_name: ukoeln-vis/ctpperf

max_issues_repo_name: ukoeln-vis/ctpperf

max_forks_repo_name: ukoeln-vis/ctpperf


text:
// This file is part of SWGANH which is released under the MIT license.
// See file LICENSE or go to http://swganh.com/LICENSE

#ifndef WIN32
#include <Python.h>
#endif

#include "base_combat_command_binding.h"

#include "swganh/scripting/python_shared_ptr.h"
#include <boost/python.hpp>

#include "swganh/app/swganh_kernel.h"
#include "swganh_core/object/creature/creature.h"
#include "swganh_core/object/tangible/tangible.h"
#include "swganh/scripting/utilities.h"

#include "base_combat_command.h"
#include "swganh_core/combat/combat_data.h"

namespace bp = boost::python;
using swganh::command::BaseCombatCommand;
using swganh::command::CommandInterface;
using swganh::command::CommandProperties;
using swganh::combat::CombatData;
using swganh::scripting::ScopedGilLock;

struct BaseCombatCommandWrapper : BaseCombatCommand, bp::wrapper<BaseCombatCommand>
{
    BaseCombatCommandWrapper(
        PyObject* obj)
        : self_(bp::handle<>(bp::borrowed(obj)))
    {
        ScopedGilLock lock;
        bp::detail::initialize_wrapper(obj, this);
    }

    std::string GetCommandName() const
    {
        std::string command;

        ScopedGilLock lock;
        try
        {
            auto overrider = this->get_override("getCommandName");
            if (overrider)
            {
                bp::object name = overrider();
                command = bp::extract<std::string>(name);
            }
        }
        catch (bp::error_already_set&)
        {
            swganh::scripting::logPythonException();
        }

        return command;
    }

    void Run()
    {
        ScopedGilLock lock;
        try
        {
            if (auto py_override = this->get_override("run"))
            {
                py_override();
            }

            BaseCombatCommand::Run();
        }
        catch (bp::error_already_set&)
        {
            swganh::scripting::logPythonException();
        }
    }

private:
    bp::object self_;
};

void swganh::command::ExportBaseCombatCommand()
{
    bp::class_<BaseCombatCommand, BaseCombatCommandWrapper, bp::bases<BaseSwgCommand>, boost::noncopyable>
    ("BaseCombatCommand", bp::init<>())
    .def("run", &BaseCombatCommandWrapper::Run)
    .def("postRun", &BaseCombatCommandWrapper::PostRun)
    .def_readwrite("properties", &BaseCombatCommandWrapper::combat_data)
    ;
    bp::class_<CombatData, std::shared_ptr<CombatData>, bp::bases<CommandProperties>>("CombatData", bp::no_init)
            .def_readwrite("min_damage", &CombatData::min_damage)
            .def_readwrite("max_damage", &CombatData::max_damage)
            .def_readwrite("damage_multiplier", &CombatData::damage_multiplier)
            .def_readwrite("accuracy_bonus", &CombatData::accuracy_bonus)
            .def_readwrite("weapon_accuracy", &CombatData::weapon_accuracy)
            .def_readwrite("speed_multiplier", &CombatData::speed_multiplier)
            .def_readwrite("attack_speed", &CombatData::attack_speed)
            .def_readwrite("attack_delay_chance", &CombatData::attack_delay_chance)
            .def_readwrite("dot_duration", &CombatData::dot_duration)
            .def_readwrite("dot_type", &CombatData::dot_type)
            .def_readwrite("dot_pool", &CombatData::dot_pool)
            .def_readwrite("dot_strength", &CombatData::dot_strength)
            .def_readwrite("range", &CombatData::range)
            .def_readwrite("cone_angle", &CombatData::cone_angle)
            .def_readwrite("area_range", &CombatData::area_range)
            .def_readwrite("animation_crc", &CombatData::animation_crc)
            .def_readwrite("combat_spam", &CombatData::combat_spam)
            .def_readwrite("attack_delay_chance", &CombatData::attack_delay_chance)
            .def_readwrite("health_hit_chance", &CombatData::health_hit_chance)
            .def_readwrite("action_hit_chance", &CombatData::action_hit_chance)
            .def_readwrite("mind_hit_chance", &CombatData::mind_hit_chance)
            ;
}

ext: cc

max_stars_repo_name: obi-two/GameServer

max_issues_repo_name: obi-two/GameServer

max_forks_repo_name: obi-two/GameServer


text:
#pragma once

#include <type_traits>
#include <Eigen/Core>

namespace Eigen {
using Vector2ui = Matrix<unsigned int, 2, 1>;
using Vector3ui = Matrix<unsigned int, 3, 1>;
using Vector4ui = Matrix<unsigned int, 4, 1>;
} // namespace Eigen

namespace vgl {
/*constexpr glm::vec4 test;
template <typename>
struct is_glm_vec : std::false_type {};

template <glm::length_t L, typename T, glm::qualifier Q>
struct is_glm_vec<glm::vec<L, T, Q>> : std::true_type {};

template <typename T>
constexpr bool is_glm_vec_v = is_glm_vec<T>::value;*/
}

ext: hpp

max_stars_repo_name: alexsr/vgl

max_issues_repo_name: alexsr/vgl

max_forks_repo_name: alexsr/vgl


text:
#pragma once

#include <boost/asio/read.hpp>
#include <boost/asio/write.hpp>

namespace stream_client {

template <typename Protocol>
template <typename ConstBufferSequence, typename Time>
std::size_t datagram_socket<Protocol>::send(const ConstBufferSequence& buffers, boost::system::error_code& ec,
                                            const Time& timeout_or_deadline)
{
    std::size_t transfered_bytes = 0;
    bool setup_expiration = true;

    do {
        ec = boost::asio::error::would_block;
        async_send(
            buffers, timeout_or_deadline,
            [&](const boost::system::error_code& error, std::size_t n_bytes) {
                transfered_bytes += n_bytes;
                if (this->deadline_fired_) {
                    ec = boost::asio::error::timed_out;
                } else {
                    ec = error;
                }
            },
            setup_expiration);

        setup_expiration = false;
        while (ec == boost::asio::error::would_block) {
            this->get_io_service().run_one();
        }
    } while (ec == boost::asio::error::try_again);

    this->get_io_service().reset();
    return transfered_bytes;
}

template <typename Protocol>
template <typename ConstBufferSequence, typename Time>
std::size_t datagram_socket<Protocol>::send(const ConstBufferSequence& buffers, const Time& timeout_or_deadline)
{
    boost::system::error_code ec;
    std::size_t transfered_bytes = send(buffers, ec, timeout_or_deadline);
    if (ec) {
        throw boost::system::system_error{ec, "Socket send() failed"};
    }

    return transfered_bytes;
}

template <typename Protocol>
template <typename MutableBufferSequence, typename Time>
std::size_t datagram_socket<Protocol>::receive(const MutableBufferSequence& buffers, boost::system::error_code& ec,
                                               const Time& timeout_or_deadline)
{
    std::size_t transfered_bytes = 0;
    bool setup_expiration = true;

    do {
        ec = boost::asio::error::would_block;
        async_receive(
            buffers, timeout_or_deadline,
            [&](const boost::system::error_code& error, std::size_t n_bytes) {
                transfered_bytes += n_bytes;
                if (this->deadline_fired_) {
                    ec = boost::asio::error::timed_out;
                } else {
                    ec = error;
                }
            },
            setup_expiration);

        setup_expiration = false;
        while (ec == boost::asio::error::would_block) {
            this->get_io_service().run_one();
        }
    } while (ec == boost::asio::error::try_again);

    this->get_io_service().reset();
    return transfered_bytes;
}

template <typename Protocol>
template <typename MutableBufferSequence, typename Time>
std::size_t datagram_socket<Protocol>::receive(const MutableBufferSequence& buffers, const Time& timeout_or_deadline)
{
    boost::system::error_code ec;
    std::size_t transfered_bytes = receive(buffers, ec, timeout_or_deadline);
    if (ec) {
        throw boost::system::system_error{ec, "Socket receive() failed"};
    }

    return transfered_bytes;
}

template <typename Protocol>
template <typename ConstBufferSequence, typename WriteHandler, typename Time>
void datagram_socket<Protocol>::async_send(const ConstBufferSequence& buffers, const Time& timeout_or_deadline,
                                           WriteHandler&& handler, bool setup_expiration)
{
    typename datagram_socket<Protocol>::expiration expire;
    if (setup_expiration) {
        expire = this->scope_expire(timeout_or_deadline);
    }
    // clang-format off
    this->next_layer().async_send(
        buffers, [e = std::move(expire), h = std::forward<WriteHandler>(handler)](const boost::system::error_code& ec,
                                                                                std::size_t n_bytes)
        {
            h(ec, std::move(n_bytes));
        }
    );
    // clang-format on
}

template <typename Protocol>
template <typename MutableBufferSequence, typename ReadHandler, typename Time>
void datagram_socket<Protocol>::async_receive(const MutableBufferSequence& buffers, const Time& timeout_or_deadline,
                                              ReadHandler&& handler, bool setup_expiration)
{
    typename datagram_socket<Protocol>::expiration expire;
    if (setup_expiration) {
        expire = this->scope_expire(timeout_or_deadline);
    }
    // clang-format off
    this->next_layer().async_receive(
        buffers, [e = std::move(expire), h = std::forward<ReadHandler>(handler)](const boost::system::error_code& ec,
                                                                                std::size_t n_bytes)
        {
            h(ec, std::move(n_bytes));
        }
    );
    // clang-format on
}

} // namespace stream_client

ext: ipp

max_stars_repo_name: phobosxy/stream-client

max_issues_repo_name: phobosxy/stream-client

max_forks_repo_name: phobosxy/stream-client


text:
// Copyright (c) 2020 Egor Tensin <Egor.Tensin@gmail.com>
// This file is part of the "winapi-common" project.
// For details, see https://github.com/egor-tensin/winapi-common.
// Distributed under the MIT License.

#include <winapi/cmd_line.hpp>

// clang-format off
// The order matters for older Boost versions.
#include <boost/test/unit_test.hpp>
#include <boost/test/data/test_case.hpp>
#include <boost/test/data/monomorphic.hpp>
// clang-format on

#include <ostream>
#include <string>
#include <vector>

using namespace winapi;

namespace std {

ostream& operator<<(ostream& os, const vector<string>& xs) {
    os << "[\n";
    for (const auto& x : xs) {
        os << x << '\n';
    }
    os << "]";
    return os;
}

} // namespace std

BOOST_TEST_SPECIALIZED_COLLECTION_COMPARE(std::vector<std::string>);

namespace {

// MSDN examples
// https://docs.microsoft.com/en-us/cpp/c-language/parsing-c-command-line-arguments?view=vs-2019

const std::vector<std::string> msdn_string{
    R"(test.exe "abc" d e)",
    R"(test.exe a\\\b d"e f"g h)",
    R"(test.exe a\\\"b c d)",
    R"(test.exe a\\\\"b c" d e)",
};

const std::vector<std::vector<std::string>> msdn_argv{
    {"test.exe", "abc", "d", "e"},
    {"test.exe", R"(a\\\b)", "de fg", "h"},
    {"test.exe", R"(a\"b)", "c", "d"},
    {"test.exe", R"(a\\b c)", "d", "e"},
};

} // namespace

BOOST_AUTO_TEST_SUITE(cmd_line_tests)

BOOST_AUTO_TEST_CASE(query) {
    const auto cmd_line = CommandLine::query();
    BOOST_TEST(!cmd_line.get_argv0().empty(), "argv[0]: " << cmd_line.get_argv0());
}

BOOST_AUTO_TEST_CASE(to_string) {
    const std::vector<std::string> argv{
        "test.exe",
        "arg1 arg2",
        R"(path\to\file)",
        R"(path\to\dir\)",
        R"(weird\\argument)",
    };
    const CommandLine cmd_line{argv};
    const auto expected =
        R"("test.exe" "arg1 arg2" "path\to\file" "path\to\dir\\" "weird\\argument")";
    BOOST_TEST(cmd_line.to_string() == expected);
}

BOOST_DATA_TEST_CASE(msdn_parse,
                     boost::unit_test::data::make(msdn_string) ^ msdn_argv,
                     input,
                     expected) {
    const auto cmd_line = CommandLine::parse(input);
    const auto actual = cmd_line.get_argv();
    BOOST_TEST(actual == expected, "actual: " << actual);
}

BOOST_DATA_TEST_CASE(msdn_to_string, msdn_argv, argv) {
    const CommandLine cmd_line{argv};
    const auto actual = CommandLine::parse(cmd_line.to_string()).get_argv();
    BOOST_TEST(actual == argv, "actual: " << actual);
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: egor-tensin/winapi-common

max_issues_repo_name: egor-tensin/winapi-common

max_forks_repo_name: egor-tensin/winapi-common


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

#include <string>
#include <boost/format.hpp>
#include "EALog.h"
#include "OutputDevice.hpp"

#define TAG "OUTDEV"

namespace earlyapp
{
    DeviceParameter::DeviceParameter(void)
    {
    }

    DeviceParameter::DeviceParameter(const char* filePath)
    {
        setFileToPlay(filePath);
    }

    DeviceParameter::DeviceParameter(const std::string& filePath)
    {
        setFileToPlay(filePath);
    }

    void DeviceParameter::setFileToPlay(const char* filePath)
    {
        m_sFilePath = std::string(filePath);
    }

    void DeviceParameter::setFileToPlay(const std::string& filePath)
    {
        m_sFilePath = filePath;
    }

    // Returns file path.
    std::string& DeviceParameter::fileToPlay(void)
    {
        return m_sFilePath;
    }

    // Initialize.
    void OutputDevice::init(std::shared_ptr<Configuration> pConf)
    {
        int gpioNumber = pConf->gpioNumber();
        if(gpioNumber > 0)
        {
            LINF_(TAG, boost::str(
                      boost::format("Setting GPIO %d with default sleep time") % gpioNumber));
            m_pGPIOCtrl = new GPIOControl(gpioNumber);
        }
    }

    // Preapare for play.
    void OutputDevice::preparePlay(std::shared_ptr<DeviceParameter> playParam)
    {
        LINF_(TAG, "preparePlay()");
    }

    // Play
    void OutputDevice::play(void)
    {
        LINF_(TAG, "play()");
    }

    // Prepare for stop.
    void OutputDevice::prepareStop(void)
    {
        LINF_(TAG, "prepareStop()");
    }

    // Stop.
    void OutputDevice::stop(void)
    {
        LINF_(TAG, "stop()");
    }

    // Terminate.
    void OutputDevice::terminate(void)
    {
        LINF_(TAG, "terminate()");
    }

    // Destructor.
    OutputDevice::~OutputDevice(void)
    {
        if(m_pGPIOCtrl != nullptr)
        {
            delete m_pGPIOCtrl;
            m_pGPIOCtrl = nullptr;
        }
    }

    // GPIO output KPI measurements.
    void OutputDevice::outputGPIOPattern(void)
    {
        if(m_pGPIOCtrl == nullptr)
        {
            // No GPIO control.
            return;
        }

        // Control GPIO with pattern of High-Low-Sleep-High-Low.
        m_pGPIOCtrl->output(GPIOControl::HIGH);
        m_pGPIOCtrl->output(GPIOControl::LOW);
        m_pGPIOCtrl->sleep();
        m_pGPIOCtrl->output(GPIOControl::HIGH);
        m_pGPIOCtrl->output(GPIOControl::LOW);
    }
} // namespace

max_stars_repo_name: YinThong/earlyapp

max_issues_repo_name: YinThong/earlyapp

max_forks_repo_name: YinThong/earlyapp


text:
#include <mango/core/regex/Regex.h>
#include "mango/core/regex/RegexMatch.h"
#include <boost/regex.hpp>

MANGO_NS_BEGIN

struct RegexImpl
{
    RegexImpl(const std::string& pattern)
      : regex(pattern.c_str())
    {
    }

    bool find(const std::string& str, RegexMatch& match) const
    {

        boost::cmatch results;
        if (!boost::regex_search(str.c_str(), results, regex, boost::regex_constants::match_extra))
        {
            return false;
        }

        for (auto i = 1lu; i < results.size(); ++i)
        {
            match.emplace_back(results.str(i), results.position(i));
        }

        return true;
    }

    bool findAll(const std::string& str, RegexMatch& match) const
    {
        boost::sregex_token_iterator first(str.begin(), str.end(), regex, 1
            , boost::regex_constants::match_continuous);
        boost::sregex_token_iterator last;

        for (; first != last; ++first)
        {
            match.emplace_back(*first);
        }

        return !match.empty();
    }

    std::string str() const
    {
        return regex.str();
    }

private:
    boost::regex regex;
};

Regex::Regex(const std::string& pattern)
  : impl(new RegexImpl(pattern))
{}

Regex::~Regex()
{
    delete impl;
}

bool Regex::find(const std::string& str, RegexMatch& match) const
{
    return impl->find(str, match);
}

bool Regex::findAll(const std::string& str, RegexMatch& match) const
{
    return impl->findAll(str, match);
}

std::string Regex::str() const
{
    return impl->str();
}

MANGO_NS_END

max_stars_repo_name: vero-zhang/mango

max_issues_repo_name: vero-zhang/mango

max_forks_repo_name: vero-zhang/mango


text:
// __BEGIN_LICENSE__
// Copyright (C) 2006-2011 United States Government as represented by
// the Administrator of the National Aeronautics and Space Administration.
// All Rights Reserved.
// __END_LICENSE__

// What's this file supposed to do ?
//
// (Pho)tometry (It)eration (DEM) Update
//
// Here be dragons! Actually this is the spot for shape from shading.
// We're not going to work on this until later.

#include <vw/Image.h>
#include <photk/Macros.h>
using namespace vw;

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

using namespace std;

struct Options {

  // For spawning multiple jobs
  int job_id, num_jobs;
};

void handle_arguments( int argc, char *argv[], Options& opt ) {
  po::options_description general_options("");
  general_options.add_options()
    ("job_id,j", po::value(&opt.job_id)->default_value(0), "")
    ("num_jobs,n", po::value(&opt.num_jobs)->default_value(1), "")
    ("help,h", "Display this help message");

  po::variables_map vm;
  try {
    po::store( po::command_line_parser( argc, argv ).options(general_options).run(), vm );
    po::notify( vm );
  } catch (po::error const& e) {
    vw_throw( ArgumentErr() << "Error parsing input:\n\t"
              << e.what() << general_options );
  }

  std::ostringstream usage;
  usage << "Usage: " << argv[0] << " [programmer hasn't filled this out]\n";

  if ( vm.count("help") )
    vw_throw( ArgumentErr() << usage.str() << general_options );
}

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

  Options opt;
  try {
    handle_arguments( argc, argv, opt );
  } PHOTK_STANDARD_CATCHES;

  return 0;
}

max_stars_repo_name: NeoGeographyToolkit/PhotometryTK

max_issues_repo_name: NeoGeographyToolkit/PhotometryTK

max_forks_repo_name: NeoGeographyToolkit/PhotometryTK


text:
#define BOOST_TEST_MODULE ea_solver_unit_tests

#include <boost/test/included/unit_test.hpp>
#include <armadillo>
#include "../src/numerical/evolutionary_algorithm/ea_solver.h"
#include "test_utils.cpp"
#include "../src/logging/easylogging++.h"

INITIALIZE_EASYLOGGINGPP

using namespace arma;

auto solver = EASolver(SIGNALS, 500, 1000, 0.0001, 100, 50);

BOOST_AUTO_TEST_CASE(test_common_cases)
{
    auto tester = SolverTester<EASolver>(solver);
    tester.test_common(0.1);
}

max_stars_repo_name: omyllymaki/math

max_issues_repo_name: omyllymaki/math

max_forks_repo_name: omyllymaki/math


text:
#include <boost/gil/image_processing/scaling.hpp>
#include <boost/gil/image.hpp>

#include <boost/core/lightweight_test.hpp>

#include <iostream>

namespace gil = boost::gil;

bool are_equal(gil::rgb8_view_t expected, gil::rgb8_view_t actual) {
    if (expected.dimensions() != actual.dimensions())
        return false;

    for (long int y = 0; y < expected.height(); ++y)
    {
        for (long int x = 0; x < expected.width(); ++x)
        {
            if (expected(x, y) != actual(x, y))
            {
                return false;
            }
        }
    }

    return true;
}

void test_lanczos_black_image()
{

    const gil::point_t input_dimensions(20, 20);
    const gil::point_t output_dimensions(input_dimensions.x / 2, input_dimensions.y / 2);
    gil::rgb8_image_t image(input_dimensions, gil::rgb8_pixel_t(0, 0, 0), 0);
    // fill with values other than 0
    gil::rgb8_image_t output_image(
        output_dimensions,
        gil::rgb8_pixel_t(100, 100, 100),
        0
    );
    gil::rgb8_image_t expected(
        output_dimensions,
        gil::rgb8_pixel_t(0, 0, 0),
        0
    );

    auto view = gil::view(image);
    auto output_view = gil::view(output_image);
    auto expected_view = gil::view(expected);
    gil::scale_lanczos(view, output_view, 5);
    BOOST_TEST(are_equal(expected_view,output_view));
}

void test_lanczos_response_on_zero()
{
    //random value for a
    BOOST_TEST(gil::lanczos(0, 2) == 1);
}

int main()
{
    test_lanczos_black_image();
    test_lanczos_response_on_zero();
    return boost::report_errors();
}


text:
/* *****************************************************
   THIS IS AN AUTOMATICALLY GENERATED FILE. DO NOT EDIT.
   *****************************************************

   Generated by:
     gltbx.generate_functions_bpl
 */

#include <gltbx/special_wrapper_support.h>
#include <gltbx/pointer_args_bpl.h>
#include <gltbx/error.h>

#if defined(__GNUC__) && __GNUC__ == 2 \
     && __GNUC_MINOR__ == 96 && __GNUC_PATCHLEVEL__ == 0
#define GLTBX_NO_OPAQUE_POINTERS
#else
#include <boost/python/return_value_policy.hpp>
#include <boost/python/return_opaque_pointer.hpp>
BOOST_PYTHON_OPAQUE_SPECIALIZED_TYPE_ID(GLUnurbs)
BOOST_PYTHON_OPAQUE_SPECIALIZED_TYPE_ID(GLUquadric)
BOOST_PYTHON_OPAQUE_SPECIALIZED_TYPE_ID(GLUtesselator)
#endif

namespace gltbx { namespace glu { namespace {

#if !defined(GLTBX_NO_OPAQUE_POINTERS)
  void
  glu_QuadricOrientation(
    boost::python::object const& py_quad,
    boost::python::object const& py_orientation)
  {
    boost::python::extract<GLUquadric*> quad_proxy(py_quad);
    GLUquadric* quad = quad_proxy();
    boost::python::extract<GLenum> orientation_proxy(py_orientation);
    GLenum orientation = orientation_proxy();
    gluQuadricOrientation(quad, orientation);
  }
#endif

#if !defined(GLTBX_NO_OPAQUE_POINTERS)
  void
  glu_QuadricTexture(
    boost::python::object const& py_quad,
    boost::python::object const& py_texture)
  {
    boost::python::extract<GLUquadric*> quad_proxy(py_quad);
    GLUquadric* quad = quad_proxy();
    boost::python::extract<GLboolean> texture_proxy(py_texture);
    GLboolean texture = texture_proxy();
    gluQuadricTexture(quad, texture);
  }
#endif

  GLint
  glu_ScaleImage(
    boost::python::object const& py_format,
    boost::python::object const& py_wIn,
    boost::python::object const& py_hIn,
    boost::python::object const& py_typeIn,
    boost::python::object const& py_dataIn,
    boost::python::object const& py_wOut,
    boost::python::object const& py_hOut,
    boost::python::object const& py_typeOut,
    boost::python::object const& py_dataOut)
  {
    boost::python::extract<GLenum> format_proxy(py_format);
    GLenum format = format_proxy();
    boost::python::extract<GLsizei> wIn_proxy(py_wIn);
    GLsizei wIn = wIn_proxy();
    boost::python::extract<GLsizei> hIn_proxy(py_hIn);
    GLsizei hIn = hIn_proxy();
    boost::python::extract<GLenum> typeIn_proxy(py_typeIn);
    GLenum typeIn = typeIn_proxy();
    throw std::runtime_error(
      "Conversion not implemented:"
      " gluScaleImage(): const void* dataIn");
  //  const void* dataIn = 0;
  //  boost::python::extract<GLsizei> wOut_proxy(py_wOut);
  //  GLsizei wOut = wOut_proxy();
  //  boost::python::extract<GLsizei> hOut_proxy(py_hOut);
  //  GLsizei hOut = hOut_proxy();
  //  boost::python::extract<GLenum> typeOut_proxy(py_typeOut);
  //  GLenum typeOut = typeOut_proxy();
  //  throw std::runtime_error(
  //    "Conversion not implemented:"
  //    " gluScaleImage(): GLvoid* dataOut");
  //  GLvoid* dataOut = 0;
  //  return gluScaleImage(format, wIn, hIn, typeIn, dataIn, wOut, hOut,
  //    typeOut, dataOut);
  }

#if !defined(GLTBX_NO_OPAQUE_POINTERS)
  void
  glu_Sphere(
    boost::python::object const& py_quad,
    boost::python::object const& py_radius,
    boost::python::object const& py_slices,
    boost::python::object const& py_stacks)
  {
    boost::python::extract<GLUquadric*> quad_proxy(py_quad);
    GLUquadric* quad = quad_proxy();
    boost::python::extract<GLdouble> radius_proxy(py_radius);
    GLdouble radius = radius_proxy();
    boost::python::extract<GLint> slices_proxy(py_slices);
    GLint slices = slices_proxy();
    boost::python::extract<GLint> stacks_proxy(py_stacks);
    GLint stacks = stacks_proxy();
    gluSphere(quad, radius, slices, stacks);
  }
#endif

#if !defined(GLTBX_NO_OPAQUE_POINTERS)
  void
  glu_TessBeginContour(
    boost::python::object const& py_tess)
  {
    boost::python::extract<GLUtesselator*> tess_proxy(py_tess);
    GLUtesselator* tess = tess_proxy();
    gluTessBeginContour(tess);
  }
#endif

#if !defined(GLTBX_NO_OPAQUE_POINTERS)
  void
  glu_TessEndContour(
    boost::python::object const& py_tess)
  {
    boost::python::extract<GLUtesselator*> tess_proxy(py_tess);
    GLUtesselator* tess = tess_proxy();
    gluTessEndContour(tess);
  }
#endif

#if !defined(GLTBX_NO_OPAQUE_POINTERS)
  void
  glu_TessBeginPolygon(
    boost::python::object const& py_tess,
    boost::python::object const& py_data)
  {
    boost::python::extract<GLUtesselator*> tess_proxy(py_tess);
    GLUtesselator* tess = tess_proxy();
    throw std::runtime_error(
      "Conversion not implemented:"
      " gluTessBeginPolygon(): GLvoid* data");
  //  GLvoid* data = 0;
  //  gluTessBeginPolygon(tess, data);
  }
#endif

#if !defined(GLTBX_NO_OPAQUE_POINTERS)
  void
  glu_TessCallback(
    boost::python::object const& py_tess,
    boost::python::object const& py_which,
    boost::python::object const& py_fn)
  {
    boost::python::extract<GLUtesselator*> tess_proxy(py_tess);
    GLUtesselator* tess = tess_proxy();
    boost::python::extract<GLenum> which_proxy(py_which);
    GLenum which = which_proxy();
    throw std::runtime_error(
      "Conversion not implemented:"
      " gluTessCallback(): glu_function_pointer fn");
  //  glu_function_pointer fn = 0;
  //  gluTessCallback(tess, which, fn);
  }
#endif

#if !defined(GLTBX_NO_OPAQUE_POINTERS)
  void
  glu_TessEndPolygon(
    boost::python::object const& py_tess)
  {
    boost::python::extract<GLUtesselator*> tess_proxy(py_tess);
    GLUtesselator* tess = tess_proxy();
    gluTessEndPolygon(tess);
  }
#endif

#if !defined(GLTBX_NO_OPAQUE_POINTERS)
  void
  glu_TessNormal(
    boost::python::object const& py_tess,
    boost::python::object const& py_valueX,
    boost::python::object const& py_valueY,
    boost::python::object const& py_valueZ)
  {
    boost::python::extract<GLUtesselator*> tess_proxy(py_tess);
    GLUtesselator* tess = tess_proxy();
    boost::python::extract<GLdouble> valueX_proxy(py_valueX);
    GLdouble valueX = valueX_proxy();
    boost::python::extract<GLdouble> valueY_proxy(py_valueY);
    GLdouble valueY = valueY_proxy();
    boost::python::extract<GLdouble> valueZ_proxy(py_valueZ);
    GLdouble valueZ = valueZ_proxy();
    gluTessNormal(tess, valueX, valueY, valueZ);
  }
#endif

#if !defined(GLTBX_NO_OPAQUE_POINTERS)
  void
  glu_TessProperty(
    boost::python::object const& py_tess,
    boost::python::object const& py_which,
    boost::python::object const& py_data)
  {
    boost::python::extract<GLUtesselator*> tess_proxy(py_tess);
    GLUtesselator* tess = tess_proxy();
    boost::python::extract<GLenum> which_proxy(py_which);
    GLenum which = which_proxy();
    boost::python::extract<GLdouble> data_proxy(py_data);
    GLdouble data = data_proxy();
    gluTessProperty(tess, which, data);
  }
#endif

#if !defined(GLTBX_NO_OPAQUE_POINTERS)
  void
  glu_TessVertex(
    boost::python::object const& py_tess,
    boost::python::object const& py_location,
    boost::python::object const& py_data)
  {
    boost::python::extract<GLUtesselator*> tess_proxy(py_tess);
    GLUtesselator* tess = tess_proxy();
    boost_python::converter<GLdouble> location_proxy(
      "location", py_location, 0, false);
    GLdouble* location = location_proxy.get();
    throw std::runtime_error(
      "Conversion not implemented:"
      " gluTessVertex(): GLvoid* data");
  //  GLvoid* data = 0;
  //  gluTessVertex(tess, location, data);
  //  location_proxy.write_back();
  }
#endif

  GLint
  glu_UnProject(
    boost::python::object const& py_winX,
    boost::python::object const& py_winY,
    boost::python::object const& py_winZ,
    boost::python::object const& py_model,
    boost::python::object const& py_proj,
    boost::python::object const& py_view,
    boost::python::object const& py_objX,
    boost::python::object const& py_objY,
    boost::python::object const& py_objZ)
  {
    boost::python::extract<GLdouble> winX_proxy(py_winX);
    GLdouble winX = winX_proxy();
    boost::python::extract<GLdouble> winY_proxy(py_winY);
    GLdouble winY = winY_proxy();
    boost::python::extract<GLdouble> winZ_proxy(py_winZ);
    GLdouble winZ = winZ_proxy();
    boost_python::converter<GLdouble> model_proxy(
      "model", py_model, 16, true);
    const GLdouble* model = model_proxy.get();
    boost_python::converter<GLdouble> proj_proxy(
      "proj", py_proj, 16, true);
    const GLdouble* proj = proj_proxy.get();
    boost_python::converter<GLint> view_proxy(
      "view", py_view, 4, true);
    const GLint* view = view_proxy.get();
    boost_python::converter<GLdouble> objX_proxy(
      "objX", py_objX, 1, false);
    GLdouble* objX = objX_proxy.get();
    boost_python::converter<GLdouble> objY_proxy(
      "objY", py_objY, 1, false);
    GLdouble* objY = objY_proxy.get();
    boost_python::converter<GLdouble> objZ_proxy(
      "objZ", py_objZ, 1, false);
    GLdouble* objZ = objZ_proxy.get();
    GLint result = gluUnProject(winX, winY, winZ, model, proj, view, objX,
      objY, objZ);
    objX_proxy.write_back();
    objY_proxy.write_back();
    objZ_proxy.write_back();
    return result;
  }

} // namespace <anonymous>

namespace boost_python {

  void
  wrap_functions_03()
  {
    using namespace boost::python;
#if !defined(GLTBX_NO_OPAQUE_POINTERS)
    def("gluQuadricOrientation", glu_QuadricOrientation, (
      arg("quad"), arg("orientation")));
#endif
#if !defined(GLTBX_NO_OPAQUE_POINTERS)
    def("gluQuadricTexture", glu_QuadricTexture, (
      arg("quad"), arg("texture")));
#endif
    def("gluScaleImage", glu_ScaleImage, (
      arg("format"), arg("wIn"), arg("hIn"), arg("typeIn"), arg("dataIn"),
      arg("wOut"), arg("hOut"), arg("typeOut"), arg("dataOut")));
#if !defined(GLTBX_NO_OPAQUE_POINTERS)
    def("gluSphere", glu_Sphere, (
      arg("quad"), arg("radius"), arg("slices"), arg("stacks")));
#endif
#if !defined(GLTBX_NO_OPAQUE_POINTERS)
    def("gluTessBeginContour", glu_TessBeginContour, (
      arg("tess")));
#endif
#if !defined(GLTBX_NO_OPAQUE_POINTERS)
    def("gluTessEndContour", glu_TessEndContour, (
      arg("tess")));
#endif
#if !defined(GLTBX_NO_OPAQUE_POINTERS)
    def("gluTessBeginPolygon", glu_TessBeginPolygon, (
      arg("tess"), arg("data")));
#endif
#if !defined(GLTBX_NO_OPAQUE_POINTERS)
    def("gluTessCallback", glu_TessCallback, (
      arg("tess"), arg("which"), arg("fn")));
#endif
#if !defined(GLTBX_NO_OPAQUE_POINTERS)
    def("gluTessEndPolygon", glu_TessEndPolygon, (
      arg("tess")));
#endif
#if !defined(GLTBX_NO_OPAQUE_POINTERS)
    def("gluTessNormal", glu_TessNormal, (
      arg("tess"), arg("valueX"), arg("valueY"), arg("valueZ")));
#endif
#if !defined(GLTBX_NO_OPAQUE_POINTERS)
    def("gluTessProperty", glu_TessProperty, (
      arg("tess"), arg("which"), arg("data")));
#endif
#if !defined(GLTBX_NO_OPAQUE_POINTERS)
    def("gluTessVertex", glu_TessVertex, (
      arg("tess"), arg("location"), arg("data")));
#endif
    def("gluUnProject", glu_UnProject, (
      arg("winX"), arg("winY"), arg("winZ"), arg("model"), arg("proj"),
      arg("view"), arg("objX"), arg("objY"), arg("objZ")));
  }

}}} // namespace gltbx::glu::boost_python


text:
/*******************************************************************************
 * Copyright (C) 2017, 2018, MINRES Technologies GmbH
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 *
 * 2. 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.
 *
 * 3. Neither the name of the 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 HOLDER 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.
 *
 * Contributors:
 *       eyck@minres.com - initial API and implementation
 ******************************************************************************/

#include "cmdhandler.h"
#include <iss/log_categories.h>
#include <util/ities.h>

#include <boost/tokenizer.hpp>
#include <cstdarg>
#include <numeric>
#include <sstream>
#include <stdexcept>

#ifdef _MSC_VER
// not #if defined(_WIN32) || defined(_WIN64) because we have strncasecmp in mingw
#define strncasecmp _strnicmp
#define strcasecmp _stricmp
#endif

using namespace iss::debugger;
using namespace boost;

void rp_console_output(const char *buf) {
    std::string msg(buf);
    if (buf[msg.size() - 1] == '\n') {
        CLOG(INFO, connection) << msg.substr(0, msg.size() - 1);
    } else {
        CLOG(INFO, connection) << buf;
    }
}

/* Funcions to stuff output value */

const unsigned CORE_ID = 0;

void cmd_handler::attach() {}

std::string cmd_handler::search_memory(std::string const& in_buf) {
    CLOG(TRACE, connection) << "executing " << __FUNCTION__;
    uint64_t addr;
    uint32_t pattern;
    uint32_t mask;
    const char *in;

    /* Format: taddr:PP,MM
     Search backwards starting at address addr for a match with the
     supplied pattern PP and mask MM. PP and MM are 4 bytes. addr
     must be at least 3 digits. */

    in = &in_buf[1];
    if (!encdec.dec_uint64(&in, &addr, ':')) {
        return std::string("E00");
    }
    if (!encdec.dec_uint32(&in, &pattern, ',')) {
        return std::string("E00");
    }
    if (!encdec.dec_uint32(&in, &mask, '\0')) {
        return std::string("E00");
    }
    return std::string("E01");
}

std::string cmd_handler::threads(std::string const& in_buf) {
    CLOG(TRACE, connection) << "executing " << __FUNCTION__;

    rp_thread_ref ref;
    const char *in;

    if (in_buf.size() == 1 || in_buf[2] == '-') {
        /* Either short or an obsolete form */
        return "";
    }

    /* Set thread */
    switch (in_buf[1]) {
    case 'c':
        in = in_buf.c_str() + 2;
        if (!encdec.dec_uint64(&in, &ref.val, '\0')) return "E00";
        return to_string(t->set_ctrl_thread(ref));
    case 'g':
        in = in_buf.c_str() + 2;
        if (!encdec.dec_uint64(&in, &ref.val, '\0')) return "E00";
        return to_string(t->set_gen_thread(ref));
    default:
        CLOG(ERR, connection) << __FUNCTION__ << ": Bad H command";
        return "";
    }
}

std::string cmd_handler::read_registers(std::string const& in_buf) {
    CLOG(TRACE, connection) << "executing " << __FUNCTION__;
    int ret;
    size_t len;
    std::vector<uint8_t> data_buf(MAX_DATABYTES);
    std::vector<uint8_t> avail_buf(MAX_DATABYTES);
    /* Get all registers. Format: 'g'. Note we do not do any data caching - all
     * caching is done by the debugger */
    ret = t->read_registers(data_buf, avail_buf);
    if (!ret) {
        return encdec.enc_regs(data_buf, avail_buf);
    } else
        return "E00";
}

std::string cmd_handler::write_registers(std::string const& in_buf) {
    CLOG(TRACE, connection) << "executing " << __FUNCTION__;
    size_t len;

    /* Write all registers. Format: 'GXXXXXXXXXX' */
    std::vector<uint8_t> data = encdec.dec_data(&in_buf[1]);
    if (data.empty())
        return "E00";
    else
        return to_string(t->write_registers(data));
}

std::string cmd_handler::read_single_register(std::string const& in_buf) {
    CLOG(TRACE, connection) << "executing " << __FUNCTION__;
    unsigned int reg_no;
    //    uint64_t avail=std::numeric_limits<uint64_t>::max();

    /* Get a single register. Format 'pNN' */
    int ret = encdec.dec_reg(&in_buf[1], &reg_no);
    if (!ret) return "E00";
    std::vector<uint8_t> data(8), avail(8);
    ret = t->read_single_register(reg_no, data, avail);
    switch (ret) {
    case iss::Ok:
        assert(data.size() <= MAX_DATABYTES);
        return encdec.enc_regs(data, avail);
    case iss::Err:
        return "E00";
    // handle targets non supporting single register read
    case iss::NotSupported:
        break;
    default:
        /* This should not happen */
        assert(false);
        break;
    }
    return "";
}

std::string cmd_handler::write_single_register(std::string const& in_buf) {
    CLOG(TRACE, connection) << "executing " << __FUNCTION__;
    unsigned int reg_no;
    /* Write a single register. Format: 'PNN=XXXXX' */
    std::vector<uint8_t> data = encdec.dec_reg_assignment(&in_buf[1], &reg_no);
    if (data.empty()) return "E00";
    assert(data.size() < MAX_DATABYTES);
    return to_string(t->write_single_register(reg_no, data));
}

std::string cmd_handler::read_memory(std::string const& in_buf) {
    CLOG(TRACE, connection) << "executing " << __FUNCTION__;
    int ret;
    size_t len;
    uint64_t addr;

    /* Read memory format: 'mAA..A,LL..LL' */
    if (!(ret = encdec.dec_mem(&in_buf[1], &addr, &len))) return "E00";

    /* Limit it so buggy gdbs will not complain */
    if (len > ((DBG_PRINTBUF_SIZE - 32) / 2)) len = (DBG_PRINTBUF_SIZE - 32) / 2;

    std::vector<uint8_t> data(len);
    ret = t->read_mem(addr, data);

    switch (ret) {
    case iss::Ok:
        assert(len <= MAX_DATABYTES);
        return encdec.enc_data(data);
    case iss::Err:
        return "E00";
    default:
        /* This should not happen */
        assert(false);
        break;
    }
    return "";
}

std::string cmd_handler::write_memory(std::string const& in_buf) {
    CLOG(TRACE, connection) << "executing " << __FUNCTION__;
    size_t cp;
    /* Write memory format: 'mAA..A,LL..LL:XX..XX' */
    if ((cp = in_buf.find_first_of(':', 1)) < in_buf.npos) return "E00";

    size_t len;
    uint64_t addr;
    int ret = encdec.dec_mem(&in_buf[1], &addr, &len);
    if (!ret || len > MAX_DATABYTES) return "E00";

    std::vector<uint8_t> data = encdec.dec_data(&in_buf[cp + 1]);
    if (!ret || len != data.size()) return "E00";
    return to_string(t->write_mem(addr, data));
}

std::string cmd_handler::running(std::string const& in_buf, bool blocking, bool vCont) {
    CLOG(TRACE, connection) << "executing " << __FUNCTION__ << "(" << in_buf << ")";
    auto step = false;
    uint32_t sig{TARGET_SIGNAL0};
    iss::status ret{iss::Err};
    /* 's' step from address
     * 'S' step from address with signal
     * 'c' continue from address
     * 'C' continue from address with signal
     */
    if (vCont) { // s:0;c
        auto cmds = util::split(in_buf, ';');
        for (auto &cmd : cmds) {
            rp_thread_ref thread{};
            if (cmd[0] == 't') {
                t->stop();
            } else {
                std::string c{cmd};
                if (cmd.find(':') != cmd.npos) { // the command is related to a specific thread
                    auto fields = util::split(cmd, ':');
                    // TODO: change to thread id instead of numbers
                    if (!encdec.dec_uint64(fields[1].c_str(), &thread.val)) return "E00";
                    c = fields[0];
                }
                if (c.size() > 1)
                    if (!encdec.dec_uint32(c.data() + 1, &sig)) return "E00";
                step |= (c[0] & 0x5f) == 'S'; // convert to uppercase and check
                ret = t->resume_from_current((c[0] & 0x5f) == 'S', sig, thread,
                                             blocking ? std::function<void(unsigned)>{} : stop_callback);
                if (ret == iss::Err) return to_string(ret);
            }
        }
    } else {                              // c[addr] or Csig[;addr]
        step = (in_buf[0] & 0x5f) == 'S'; // convert to uppercase and check
        const char *addr_ptr = nullptr;
        if (in_buf[0] < 'a') { // Uppercase, resume with signal, format Csig[;AA..AA], Ssig[;AA..AA], or Wsig[;AA..AA]
            const char *in = in_buf.data() + 1;
            if (strchr(in, ';')) {
                if (!encdec.dec_uint32(&in, &sig, ';')) return "E00";
                addr_ptr = in;
            } else {
                if (!encdec.dec_uint32(&in, &sig, '\0')) return "E00";
            }
        } else if (in_buf[1] != '\0') {
            addr_ptr = &in_buf[1];
        }
        if (addr_ptr) {
            uint64_t addr;
            if (!encdec.dec_uint64(&addr_ptr, &addr, '\0')) return "E00";
            ret = t->resume_from_addr(step, sig, addr, rp_thread_ref{},
                                      blocking ? std::function<void(unsigned)>{} : stop_callback);
        } else {
            ret = t->resume_from_current(step, sig, rp_thread_ref{},
                                         blocking ? std::function<void(unsigned)>{} : stop_callback);
        }
        if (ret != iss::Ok) return to_string(ret);
    }

    /* Now we have to wait for the target */
    /* Try a non-blocking wait first */
    bool running = false;
    ret = t->wait_non_blocking(running);
    if ((ret == iss::NotSupported || blocking) && !step) {
        // There is no partial wait facility for this target or there is no stop callback provided,
        // so use as blocking wait */
        ret = t->wait_blocking();
        running = false;
    }
    if (ret == iss::Err) return to_string(ret);
    if (!running) {
        /* We are done. The program has already stopped */
        return "S05"; // answer with SIGTRAP
    } else
        return "OK";
}

int cmd_handler::kill(std::string const& in_buf, std::string &out_buf) {
    CLOG(TRACE, connection) << "executing " << __FUNCTION__;
    int ret;

    s.shutdown();

    if (!extended_protocol) {
        //        dbg_sock_close();
        //
        //        if (!can_restart) {
        //            /* If the current target cannot restart, we have little choice
        //            but to exit right now. */
        //            CLOG(INFO, connection)<<__FUNCTION__<<": session killed.
        //            Exiting";
        //            dbg_sock_cleanup();
        //            exit(0);
        //        }

        CLOG(INFO, connection) << __FUNCTION__ << ": session killed. Will wait for a new connection";
        return 0;
    }

    CLOG(INFO, connection) << __FUNCTION__ << ": server restarting";

    /* Let us do our best while starting system */
    if (!can_restart) {
        /* Even if restart is not supported it is still worth calling connect */
        return -1;
    }

    ret = s.reset(CORE_ID);

    assert(ret != iss::NotSupported);

    if (ret != iss::Ok) {
        /* There is no point in continuing */
        CLOG(ERR, connection) << __FUNCTION__ << ": unable to restart target";
        out_buf = "E00";
        //        rp_putpkt(out_buf);
        //        dbg_sock_close();
        //
        //        if (!can_restart) {
        //            dbg_sock_cleanup();
        //            exit(1);
        //        }

        CLOG(INFO, connection) << __FUNCTION__ << ": will wait for a new connection";
        return 0;
    }
    return 1;
}

std::string cmd_handler::thread_alive(std::string const& in_buf) {
    CLOG(TRACE, connection) << "executing " << __FUNCTION__;
    int ret;
    bool alive;
    rp_thread_ref ref;
    const char *in;

    /* Is thread alive? */
    /* This is a deprecated feature of the remote debug protocol */
    in = &in_buf[1];
    if (!(ret = encdec.dec_uint64(&in, &ref.val, '\0'))) return "E00";

    ret = t->is_thread_alive(ref, alive);
    if (ret != iss::Ok) {
        return to_string(ret);
    } else {
        if (alive)
            return "OK";
        else
            return "E00";
    }
    return "E01";
}

int cmd_handler::restart_target(std::string const& in_buf, std::string &out_buf) {
    CLOG(TRACE, connection) << "executing " << __FUNCTION__;
    int ret;

    /* Restarting the target is only supported in the extended protocol. */
    if (!extended_protocol) return 0;

    assert(can_restart);

    /* Let us do our best to restart the system */
    if ((ret = s.reset(CORE_ID)) != iss::Ok) {
        /* There is no point to continuing */
        CLOG(ERR, connection) << __FUNCTION__ << ": unable to restart target";
        out_buf = "E00";
        CLOG(INFO, connection) << __FUNCTION__ << ": will wait for a new connection";
        return -1;
    }
    return 1;
}

std::string cmd_handler::detach(std::string const& in_buf) {
    CLOG(TRACE, connection) << "executing " << __FUNCTION__;
    int ret;

    s.shutdown();

    //    /* Note: The current GDB does not expect a reply */
    //    rp_putpkt(out_buf);
    //    dbg_sock_close();

    CLOG(INFO, connection) << __FUNCTION__ << ": debugger detaching";

    if (!can_restart) {
        /* If the current target cannot restart, we have little choice but
         to exit right now. */
        CLOG(INFO, connection) << __FUNCTION__ << ": target is not restartable. Exiting";
        exit(0);
    }

    CLOG(INFO, connection) << __FUNCTION__ << ": will wait for a new connection";
    return "";
}

std::string cmd_handler::query(std::string const& in_buf) {
    CLOG(TRACE, connection) << "executing " << __FUNCTION__;
    int ret;
    rp_thread_ref ref;
    rp_thread_info info;
    unsigned int len;
    uint32_t val;
    uint64_t addr;

    if (in_buf.size() == 1) {
        CLOG(ERR, connection) << __FUNCTION__ << ": bad 'q' command received";
        return "";
    }
    if (strncmp(in_buf.c_str() + 1, "Attached", 8) == 0) {
        return "1"; // always attached
    }
    if (strncmp(in_buf.c_str() + 1, "Offsets", 7) == 0) {
        uint64_t text;
        uint64_t data;
        uint64_t bss;

        /* Get the program segment offsets */
        ret = t->offsets_query(text, data, bss);
        if (ret == iss::Ok) {
            std::stringstream ss;
            ss << std::hex << "Text=" << text << ";Data=" << data << ";Bss=" << bss;
            return ss.str();
        } else {
            return to_string(ret);
        }
    }

    if (strncmp(in_buf.c_str() + 1, "CRC:", 4) == 0) {
        /* Find the CRC32 value of the specified memory area */
        const char *cp = &in_buf[5];
        if (!encdec.dec_uint64(&cp, &addr, ',')) {
            return "E00";
        }

        if (!encdec.dec_uint32(&cp, &len, '\0')) {
            return "E00";
        }
        ret = t->crc_query(addr, len, val);
        if (ret == iss::Ok) {
            std::stringstream ss;
            ss << "C" << std::hex << val;
            return ss.str();
        } else
            return to_string(ret);
    }

    if (strncmp(in_buf.c_str() + 1, "Symbol:", 7) == 0) {
        return "";
    }

    if (strncmp(in_buf.c_str() + 1, "TStatus:", 8) == 0) {
        return "T0;tnotrun:0";
    }

    if (strncmp(in_buf.c_str() + 1, "ThreadExtraInfo,", 16) == 0) {
        std::string data_buf;
        const char *in;

        if (!(ret = encdec.dec_uint64(&in, &ref.val, '\0'))) {
            return "E00";
        }

        ret = t->threadextrainfo_query(ref, data_buf);
        switch (ret) {
        case iss::Ok:
            return encdec.enc_data((unsigned char *)data_buf.c_str(), strlen(data_buf.c_str()));
            break;
        case iss::Err:
        case iss::NotSupported:
            return to_string(ret);
            break;
        default:
            assert(false);
            break;
        }
        return "";
    }

    if (strncmp(in_buf.c_str() + 1, "fThreadInfo", 11) == 0) {
        std::string buf;
        ret = t->threadinfo_query(1, buf);
        switch (ret) {
        case iss::Ok:
            return buf;
        case iss::NotSupported:
        case iss::Err:
            return to_string(ret);
        default:
            /* This should not happen */
            assert(false);
        }
        return "";
    }

    if (strncmp(in_buf.c_str() + 1, "sThreadInfo", 11) == 0) {
        std::string buf;
        ret = t->threadinfo_query(0, buf);
        switch (ret) {
        case iss::Ok:
            return buf;
        case iss::NotSupported:
        case iss::Err:
            return to_string(ret);
        default:
            /* This should not happen */
            assert(false);
        }
        return "";
    }

    if (strncmp(in_buf.c_str() + 1, "fProcessInfo", 12) == 0) {
        /* Get first string of process info */
        return "";
    }

    if (strncmp(in_buf.c_str() + 1, "sProcessInfo", 12) == 0) {
        /* Get subsequent string of process info */
        return "";
    }

    if (strncmp(in_buf.c_str() + 1, "Rcmd,", 5) == 0) {
        /* Remote command */
        std::stringstream ss;
        auto ret = rcmd(in_buf.c_str() + 6, rp_console_output, [&ss](std::string const& str) -> void { ss << str; });
        if (ret == iss::Ok && ss.str().size() > 0)
            return ss.str();
        else
            return to_string(ret);
    }
    if (strncmp(in_buf.c_str() + 1, "Xfer:features:read:", 19) == 0) {
        /* query features 'Xfer:features:read:annex:offset,length*/
        static std::string buf;
        const std::string start("l"); // last packet otherwise 'm'
        if (buf.size() == 0) t->target_xml_query(buf);
        auto col_pos = in_buf.find_first_of(':', 20);
        auto annex = in_buf.substr(20, col_pos - 20);
        auto cpos = in_buf.find_first_of(',', col_pos);
        auto offset_str = in_buf.substr(col_pos + 1, cpos - col_pos - 1);
        auto length_str = in_buf.substr(cpos + 1);
        // TODO: implement xml handling properly
        return start + buf;
    }
    if (strncmp(in_buf.c_str() + 1, "Supported", 9) == 0 && (in_buf[10] == ':' || in_buf[10] == '\0')) {
        std::string stdFeat("vContSupported+;hwbreak+;swbreak+;qXfer:features:read+");
        //        std::string stdFeat("vContSupported+;hwbreak+;swbreak+");
        // std::string stdFeat("hwbreak+;swbreak+");
        std::string buf;
        ret = t->packetsize_query(buf);
        switch (ret) {
        case iss::Ok:
            return stdFeat + ";" + buf;
        case iss::NotSupported:
        case iss::Err:
            return to_string(ret);
        default:
            /* This should not happen */
            assert(false);
        }
        return "";
    }

    switch (in_buf[1]) {
    case 'C':
        /* Current thread query */
        ret = t->current_thread_query(ref);
        if (ret == iss::Ok) {
            std::stringstream ss;
            ss << "QC" << std::hex << ref.val;
            return ss.str();
        } else
            return to_string(ret);
        break;
    case 'L':
        /* Thread list query */
        {
            rp_thread_ref arg;
            size_t max_found;
            size_t count;
            bool done;
            int first;
            ret = encdec.dec_list_query(&in_buf[2], &first, &max_found, &arg);
            if (!ret || max_found > 255) {
                return "E00";
            }
            std::vector<rp_thread_ref> threads(max_found);

            ret = t->thread_list_query(first, arg, threads, max_found, count, done);
            if (ret != iss::Ok || count > max_found) {
                return to_string(ret);
            }

            std::string res = encdec.enc_list_query_response(count, done, arg, threads);
            if (res.size())
                return res;
            else
                return "E00";
        }
        break;
    case 'P':
        /* Thread info query */
        {
            unsigned int mask;
            if (!(ret = encdec.dec_process_query(&in_buf[2], &mask, &ref))) return "E00";

            info.thread_id.val = 0;
            info.display[0] = 0;
            info.thread_name[0] = 0;
            info.more_display[0] = 0;

            if ((ret = t->process_query(mask, ref, info)) != iss::Ok) return to_string(ret);

            std::string ret = encdec.enc_process_query_response(mask, &ref, &info);
            if (ret.size())
                return ret;
            else
                return "E00";
            break;
        }
    default:
        /* Raw Query is a universal fallback */
        std::string buf;
        ret = t->raw_query(in_buf, buf);
        if (ret != iss::Ok) return to_string(ret);
        break;
    }
    return "";
}

std::string cmd_handler::set(std::string const& in_buf) {
    if (in_buf.find("QPassSignals:", 0) == 0) {
        /* Passing signals not supported */
        return ("");
    } else if (in_buf.find("QTDP", 0) == 0 || in_buf.find("QFrame", 0) == 0 || in_buf.find("QTStart", 0) == 0 ||
               in_buf.find("QTStop", 0) == 0 || in_buf.find("QTinit", 0) == 0 || in_buf.find("QTro", 0) == 0) {
        // a placeholder for tracepont packets, empty response to QTDP should
        // disable it */
        return ("");
    }
    return "";
}

std::string cmd_handler::breakpoint(std::string const& in_buf) {
    CLOG(TRACE, connection) << "executing " << __FUNCTION__;
    uint64_t addr;
    unsigned int len;
    int type;
    int ret;

    if (!(ret = encdec.dec_break(in_buf.c_str(), &type, &addr, &len))) return "E00";

    if (in_buf[0] == 'Z') {
        ret = t->add_break(type, addr, len);
        return "OK";
    } else {
        try {
            ret = t->remove_break(type, addr, len);
            return "OK";
        } catch (...) {
            return "E00";
        }
    }
}

void cmd_handler::interrupt_target() { t->stop(); }

/* Help function, generate help text from command table */
int cmd_handler::rcmd_help(int argc, char *argv[], out_func of, data_func df) {
    CLOG(TRACE, connection) << "executing " << __FUNCTION__;
    char buf[1000 + 1];
    char buf2[1000 + 1];
    int i = 0;

    encdec.enc_string("Remote command help:\n", buf, 1000);
    of("Remote command help:\n");
    df(buf);
    for (i = 0; rp_remote_commands[i].name; i++) {
#ifdef WIN32
        sprintf(buf2, "%-10s %s\n", rp_remote_commands[i].name, rp_remote_commands[i].help);
#else
        snprintf(buf2, 1000, "%-10s %s\n", rp_remote_commands[i].name, rp_remote_commands[i].help);
#endif
        encdec.enc_string(buf2, buf, 1000);
        of(buf2);
        df(buf);
    }
    std::vector<target_adapter_if::custom_command> cc = t->custom_commands();
    for (i = 0; i < cc.size(); i++) {
#ifdef WIN32
        sprintf(buf2, "%-10s %s\n", cc[i].name, cc[i].help);
#else
        snprintf(buf2, 1000, "%-10s %s\n", cc[i].name, cc[i].help);
#endif
        encdec.enc_string(buf2, buf, 1000);
        of(buf2);
        df(buf);
    }
    return iss::Ok;
}

/* Set function, set debug level */
int cmd_handler::rcmd_set(int argc, char *argv[], out_func of, data_func df) {
    CLOG(TRACE, connection) << "executing " << __FUNCTION__;
    char buf[1000 + 1];
    char buf2[1000 + 1];

    if (argc == 1) {
        sprintf(buf2, "Missing argument to set command.\n");
        encdec.enc_string(buf2, buf, 1000);
        of(buf2);
        df(buf);
        return iss::Err;
    }

    if (strcmp("debug", argv[1]) != 0) {
        sprintf(buf2, "Undefined set command: \"%s\"\n", argv[1]);
        encdec.enc_string(buf2, buf, 1000);
        of(buf2);
        df(buf);
        return iss::Err;
    }

    if (argc != 3) {
        sprintf(buf2, "Wrong arguments for debug command.\n");
        encdec.enc_string(buf2, buf, 1000);
        of(buf2);
        df(buf);
        return iss::Err;
    }

    if (strcmp("0", argv[2]) == 0 || strcasecmp("NONE", argv[2]) == 0)
        LOGGER(DEFAULT)::reporting_level() = logging::NONE;
    else if (strcmp("1", argv[2]) == 0 || strcasecmp("FATAL", argv[2]) == 0)
        LOGGER(DEFAULT)::reporting_level() = logging::FATAL;
    else if (strcmp("2", argv[2]) == 0 || strcasecmp("ERROR", argv[2]) == 0)
        LOGGER(DEFAULT)::reporting_level() = logging::ERR;
    else if (strcmp("3", argv[2]) == 0 || strcasecmp("WARNING", argv[2]) == 0)
        LOGGER(DEFAULT)::reporting_level() = logging::WARN;
    else if (strcmp("4", argv[2]) == 0 || strcasecmp("INFO", argv[2]) == 0)
        LOGGER(DEFAULT)::reporting_level() = logging::INFO;
    else if (strcmp("5", argv[2]) == 0 || strcasecmp("DEBUG", argv[2]) == 0)
        LOGGER(DEFAULT)::reporting_level() = logging::DEBUG;
    else if (strcmp("6", argv[2]) == 0 || strcasecmp("TRACE", argv[2]) == 0)
        LOGGER(DEFAULT)::reporting_level() = logging::TRACE;
    else {
        sprintf(buf2, "Invalid debug level: \"%s\"\n", argv[2]);
        encdec.enc_string(buf2, buf, 1000);
        of(buf2);
        df(buf);
        return iss::Err;
    }
    // print unconditional
    LOGGER(DEFAULT)().get(logging::INFO) << "Log level set to " << LOGGER(DEFAULT)::reporting_level();
    return iss::Ok;
}

/* Target method */
int cmd_handler::rcmd(const char *const in_buf, out_func of, data_func df) {
    CLOG(TRACE, connection) << "executing " << __FUNCTION__;
    int count = 0;
    int i;
    char *args[MAXARGS];
    char *ptr;
    unsigned int ch;
    char buf[1000 + 1];
    char *s;

    CLOG(TRACE, connection) << "command '" << in_buf << "'";

    if (strlen(in_buf)) {
        /* There is something to process */
        /* TODO: Handle target specific commands, such as flash erase, JTAG
     control, etc. */
        /* A single example "flash erase" command is partially implemented
     here as an example. */

        /* Turn the hex into ASCII */
        ptr = const_cast<char *>(in_buf);
        s = buf;
        while (*ptr) {
            if (encdec.dec_byte(ptr, &ch) == 0) return iss::Err;
            *s++ = ch;
            ptr += 2;
        }
        *s = '\0';
        CLOG(DEBUG, connection) << "command '" << buf << "'";

        /* Split string into separate arguments */
        ptr = buf;
        args[count++] = ptr;
        while (*ptr) {
            /* Search to the end of the string */
            if (*ptr == ' ') {
                /* Space is the delimiter */
                *ptr = 0;
                if (count >= MAXARGS) return iss::Err;
                args[count++] = ptr + 1;
            }
            ptr++;
        }
        /* Search the command table, and execute the function if found */
        CLOG(TRACE, connection) << "executing target dependant command '" << args[0] << "'";

        /* Search the target command table first, such that we allow target to
         * override the general command.  */
        for (i = 0; i < t->custom_commands().size(); i++) {
            if (strcmp(args[0], t->custom_commands()[i].name) == 0)
                return t->custom_commands()[i].function(count, args, of, df);
        }

        for (i = 0; rp_remote_commands[i].name; i++) {
            if (strcmp(args[0], rp_remote_commands[i].name) == 0) {
                int (cmd_handler::*fptr)(int, char **, out_func, data_func) = rp_remote_commands[i].function;
                return (this->*fptr)(count, args, of, df);
            }
        }
        return iss::NotSupported;
    }
    return iss::Err;
}

boost::optional<std::string> cmd_handler::handle_extended(std::string const& in_buf) {
    if (in_buf.find("vCtrlC", 0) == 0) {
        t->stop();
        return boost::optional<std::string>{"OK"};
        // to be implemented later
    } else if (in_buf.find("vCont", 0) == 0) {
        if (in_buf[5] == '?') {
            // return boost::optional<std::string>{"vCont;c;C;t;s;S"};
            return boost::optional<std::string>{""};
        } else if (in_buf.size() == 5) {
            std::string ret = running("c", false, true);
            if (ret.size() > 0) return ret;
            return boost::optional<std::string>{};
        } else {
            std::string ret = running(in_buf.substr(6), false, true);
            if (ret.size() > 0) return ret;
            return boost::optional<std::string>{};
        }
    } else if (in_buf.find("vRun", 0) == 0) {
        t->restart();
        return boost::optional<std::string>{"S05"};
    } else if (in_buf.find("vAttach", 0) == 0) {
        return boost::optional<std::string>{"S05"};
    } else if (in_buf.find("vCtrlC", 0) == 0) {
        t->stop();
        return boost::optional<std::string>{"OK"};
    } else
        return boost::optional<std::string>{""};
    // not suppported:
    // vFile
    // vFlashErase
    // vFlashWrite
    // vFlashDone
}

max_stars_repo_name: Minres/DBT-RISE-Core

max_issues_repo_name: Minres/DBT-RISE-Core

max_forks_repo_name: Minres/DBT-RISE-Core