text:
/**
 *******************************************************************************
 * ClientMessageHandler.cpp                                                    *
 *                                                                             *
 * Client message handler                                                      *
 *   - Perform CRUD request from client                                        *
 *******************************************************************************
 */

/*
 *******************************************************************************
 *  Headers                                                                    *
 *******************************************************************************
 */
#include "stdinclude.h"

#include "CreatMessage.h"
#include "ReadMessage.h"
#include "UpdateMessage.h"
#include "DeleteMessage.h"

#include "StoreClient.h"
#include "ClientMessageHandler.h"
#include "ConnectionManager.h"

#include <chrono>
#include <boost/bind.hpp>
#include <boost/asio.hpp>

using namespace boost::asio;

/*
 *******************************************************************************
 *  Forward declaraction                                                       *
 *******************************************************************************
 */

/*
 *******************************************************************************
 *  Class declaraction                                                         *
 *******************************************************************************
 */

ClientMessageHandler::ClientMessageHandler(io_service & io,
                                           ConnectionManager& mgr,
                                           StoreManager& store,
                                           ConfigPortal * pcfg):
   StoreMessageHandler(io, mgr, store, pcfg),
   m_strand(io),
   m_pending_tran()
{
}

ClientMessageHandler::~ClientMessageHandler()
{
    for (auto && t: m_pending_tran) {
        if (t.second!=nullptr) {
            delete t.second;
        }
    }
    m_pending_tran.clear();
}

void ClientMessageHandler::handle_time_event()
{
    m_strand.post([this]() {
        using namespace std::chrono;

        system_clock::time_point now = system_clock::now();
        duration<int, std::milli> expires(m_pconfig->get_message_timeout());
        for (auto it = m_pending_tran.begin(); it != m_pending_tran.end(); ) {
            if (it->second->get_creat_time() + expires < now) {
                // Expires
                if (!it->second->is_client_response()) {
                    StoreMessage * resp = construct_client_resp_msg(it->second, MsgStatus::ERROR);
                    if (resp != nullptr) {
                        send_message(resp);
                    }
                }
                delete it->second;
                it = m_pending_tran.erase(it);
            }
            else {
                it++;
            }
        }
    });
}

int ClientMessageHandler::handle_create_request(CreatRequestMessage* pmsg)
{
    // Find who is in charge of the key, and then send server request message to
    // these nodes.
    if (pmsg == nullptr) return -1;
    async_find_nodes(pmsg->get_key(), [this, pmsg](const std::vector<MemberEntry > &v) {
            std::vector<unsigned char> val;
            std::map<ip::tcp::endpoint, StoreClient* > node_clt;
            unsigned long long txid = reinterpret_cast<unsigned long long>(pmsg);

            pmsg->get_value(val);

            ClientTransaction * pclt_tran = new ClientTransaction(pmsg,
                                            ClientTransaction::REQUEST_TYPE::CREAT,
                                            v);
            // TODO: handle errors
            prepare_node_tran(v, pclt_tran, node_clt);
            add_pending_tran(pmsg, pclt_tran);

            int replica_type = -1;
            for (auto&& n : v) {
                boost::asio::ip::tcp::endpoint ep = get_node_endpoint(n);
                replica_type++;
                if (node_clt.find(ep) == node_clt.end()) {
                    getlog()->sendlog(LogLevel::ERROR, "Can't find client for node '%s:%d'\n",
                                     ep.address().to_string().c_str(), ep.port());
                    continue;
                }
                StoreClient * pclt = node_clt[ep];
                if (pclt == nullptr) {
                    m_store.async_creat(pmsg->get_key(), replica_type,
                                        val.data(), val.size(),
                                        [this, txid](int rc) {
                                            handle_store_cud_complete(rc, txid);
                                        });
                }
                else {
                    // Construct server request messages
                    // Send to node n
                    CreatRequestMessage * preq = new CreatRequestMessage(MessageOriginator::Server,
                                                                         reinterpret_cast<int64>(pmsg));
                    preq->set_key(pmsg->get_key());
                    preq->set_value(val.data(), val.size());
                    preq->set_replica_type(replica_type);
                    preq->set_dest_endpoint(ep);
                    pclt->async_call(ep, preq,
                                     [this, txid](const ClientErrorCode& e,
                                                  StoreMessage* presp) {
                                         handle_clt_crud_complete(static_cast<int>(e), presp, txid);
                                     });
                }
            }
        });
    return 0;
}

int ClientMessageHandler::handle_create_response(CreatResponseMessage* pmsg)
{
    // TODO: not support
    return 0;
}

int ClientMessageHandler::handle_read_request(ReadRequestMessage* pmsg)
{
    if (pmsg == nullptr) return -1;
    async_find_nodes(pmsg->get_key(), [this, pmsg](const std::vector<MemberEntry > &v) {
            std::map<ip::tcp::endpoint, StoreClient* > node_clt;
            unsigned long long txid = reinterpret_cast<unsigned long long>(pmsg);

            ClientTransaction * pclt_tran = new ClientTransaction(pmsg,
                                            ClientTransaction::REQUEST_TYPE::READ,
                                            v);
            // TODO: handle errors
            prepare_node_tran(v, pclt_tran, node_clt);
            add_pending_tran(pmsg, pclt_tran);

            int replica_type = -1;
            for (auto&& n : v) {
                boost::asio::ip::tcp::endpoint ep = get_node_endpoint(n);
                replica_type++;
                if (node_clt.find(ep) == node_clt.end()) {
                    getlog()->sendlog(LogLevel::ERROR, "Can't find client for node '%s:%d'\n",
                                     ep.address().to_string().c_str(), ep.port());
                    continue;
                }
                StoreClient * pclt = node_clt[ep];
                if (pclt == nullptr) {
                    m_store.async_read(pmsg->get_key(), replica_type,
                              [this, txid](int rc, unsigned char* val, size_t sz) {
                                  handle_store_r_complete(rc, txid, val, sz);
                              });
                }
                else {
                    // Construct server request messages
                    // Send to node n
                    ReadRequestMessage * preq = new ReadRequestMessage(MessageOriginator::Server,
                                                                       reinterpret_cast<int64>(pmsg));
                    preq->set_key(pmsg->get_key());
                    preq->set_replica_type(replica_type);
                    preq->set_dest_endpoint(ep);
                    pclt->async_call(ep, preq,
                                     [this, txid](const ClientErrorCode& e,
                                                  StoreMessage* presp) {
                                         handle_clt_crud_complete(static_cast<int>(e), presp, txid);
                                     });
                }
            }
        });
    return 0;
}

int ClientMessageHandler::handle_read_response(ReadResponseMessage* pmsg)
{
    if (pmsg == nullptr) return -1;
    return 0;
}

int ClientMessageHandler::handle_update_request(UpdateRequestMessage* pmsg)
{
    if (pmsg == nullptr) return -1;
    async_find_nodes(pmsg->get_key(), [this, pmsg](const std::vector<MemberEntry > &v) {
            std::vector<unsigned char> val;
            std::map<ip::tcp::endpoint, StoreClient* > node_clt;
            unsigned long long txid = reinterpret_cast<unsigned long long>(pmsg);

            pmsg->get_value(val);

            ClientTransaction * pclt_tran = new ClientTransaction(pmsg,
                                            ClientTransaction::REQUEST_TYPE::UPDATE,
                                            v);
            // TODO: handle errors
            prepare_node_tran(v, pclt_tran, node_clt);
            add_pending_tran(pmsg, pclt_tran);

            int replica_type = -1;
            for (auto&& n : v) {
                boost::asio::ip::tcp::endpoint ep = get_node_endpoint(n);
                replica_type++;
                if (node_clt.find(ep) == node_clt.end()) {
                    getlog()->sendlog(LogLevel::ERROR, "Can't find client for node '%s:%d'\n",
                                     ep.address().to_string().c_str(), ep.port());
                    continue;
                }
                StoreClient * pclt = node_clt[ep];
                if (pclt == nullptr) {
                    m_store.async_update(pmsg->get_key(), replica_type,
                                        val.data(), val.size(),
                                        [this, txid](int rc) {
                                            handle_store_cud_complete(rc, txid);
                                        });
                }
                else {
                    // Construct server request messages
                    // Send to node n
                    UpdateRequestMessage * preq = new UpdateRequestMessage(MessageOriginator::Server,
                                                                         reinterpret_cast<int64>(pmsg));
                    preq->set_key(pmsg->get_key());
                    preq->set_value(val.data(), val.size());
                    preq->set_replica_type(replica_type);
                    preq->set_dest_endpoint(ep);
                    pclt->async_call(ep, preq,
                                     [this, txid](const ClientErrorCode& e,
                                                  StoreMessage* presp) {
                                         handle_clt_crud_complete(static_cast<int>(e), presp, txid);
                                     });
                }
            }
        });
    return 0;
}

int ClientMessageHandler::handle_update_response(UpdateResponseMessage* pmsg)
{
    if (pmsg == nullptr) return -1;
    return 0;
}

int ClientMessageHandler::handle_delete_request(DeleteRequestMessage* pmsg)
{
    if (pmsg == nullptr) return -1;
    async_find_nodes(pmsg->get_key(), [this, pmsg](const std::vector<MemberEntry > &v) {
            std::map<ip::tcp::endpoint, StoreClient* > node_clt;
            unsigned long long txid = reinterpret_cast<unsigned long long>(pmsg);

            ClientTransaction * pclt_tran = new ClientTransaction(pmsg,
                                            ClientTransaction::REQUEST_TYPE::DELETE,
                                            v);
            // TODO: handle errors
            prepare_node_tran(v, pclt_tran, node_clt);
            add_pending_tran(pmsg, pclt_tran);

            int replica_type = -1;
            for (auto&& n : v) {
                boost::asio::ip::tcp::endpoint ep = get_node_endpoint(n);
                replica_type++;
                if (node_clt.find(ep) == node_clt.end()) {
                    getlog()->sendlog(LogLevel::ERROR, "Can't find client for node '%s:%d'\n",
                                     ep.address().to_string().c_str(), ep.port());
                    continue;
                }
                StoreClient * pclt = node_clt[ep];
                if (pclt == nullptr) {
                    m_store.async_delete(pmsg->get_key(), replica_type,
                                        [this, txid](int rc) {
                                            handle_store_cud_complete(rc, txid);
                                        });
                }
                else {
                    // Construct server request messages
                    // Send to node n
                    DeleteRequestMessage * preq = new DeleteRequestMessage(MessageOriginator::Server,
                                                                         reinterpret_cast<int64>(pmsg));
                    preq->set_key(pmsg->get_key());
                    preq->set_replica_type(replica_type);
                    preq->set_dest_endpoint(ep);
                    pclt->async_call(ep, preq,
                                     [this, txid](const ClientErrorCode& e,
                                                  StoreMessage* presp) {
                                         handle_clt_crud_complete(static_cast<int>(e), presp, txid);
                                     });
                }
            }
        });
    return 0;
}

int ClientMessageHandler::handle_delete_response(DeleteResponseMessage* pmsg)
{
    if (pmsg == nullptr) return -1;
    return 0;
}

ip::tcp::endpoint ClientMessageHandler::get_node_endpoint(const struct MemberEntry& e)
{
     return ip::tcp::endpoint(rawip2address(e.af, e.address), e.portnumber);
}

ip::tcp::endpoint ClientMessageHandler::get_self_endpoint() const
{
     return ip::tcp::endpoint(m_self_addr, m_self_port);
}

int ClientMessageHandler::prepare_node_tran(
                          const std::vector<struct MemberEntry > & nodes,
                          ClientTransaction * pclt_tran,
                          std::map<ip::tcp::endpoint, StoreClient* > & node_clt)
{
    if (pclt_tran==nullptr) return -1;
    node_clt.clear();
    for (auto&& n : nodes) {
        boost::asio::ip::tcp::endpoint ep = get_node_endpoint(n);
        StoreClient * pclt = nullptr;
        if (!is_self(n)) {
            pclt = new StoreClient(m_pconfig, m_io);
        }
        pclt_tran->start_wait_reply(ep, pclt);
        node_clt[ep] = pclt;
    }
    return 0;
}

void ClientMessageHandler::handle_store_cud_complete(int rc, unsigned long long txid)
{
    m_strand.post([this, rc, txid]() {
        auto it = m_pending_tran.find(txid);
        if (it != m_pending_tran.end()) {
            it->second->add_reply(get_self_endpoint(),
                                  rc);
            handle_node_reply(it);
        }
    });
}

void ClientMessageHandler::handle_store_r_complete(int rc, unsigned long long txid,
                                                   unsigned char* data, size_t sz)
{
    m_strand.post([=]() {
        auto it = m_pending_tran.find(txid);
        if (it != m_pending_tran.end()) {
            it->second->add_reply(get_self_endpoint(),
                                  rc, data, sz);
            handle_node_reply(it);
        }
    });
}

void ClientMessageHandler::handle_clt_crud_complete(int rc,
                                                    StoreMessage * pmsg,
                                                    unsigned long long txid)
{
    m_strand.post([this, rc, pmsg, txid]() {
        auto it = m_pending_tran.find(txid);
        if (it != m_pending_tran.end()) {
            it->second->add_reply(pmsg);
            handle_node_reply(it);
        }
    });
}

void ClientMessageHandler::handle_node_reply(std::map<unsigned long long, ClientTransaction* >::iterator& it)
{
    CheckOperation op = check_clnt_tran(it->second);
    if (op==CheckOperation::SEND_RESP) {
        // construct response message and send back
        StoreMessage * resp = construct_client_resp_msg(it->second, MsgStatus::OK);
        if (resp != nullptr) {
            send_message(resp);
            it->second->mark_send_clnt_resp();
        }
    }
    if (op==CheckOperation::DELETE) {
        if (!it->second->is_client_response()) {
            // failed
            StoreMessage * resp = construct_client_resp_msg(it->second, MsgStatus::ERROR);
            if (resp != nullptr) {
                send_message(resp);
            }
        }
        delete it->second;
        m_pending_tran.erase(it);
    }
}

ClientMessageHandler::CheckOperation ClientMessageHandler::check_clnt_tran(ClientTransaction* pclt_trn)
{
    int total_reply;
    int succ_reply;
    std::tie(total_reply, succ_reply) = pclt_trn->get_reply_count();
    if (succ_reply >= m_pconfig->get_quorum_num()) {
        if (!pclt_trn->is_client_response()) {
            return CheckOperation::SEND_RESP;
        }
    }
    if (total_reply >= pclt_trn->get_wait_count()) {
        return CheckOperation::DELETE;
    }
    return CheckOperation::NOP;
}

void ClientMessageHandler::add_pending_tran(StoreMessage* pmsg,
                                            ClientTransaction * pclt_trn)
{
    if ((pmsg == nullptr) || (pclt_trn==nullptr)) {
        getlog()->sendlog(LogLevel::FATAL, "add pending transaction, nullptr\n");
        return ;
    }
    m_strand.post([this, pmsg, pclt_trn]() {
            if (m_pending_tran.find(reinterpret_cast<unsigned long long>(pmsg)) != m_pending_tran.end()) {
                return;
            }
            m_pending_tran.insert(std::make_pair(reinterpret_cast<unsigned long long>(pmsg), pclt_trn));
        });

}

StoreMessage* ClientMessageHandler::construct_client_resp_msg(ClientTransaction* pclt_trn,
                                                              MsgStatus status)
{
    if (pclt_trn == nullptr) {
        getlog()->sendlog(LogLevel::ERROR, "Consturct client response message got nullptr\n");
        return nullptr;
    }

    StoreMessage * presp = nullptr;
    switch(pclt_trn->get_type()) {
    case ClientTransaction::REQUEST_TYPE::CREAT:
        presp = new CreatResponseMessage(MessageOriginator::Client,
                                         pclt_trn->get_txid(), status);
        break;
    case ClientTransaction::REQUEST_TYPE::READ:
    {
        presp = new ReadResponseMessage(MessageOriginator::Client,
                                        pclt_trn->get_txid(), status);
        std::vector<unsigned char> v;
        pclt_trn->get_read_value(v);
        dynamic_cast<ReadResponseMessage*>(presp)->set_value(v);
        break;
    }
    case ClientTransaction::REQUEST_TYPE::UPDATE:
        //presp = construct_update_response(pclt_trn->get_txid(), status);
        break;
    case ClientTransaction::REQUEST_TYPE::DELETE:
        //presp = construct_delete_response(pclt_trn->get_txid(), status);
        break;
    default:
        break;
    }

    if (presp != nullptr) {
        presp->set_connection(pclt_trn->get_msg()->get_connection());
    }

    return presp;
}

/* eof */

max_stars_repo_name: chenjun-bj/pluto

max_issues_repo_name: chenjun-bj/pluto

max_forks_repo_name: chenjun-bj/pluto


text:
//
// Copyright (c) 2011-2012 Krzysztof Jusiak (krzysztof at jusiak dot net)
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef QFSM_BACK_AUX_CACHE_HPP
#define QFSM_BACK_AUX_CACHE_HPP

#include <boost/optional.hpp>
#include <boost/utility/enable_if.hpp>
#include <boost/type_traits/is_base_of.hpp>
#include <boost/mpl/inherit_linearly.hpp>
#include <boost/mpl/inherit.hpp>
#include <boost/mpl/find_if.hpp>
#include <boost/mpl/transform_view.hpp>
#include <boost/mpl/empty.hpp>
#include <boost/mpl/pop_front.hpp>
#include <boost/mpl/front.hpp>
#include <boost/mpl/bool.hpp>
#include "QFsm/Back/FsmPolicy.hpp"
#include "QFsm/Back/Aux/TransitionTypes.hpp"

namespace QFsm
{
namespace Back
{
namespace Aux
{

namespace Detail { class Cache_ { }; } // namespace Detail

template<typename TTransitionTable, typename TCacheEnabled>
class Cache : Detail::Cache_
{
    struct Guards : boost::mpl::transform_view
        <
            TTransitionTable,
            Aux::Guard<boost::mpl::_2>
        >::type
    { };

    template<typename T> struct Optional
    {
        typedef Optional type;
        typedef boost::optional<bool> element_type;
        element_type field;
    };

    struct Entries : boost::mpl::inherit_linearly
        <
            Guards,
            boost::mpl::inherit< boost::mpl::_1, Optional<boost::mpl::_2> >
        >::type
    { };

public:
    void reset()
    {
        fillTypes<Guards>();
    }

    template<typename T> void set(bool p_value)
    {
        get<T, Optional>(m_entries) = p_value;
    }

    template<typename T> boost::optional<bool> get()
    {
        return get<T, Optional>(m_entries);
    }

private:
    template<typename T> inline typename Optional<T>::element_type& get(Optional<T>& p_arg)
    {
        return p_arg.field;
    }

    template<typename Seq> void fillTypes(typename boost::enable_if< boost::mpl::empty<Seq> >::type* = 0) { }
    template<typename Seq> void fillTypes(typename boost::disable_if< boost::mpl::empty<Seq> >::type* = 0)
    {
        get<typename boost::mpl::front<Seq>::type, Optional>(m_entries);
        fillTypes<typename boost::mpl::pop_front<Seq>::type>();
    }

    Entries m_entries;
};

template<typename TTransitionTable> class Cache<TTransitionTable, CacheDisabled> : Detail::Cache_
{
public:
    void reset() { }
    template<typename T> void set(bool) { }
    template<typename T> boost::mpl::false_ get() { return boost::mpl::false_(); }
};

template<typename Pool> static typename boost::mpl::find_if<typename Pool::type, boost::is_base_of<Detail::Cache_, boost::mpl::_1> >::type::type& cache(Pool& p_pool)
{
    typedef typename boost::mpl::find_if<typename Pool::type, boost::is_base_of<Detail::Cache_, boost::mpl::_1> >::type::type type;
    return p_pool.template acquire<type>();
}

} // namespace Aux
} // namespace Back
} // namespace QFsm

#endif

ext: hpp

max_stars_repo_name: krzysztof-jusiak/qfsm

max_issues_repo_name: krzysztof-jusiak/qfsm

max_forks_repo_name: krzysztof-jusiak/qfsm


text:
//
// Copyright 2005-2007 Adobe Systems Incorporated
//
// Distributed under the Boost Software License, Version 1.0
// See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
//
#ifndef BOOST_GIL_COLOR_CONVERT_HPP
#define BOOST_GIL_COLOR_CONVERT_HPP

#include <boost/gil/channel_algorithm.hpp>
#include <boost/gil/cmyk.hpp>
#include <boost/gil/color_base_algorithm.hpp>
#include <boost/gil/gray.hpp>
#include <boost/gil/metafunctions.hpp>
#include <boost/gil/pixel.hpp>
#include <boost/gil/rgb.hpp>
#include <boost/gil/rgba.hpp>
#include <boost/gil/utilities.hpp>

#include <algorithm>
#include <functional>
#include <type_traits>

namespace boost { namespace gil {

/// Support for fast and simple color conversion.
/// Accurate color conversion using color profiles can be supplied separately in a dedicated module.

// Forward-declare
template <typename P> struct channel_type;

////////////////////////////////////////////////////////////////////////////////////////
///
///                 COLOR SPACE CONVERSION
///
////////////////////////////////////////////////////////////////////////////////////////

/// \ingroup ColorConvert
/// \brief Color Convertion function object. To be specialized for every src/dst color space
template <typename C1, typename C2>
struct default_color_converter_impl
{
    static_assert(
        std::is_same<C1, C2>::value,
        "default_color_converter_impl not specialized for given color spaces");
};

/// \ingroup ColorConvert
/// \brief When the color space is the same, color convertion performs channel depth conversion
template <typename C>
struct default_color_converter_impl<C,C> {
    template <typename P1, typename P2>
    void operator()(const P1& src, P2& dst) const {
        static_for_each(src,dst,default_channel_converter());
    }
};

namespace detail {

/// red * .3 + green * .59 + blue * .11 + .5

// The default implementation of to_luminance uses float0..1 as the intermediate channel type
template <typename RedChannel, typename GreenChannel, typename BlueChannel, typename GrayChannelValue>
struct rgb_to_luminance_fn {
    GrayChannelValue operator()(const RedChannel& red, const GreenChannel& green, const BlueChannel& blue) const {
        return channel_convert<GrayChannelValue>(float32_t(
            channel_convert<float32_t>(red  )*0.30f +
            channel_convert<float32_t>(green)*0.59f +
            channel_convert<float32_t>(blue )*0.11f) );
    }
};

// performance specialization for unsigned char
template <typename GrayChannelValue>
struct rgb_to_luminance_fn<uint8_t,uint8_t,uint8_t, GrayChannelValue> {
    GrayChannelValue operator()(uint8_t red, uint8_t green, uint8_t blue) const {
        return channel_convert<GrayChannelValue>(uint8_t(
            ((uint32_t(red  )*4915 + uint32_t(green)*9667 + uint32_t(blue )*1802) + 8192) >> 14));
    }
};

template <typename GrayChannel, typename RedChannel, typename GreenChannel, typename BlueChannel>
typename channel_traits<GrayChannel>::value_type rgb_to_luminance(const RedChannel& red, const GreenChannel& green, const BlueChannel& blue) {
    return rgb_to_luminance_fn<RedChannel,GreenChannel,BlueChannel,
                               typename channel_traits<GrayChannel>::value_type>()(red,green,blue);
}

}   // namespace detail

/// \ingroup ColorConvert
/// \brief Gray to RGB
template <>
struct default_color_converter_impl<gray_t,rgb_t> {
    template <typename P1, typename P2>
    void operator()(const P1& src, P2& dst) const {
        get_color(dst,red_t())  =
            channel_convert<typename color_element_type<P2, red_t  >::type>(get_color(src,gray_color_t()));
        get_color(dst,green_t())=
            channel_convert<typename color_element_type<P2, green_t>::type>(get_color(src,gray_color_t()));
        get_color(dst,blue_t()) =
            channel_convert<typename color_element_type<P2, blue_t >::type>(get_color(src,gray_color_t()));
    }
};

/// \ingroup ColorConvert
/// \brief Gray to CMYK
/// \todo FIXME: Where does this calculation come from? Shouldn't gray be inverted?
///              Currently, white becomes black and black becomes white.
template <>
struct default_color_converter_impl<gray_t,cmyk_t> {
    template <typename P1, typename P2>
    void operator()(const P1& src, P2& dst) const {
        get_color(dst,cyan_t())=
            channel_traits<typename color_element_type<P2, cyan_t   >::type>::min_value();
        get_color(dst,magenta_t())=
            channel_traits<typename color_element_type<P2, magenta_t>::type>::min_value();
        get_color(dst,yellow_t())=
            channel_traits<typename color_element_type<P2, yellow_t >::type>::min_value();
        get_color(dst,black_t())=
            channel_convert<typename color_element_type<P2, black_t >::type>(get_color(src,gray_color_t()));
    }
};

/// \ingroup ColorConvert
/// \brief RGB to Gray
template <>
struct default_color_converter_impl<rgb_t,gray_t> {
    template <typename P1, typename P2>
    void operator()(const P1& src, P2& dst) const {
        get_color(dst,gray_color_t()) =
            detail::rgb_to_luminance<typename color_element_type<P2,gray_color_t>::type>(
                get_color(src,red_t()), get_color(src,green_t()), get_color(src,blue_t())
            );
    }
};

/// \ingroup ColorConvert
/// \brief RGB to CMYK (not the fastest code in the world)
///
/// k = min(1 - r, 1 - g, 1 - b)
/// c = (1 - r - k) / (1 - k)
/// m = (1 - g - k) / (1 - k)
/// y = (1 - b - k) / (1 - k)
/// where `1` denotes max value of channel type of destination pixel.
///
/// The conversion from RGB to CMYK is based on CMY->CMYK (Version 2)
/// from the Principles of Digital Image Processing - Fundamental Techniques
/// by Burger, Wilhelm, Burge, Mark J.
/// and it is a gross approximation not precise enough for professional work.
///
template <>
struct default_color_converter_impl<rgb_t, cmyk_t>
{
    template <typename SrcPixel, typename DstPixel>
    void operator()(SrcPixel const& src, DstPixel& dst) const
    {
        using src_t = typename channel_type<SrcPixel>::type;
        src_t const r = get_color(src, red_t());
        src_t const g = get_color(src, green_t());
        src_t const b = get_color(src, blue_t());

        using uint_t = typename channel_type<cmyk8_pixel_t>::type;
        uint_t c = channel_invert(channel_convert<uint_t>(r)); // c = 1 - r
        uint_t m = channel_invert(channel_convert<uint_t>(g)); // m = 1 - g
        uint_t y = channel_invert(channel_convert<uint_t>(b)); // y = 1 - b
        uint_t k = (std::min)(c,(std::min)(m,y));              // k = minimum(c, m, y)

        // Apply color correction, strengthening, reducing non-zero components by
        // s = 1 / (1 - k) for k < 1, where 1 denotes dst_t max, otherwise s = 1 (literal).
        uint_t const dst_max = channel_traits<uint_t>::max_value();
        uint_t const s_div   = dst_max - k;
        if (s_div != 0)
        {
            double const s = dst_max / static_cast<double>(s_div);
            c = (c - k) * s;
            m = (m - k) * s;
            y = (y - k) * s;
        }
        else
        {
            // Black only for k = 1 (max of dst_t)
            c = channel_traits<uint_t>::min_value();
            m = channel_traits<uint_t>::min_value();
            y = channel_traits<uint_t>::min_value();
        }
        using dst_t   = typename channel_type<DstPixel>::type;
        get_color(dst, cyan_t())    = channel_convert<dst_t>(c);
        get_color(dst, magenta_t()) = channel_convert<dst_t>(m);
        get_color(dst, yellow_t())  = channel_convert<dst_t>(y);
        get_color(dst, black_t())   = channel_convert<dst_t>(k);
    }
};

/// \ingroup ColorConvert
/// \brief CMYK to RGB (not the fastest code in the world)
///
/// r = 1 - min(1, c*(1-k)+k)
/// g = 1 - min(1, m*(1-k)+k)
/// b = 1 - min(1, y*(1-k)+k)
template <>
struct default_color_converter_impl<cmyk_t,rgb_t> {
    template <typename P1, typename P2>
    void operator()(const P1& src, P2& dst) const {
        using T1 = typename channel_type<P1>::type;
        get_color(dst,red_t())  =
            channel_convert<typename color_element_type<P2,red_t>::type>(
                channel_invert<T1>(
                    (std::min)(channel_traits<T1>::max_value(),
                             T1(channel_multiply(get_color(src,cyan_t()),channel_invert(get_color(src,black_t())))+get_color(src,black_t())))));
        get_color(dst,green_t())=
            channel_convert<typename color_element_type<P2,green_t>::type>(
                channel_invert<T1>(
                    (std::min)(channel_traits<T1>::max_value(),
                             T1(channel_multiply(get_color(src,magenta_t()),channel_invert(get_color(src,black_t())))+get_color(src,black_t())))));
        get_color(dst,blue_t()) =
            channel_convert<typename color_element_type<P2,blue_t>::type>(
                channel_invert<T1>(
                    (std::min)(channel_traits<T1>::max_value(),
                             T1(channel_multiply(get_color(src,yellow_t()),channel_invert(get_color(src,black_t())))+get_color(src,black_t())))));
    }
};

/// \ingroup ColorConvert
/// \brief CMYK to Gray
///
/// gray = (1 - 0.212c - 0.715m - 0.0722y) * (1 - k)
template <>
struct default_color_converter_impl<cmyk_t,gray_t> {
    template <typename P1, typename P2>
    void operator()(const P1& src, P2& dst) const  {
        get_color(dst,gray_color_t())=
            channel_convert<typename color_element_type<P2,gray_color_t>::type>(
                channel_multiply(
                    channel_invert(
                       detail::rgb_to_luminance<typename color_element_type<P1,black_t>::type>(
                            get_color(src,cyan_t()),
                            get_color(src,magenta_t()),
                            get_color(src,yellow_t())
                       )
                    ),
                    channel_invert(get_color(src,black_t()))));
    }
};

namespace detail {

template <typename Pixel>
auto alpha_or_max_impl(Pixel const& p, std::true_type) -> typename channel_type<Pixel>::type
{
    return get_color(p,alpha_t());
}
template <typename Pixel>
auto alpha_or_max_impl(Pixel const&, std::false_type) -> typename channel_type<Pixel>::type
{
    return channel_traits<typename channel_type<Pixel>::type>::max_value();
}

} // namespace detail

// Returns max_value if the pixel has no alpha channel. Otherwise returns the alpha.
template <typename Pixel>
auto alpha_or_max(Pixel const& p) -> typename channel_type<Pixel>::type
{
    return detail::alpha_or_max_impl(
        p,
        mp11::mp_contains<typename color_space_type<Pixel>::type, alpha_t>());
}

/// \ingroup ColorConvert
/// \brief Converting any pixel type to RGBA. Note: Supports homogeneous pixels only.
template <typename C1>
struct default_color_converter_impl<C1,rgba_t> {
    template <typename P1, typename P2>
    void operator()(const P1& src, P2& dst) const {
        using T2 = typename channel_type<P2>::type;
        pixel<T2,rgb_layout_t> tmp;
        default_color_converter_impl<C1,rgb_t>()(src,tmp);
        get_color(dst,red_t())  =get_color(tmp,red_t());
        get_color(dst,green_t())=get_color(tmp,green_t());
        get_color(dst,blue_t()) =get_color(tmp,blue_t());
        get_color(dst,alpha_t())=channel_convert<T2>(alpha_or_max(src));
    }
};

/// \ingroup ColorConvert
///  \brief Converting RGBA to any pixel type. Note: Supports homogeneous pixels only.
///
/// Done by multiplying the alpha to get to RGB, then converting the RGB to the target pixel type
/// Note: This may be slower if the compiler doesn't optimize out constructing/destructing a temporary RGB pixel.
///       Consider rewriting if performance is an issue
template <typename C2>
struct default_color_converter_impl<rgba_t,C2> {
    template <typename P1, typename P2>
    void operator()(const P1& src, P2& dst) const {
        using T1 = typename channel_type<P1>::type;
        default_color_converter_impl<rgb_t,C2>()(
            pixel<T1,rgb_layout_t>(channel_multiply(get_color(src,red_t()),  get_color(src,alpha_t())),
                                   channel_multiply(get_color(src,green_t()),get_color(src,alpha_t())),
                                   channel_multiply(get_color(src,blue_t()), get_color(src,alpha_t())))
            ,dst);
    }
};

/// \ingroup ColorConvert
/// \brief Unfortunately RGBA to RGBA must be explicitly provided - otherwise we get ambiguous specialization error.
template <>
struct default_color_converter_impl<rgba_t,rgba_t> {
    template <typename P1, typename P2>
    void operator()(const P1& src, P2& dst) const {
        static_for_each(src,dst,default_channel_converter());
    }
};

/// @defgroup ColorConvert Color Space Converion
/// \ingroup ColorSpaces
/// \brief Support for conversion between pixels of different color spaces and channel depths

/// \ingroup PixelAlgorithm ColorConvert
/// \brief class for color-converting one pixel to another
struct default_color_converter {
    template <typename SrcP, typename DstP>
    void operator()(const SrcP& src,DstP& dst) const {
        using SrcColorSpace = typename color_space_type<SrcP>::type;
        using DstColorSpace = typename color_space_type<DstP>::type;
        default_color_converter_impl<SrcColorSpace,DstColorSpace>()(src,dst);
    }
};

/// \ingroup PixelAlgorithm
/// \brief helper function for converting one pixel to another using GIL default color-converters
///     where ScrP models HomogeneousPixelConcept
///           DstP models HomogeneousPixelValueConcept
template <typename SrcP, typename DstP>
inline void color_convert(const SrcP& src, DstP& dst) {
    default_color_converter()(src,dst);
}

} }  // namespace boost::gil

#endif

max_issues_repo_name: DevanshSGit/gil

max_forks_repo_name: DevanshSGit/gil


text:
/* boost random/uniform_on_sphere.hpp header file
 *
 * Copyright Jens Maurer 2000-2001
 * Permission to use, copy, modify, sell, and distribute this software
 * is hereby granted without fee provided that the above copyright notice
 * appears in all copies and that both that copyright notice and this
 * permission notice appear in supporting documentation,
 *
 * Jens Maurer makes no representations about the suitability of this
 * software for any purpose. It is provided "as is" without express or
 * implied warranty.
 *
 * See http://www.boost.org for most recent version including documentation.
 *
 * $Id: uniform_on_sphere.hpp 11696 2001-11-14 21:53:38Z jmaurer $
 *
 * Revision history
 *  2001-02-18  moved to individual header files
 */

#ifndef BOOST_RANDOM_UNIFORM_ON_SPHERE_HPP
#define BOOST_RANDOM_UNIFORM_ON_SPHERE_HPP

#include <vector>
#include <algorithm>     // std::transform
#include <functional>    // std::bind2nd, std::divides
#include <boost/random/normal_distribution.hpp>

namespace boost {

template<class UniformRandomNumberGenerator, class RealType = double,
   class Cont = std::vector<RealType> >
class uniform_on_sphere
{
public:
  typedef UniformRandomNumberGenerator base_type;
  typedef Cont result_type;

  explicit uniform_on_sphere(base_type & rng, int dim = 2)
    : _rng(rng), _container(dim), _dim(dim) { }
  // compiler-generated copy ctor is fine
  // normal_distribution cannot be assigned, neither can this class
  const result_type & operator()()
  {
    RealType sqsum = 0;
    for(typename Cont::iterator it = _container.begin();
        it != _container.end();
        ++it) {
      RealType val = _rng();
      *it = val;
      sqsum += val * val;
    }
#ifndef BOOST_NO_STDC_NAMESPACE
    using std::sqrt;
#endif
    // for all i: result[i] /= sqrt(sqsum)
    std::transform(_container.begin(), _container.end(), _container.begin(),
                   std::bind2nd(std::divides<RealType>(), sqrt(sqsum)));
    return _container;
  }

#ifndef BOOST_NO_OPERATORS_IN_NAMESPACE
  friend bool operator==(const uniform_on_sphere& x,
                         const uniform_on_sphere& y)
  { return x._dim == y._dim && x._rng == y._rng; }
#else
  // Use a member function
  bool operator==(const uniform_on_sphere& rhs) const
  { return _dim == rhs._dim && _rng == rhs._rng; }
#endif
private:
  normal_distribution<base_type, RealType> _rng;
  result_type _container;
  const int _dim;
};

} // namespace boost

#endif // BOOST_RANDOM_UNIFORM_ON_SPHERE_HPP


text:
/**
 * \file
 * \brief Load analog library configuration
 *
 * \author Uilian Ries <uilianries@gmail.com>
 */

#include "bbbgpio/analog_config.hpp"

#include <boost/regex.hpp>
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>

namespace bbb {
namespace gpio {

    analog_config::analog_config(unsigned index)
    {
        boost::filesystem::path bone_dir{ "/sys/devices" };
        boost::regex path_filter("bone_capemgr.\\d{1,2}");

        boost::filesystem::directory_iterator end;

        using slot_list = std::vector<boost::filesystem::path>;
        slot_list slots;

        for (boost::filesystem::directory_iterator it(bone_dir); it != end; ++it) {
            if (!boost::filesystem::is_directory(it->status())) {
                continue;
            }

            boost::smatch what;

            if (!boost::regex_match(it->path().string(), what, path_filter)) {
                continue;
            }

            boost::filesystem::path slot = it->path() / "slots";
            slots.push_back(slot);
        }

        for (const auto& slot : slots) {
            boost::filesystem::ofstream ofs(slot);
            if (!ofs) {
                throw std::runtime_error("Could not open cape bone slot file");
            }

            constexpr auto cape_bone = "cape-bone-iio";
            ofs << cape_bone;
        }

        auto analog_slot = "AIN" + std::to_string(index);

        boost::filesystem::recursive_directory_iterator recursive_end;
        auto analog_path = std::find_if(boost::filesystem::recursive_directory_iterator(bone_dir), recursive_end,
            [&analog_slot](const boost::filesystem::directory_entry& entry) {
                                        return entry.path().filename() == analog_slot;
            });

        if (analog_path == recursive_end) {
            throw std::runtime_error("Could not find AINx");
        }

        pin_path_ = analog_path->path();
    }

    boost::filesystem::path analog_config::get_value() const noexcept
    {
        return pin_path_;
    }

} // namespace gpio
} // namespace bbb

ext: cpp

max_stars_repo_name: uilianries/BeagleBoneBlackGPIO

max_issues_repo_name: uilianries/BeagleBoneBlackGPIO

max_forks_repo_name: uilianries/BeagleBoneBlackGPIO


text:
/*********************************************************************
* Software License Agreement (BSD License)
*
*  Copyright (c) 2008, Willow Garage, Inc.
*  All rights reserved.
*
*  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 the Willow Garage 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.
*********************************************************************/
#include <boost/version.hpp>
#if ((BOOST_VERSION / 100) % 1000) >= 53
#include <boost/thread/lock_guard.hpp>
#endif

#include <ros/ros.h>
#include <nodelet/nodelet.h>
#include <image_transport/image_transport.h>
#include <image_transport/subscriber_filter.h>
#include <message_filters/subscriber.h>
#include <message_filters/synchronizer.h>
#include <message_filters/sync_policies/exact_time.h>
#include <message_filters/sync_policies/approximate_time.h>
#include <sensor_msgs/image_encodings.h>
#include <sensor_msgs/point_cloud2_iterator.h>
#include <sensor_msgs/PointCloud2.h>
#include <image_geometry/pinhole_camera_model.h>
#include <depth_image_proc/depth_traits.h>
#include <cv_bridge/cv_bridge.h>
#include <opencv2/imgproc/imgproc.hpp>

namespace depth_image_proc {

using namespace message_filters::sync_policies;
namespace enc = sensor_msgs::image_encodings;

class PointCloudXyzrgbNodelet : public nodelet::Nodelet
{
  ros::NodeHandlePtr rgb_nh_;
  boost::shared_ptr<image_transport::ImageTransport> rgb_it_, depth_it_;

  // Subscriptions
  image_transport::SubscriberFilter sub_depth_, sub_rgb_;
  message_filters::Subscriber<sensor_msgs::CameraInfo> sub_info_;
  typedef ApproximateTime<sensor_msgs::Image, sensor_msgs::Image, sensor_msgs::CameraInfo> SyncPolicy;
  typedef ExactTime<sensor_msgs::Image, sensor_msgs::Image, sensor_msgs::CameraInfo> ExactSyncPolicy;
  typedef message_filters::Synchronizer<SyncPolicy> Synchronizer;
  typedef message_filters::Synchronizer<ExactSyncPolicy> ExactSynchronizer;
  boost::shared_ptr<Synchronizer> sync_;
  boost::shared_ptr<ExactSynchronizer> exact_sync_;

  // Publications
  boost::mutex connect_mutex_;
  typedef sensor_msgs::PointCloud2 PointCloud;
  ros::Publisher pub_point_cloud_;

  image_geometry::PinholeCameraModel model_;

  virtual void onInit();

  void connectCb();

  void imageCb(const sensor_msgs::ImageConstPtr& depth_msg,
               const sensor_msgs::ImageConstPtr& rgb_msg,
               const sensor_msgs::CameraInfoConstPtr& info_msg);

  template<typename T>
  void convert(const sensor_msgs::ImageConstPtr& depth_msg,
               const sensor_msgs::ImageConstPtr& rgb_msg,
               const PointCloud::Ptr& cloud_msg,
               int red_offset, int green_offset, int blue_offset, int color_step);
};

void PointCloudXyzrgbNodelet::onInit()
{
  ros::NodeHandle& nh         = getNodeHandle();
  ros::NodeHandle& private_nh = getPrivateNodeHandle();
  rgb_nh_.reset( new ros::NodeHandle(nh, "rgb") );
  ros::NodeHandle depth_nh(nh, "depth_registered");
  rgb_it_  .reset( new image_transport::ImageTransport(*rgb_nh_) );
  depth_it_.reset( new image_transport::ImageTransport(depth_nh) );

  // Read parameters
  int queue_size;
  private_nh.param("queue_size", queue_size, 5);
  bool use_exact_sync;
  private_nh.param("exact_sync", use_exact_sync, false);

  // Synchronize inputs. Topic subscriptions happen on demand in the connection callback.
  if (use_exact_sync)
  {
    exact_sync_.reset( new ExactSynchronizer(ExactSyncPolicy(queue_size), sub_depth_, sub_rgb_, sub_info_) );
    exact_sync_->registerCallback(boost::bind(&PointCloudXyzrgbNodelet::imageCb, this, _1, _2, _3));
  }
  else
  {
    sync_.reset( new Synchronizer(SyncPolicy(queue_size), sub_depth_, sub_rgb_, sub_info_) );
    sync_->registerCallback(boost::bind(&PointCloudXyzrgbNodelet::imageCb, this, _1, _2, _3));
  }

  // Monitor whether anyone is subscribed to the output
  ros::SubscriberStatusCallback connect_cb = boost::bind(&PointCloudXyzrgbNodelet::connectCb, this);
  // Make sure we don't enter connectCb() between advertising and assigning to pub_point_cloud_
  boost::lock_guard<boost::mutex> lock(connect_mutex_);
  pub_point_cloud_ = depth_nh.advertise<PointCloud>("points", 1, connect_cb, connect_cb);
}

// Handles (un)subscribing when clients (un)subscribe
void PointCloudXyzrgbNodelet::connectCb()
{
  boost::lock_guard<boost::mutex> lock(connect_mutex_);
  if (pub_point_cloud_.getNumSubscribers() == 0)
  {
    sub_depth_.unsubscribe();
    sub_rgb_  .unsubscribe();
    sub_info_ .unsubscribe();
  }
  else if (!sub_depth_.getSubscriber())
  {
    ros::NodeHandle& private_nh = getPrivateNodeHandle();
    // parameter for depth_image_transport hint
    std::string depth_image_transport_param = "depth_image_transport";

    // depth image can use different transport.(e.g. compressedDepth)
    image_transport::TransportHints depth_hints("raw",ros::TransportHints(), private_nh, depth_image_transport_param);
    sub_depth_.subscribe(*depth_it_, "image_rect",       1, depth_hints);

    // rgb uses normal ros transport hints.
    image_transport::TransportHints hints("raw", ros::TransportHints(), private_nh);
    sub_rgb_  .subscribe(*rgb_it_,   "image_rect_color", 1, hints);
    sub_info_ .subscribe(*rgb_nh_,   "camera_info",      1);
  }
}

void PointCloudXyzrgbNodelet::imageCb(const sensor_msgs::ImageConstPtr& depth_msg,
                                      const sensor_msgs::ImageConstPtr& rgb_msg_in,
                                      const sensor_msgs::CameraInfoConstPtr& info_msg)
{
  // Check for bad inputs
  if (depth_msg->header.frame_id != rgb_msg_in->header.frame_id)
  {
    NODELET_ERROR_THROTTLE(5, "Depth image frame id [%s] doesn't match RGB image frame id [%s]",
                           depth_msg->header.frame_id.c_str(), rgb_msg_in->header.frame_id.c_str());
    return;
  }

  // Update camera model
  model_.fromCameraInfo(info_msg);

  // Check if the input image has to be resized
  sensor_msgs::ImageConstPtr rgb_msg = rgb_msg_in;
  if (depth_msg->width != rgb_msg->width || depth_msg->height != rgb_msg->height)
  {
    sensor_msgs::CameraInfo info_msg_tmp = *info_msg;
    info_msg_tmp.width = depth_msg->width;
    info_msg_tmp.height = depth_msg->height;
    float ratio = float(depth_msg->width)/float(rgb_msg->width);
    // float ratio = float(depth_msg->height)/float(rgb_msg->height);
    info_msg_tmp.K[0] *= ratio;
    info_msg_tmp.K[2] *= ratio;
    info_msg_tmp.K[4] *= ratio;
    info_msg_tmp.K[5] *= ratio;
    info_msg_tmp.P[0] *= ratio;
    info_msg_tmp.P[2] *= ratio;
    info_msg_tmp.P[5] *= ratio;
    info_msg_tmp.P[6] *= ratio;
    model_.fromCameraInfo(info_msg_tmp);

    cv_bridge::CvImageConstPtr cv_ptr;
    try
    {
      cv_ptr = cv_bridge::toCvShare(rgb_msg, rgb_msg->encoding);
    }
    catch (cv_bridge::Exception& e)
    {
      ROS_ERROR("cv_bridge exception: %s", e.what());
      return;
    }
    cv_bridge::CvImage cv_rsz;
    cv_rsz.header = cv_ptr->header;
    cv_rsz.encoding = cv_ptr->encoding;

    // TODO: Fix terrible hack
    int ind = depth_msg->height / ratio;
    if (ind >= cv_ptr->image.rows)
    {
      ind = cv_ptr->image.rows - 1;
    }
    cv::resize(cv_ptr->image.rowRange(0,ind), cv_rsz.image, cv::Size(depth_msg->width, depth_msg->height));
    // cv::resize(cv_ptr->image.rowRange(0,depth_msg->height/ratio), cv_rsz.image, cv::Size(depth_msg->width, depth_msg->height));
    if ((rgb_msg->encoding == enc::RGB8) || (rgb_msg->encoding == enc::BGR8) || (rgb_msg->encoding == enc::MONO8))
      rgb_msg = cv_rsz.toImageMsg();
    else
      rgb_msg = cv_bridge::toCvCopy(cv_rsz.toImageMsg(), enc::RGB8)->toImageMsg();

    //NODELET_ERROR_THROTTLE(5, "Depth resolution (%ux%u) does not match RGB resolution (%ux%u)",
    //                       depth_msg->width, depth_msg->height, rgb_msg->width, rgb_msg->height);
    //return;
  } else
    rgb_msg = rgb_msg_in;

  // Supported color encodings: RGB8, BGR8, MONO8
  int red_offset, green_offset, blue_offset, color_step;
  if (rgb_msg->encoding == enc::RGB8)
  {
    red_offset   = 0;
    green_offset = 1;
    blue_offset  = 2;
    color_step   = 3;
  }
  else if (rgb_msg->encoding == enc::BGR8)
  {
    red_offset   = 2;
    green_offset = 1;
    blue_offset  = 0;
    color_step   = 3;
  }
  else if (rgb_msg->encoding == enc::MONO8)
  {
    red_offset   = 0;
    green_offset = 0;
    blue_offset  = 0;
    color_step   = 1;
  }
  else
  {
    try
    {
      rgb_msg = cv_bridge::toCvCopy(rgb_msg, enc::RGB8)->toImageMsg();
    }
    catch (cv_bridge::Exception& e)
    {
      NODELET_ERROR_THROTTLE(5, "Unsupported encoding [%s]: %s", rgb_msg->encoding.c_str(), e.what());
      return;
    }
    red_offset   = 0;
    green_offset = 1;
    blue_offset  = 2;
    color_step   = 3;
  }

  // Allocate new point cloud message
  PointCloud::Ptr cloud_msg (new PointCloud);
  cloud_msg->header = depth_msg->header; // Use depth image time stamp
  cloud_msg->height = depth_msg->height;
  cloud_msg->width  = depth_msg->width;
  cloud_msg->is_dense = false;
  cloud_msg->is_bigendian = false;

  sensor_msgs::PointCloud2Modifier pcd_modifier(*cloud_msg);
  pcd_modifier.setPointCloud2FieldsByString(2, "xyz", "rgb");

  if (depth_msg->encoding == enc::TYPE_16UC1)
  {
    convert<uint16_t>(depth_msg, rgb_msg, cloud_msg, red_offset, green_offset, blue_offset, color_step);
  }
  else if (depth_msg->encoding == enc::TYPE_32FC1)
  {
    convert<float>(depth_msg, rgb_msg, cloud_msg, red_offset, green_offset, blue_offset, color_step);
  }
  else
  {
    NODELET_ERROR_THROTTLE(5, "Depth image has unsupported encoding [%s]", depth_msg->encoding.c_str());
    return;
  }

  pub_point_cloud_.publish (cloud_msg);
}

template<typename T>
void PointCloudXyzrgbNodelet::convert(const sensor_msgs::ImageConstPtr& depth_msg,
                                      const sensor_msgs::ImageConstPtr& rgb_msg,
                                      const PointCloud::Ptr& cloud_msg,
                                      int red_offset, int green_offset, int blue_offset, int color_step)
{
  // Use correct principal point from calibration
  float center_x = model_.cx();
  float center_y = model_.cy();

  // Combine unit conversion (if necessary) with scaling by focal length for computing (X,Y)
  double unit_scaling = DepthTraits<T>::toMeters( T(1) );
  float constant_x = unit_scaling / model_.fx();
  float constant_y = unit_scaling / model_.fy();
  float bad_point = std::numeric_limits<float>::quiet_NaN ();

  const T* depth_row = reinterpret_cast<const T*>(&depth_msg->data[0]);
  int row_step = depth_msg->step / sizeof(T);
  const uint8_t* rgb = &rgb_msg->data[0];
  int rgb_skip = rgb_msg->step - rgb_msg->width * color_step;

  sensor_msgs::PointCloud2Iterator<float> iter_x(*cloud_msg, "x");
  sensor_msgs::PointCloud2Iterator<float> iter_y(*cloud_msg, "y");
  sensor_msgs::PointCloud2Iterator<float> iter_z(*cloud_msg, "z");
  sensor_msgs::PointCloud2Iterator<uint8_t> iter_r(*cloud_msg, "r");
  sensor_msgs::PointCloud2Iterator<uint8_t> iter_g(*cloud_msg, "g");
  sensor_msgs::PointCloud2Iterator<uint8_t> iter_b(*cloud_msg, "b");
  sensor_msgs::PointCloud2Iterator<uint8_t> iter_a(*cloud_msg, "a");

  for (int v = 0; v < int(cloud_msg->height); ++v, depth_row += row_step, rgb += rgb_skip)
  {
    for (int u = 0; u < int(cloud_msg->width); ++u, rgb += color_step, ++iter_x, ++iter_y, ++iter_z, ++iter_a, ++iter_r, ++iter_g, ++iter_b)
    {
      T depth = depth_row[u];

      // Check for invalid measurements
      if (!DepthTraits<T>::valid(depth))
      {
        *iter_x = *iter_y = *iter_z = bad_point;
      }
      else
      {
        // Fill in XYZ
        *iter_x = (u - center_x) * depth * constant_x;
        *iter_y = (v - center_y) * depth * constant_y;
        *iter_z = DepthTraits<T>::toMeters(depth);
      }

      // Fill in color
      *iter_a = 255;
      *iter_r = rgb[red_offset];
      *iter_g = rgb[green_offset];
      *iter_b = rgb[blue_offset];
    }
  }
}

} // namespace depth_image_proc

// Register as nodelet
#include <pluginlib/class_list_macros.h>
PLUGINLIB_EXPORT_CLASS(depth_image_proc::PointCloudXyzrgbNodelet,nodelet::Nodelet);


text:
//
// Copyright 2017 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
//    names, trademarks, service marks, or product names of the Licensor
//    and its affiliates, except as required to comply with Section 4(c) of
//    the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#include "pxr/pxr.h"
#include "pxr/usd/sdf/path.h"

#include "pxr/base/tf/stopwatch.h"
#include "pxr/base/tf/diagnostic.h"

#include <atomic>
#include <ctime>
#include <cstdlib>
#include <mutex>
#include <thread>

#include <boost/program_options.hpp>

using std::string;
using std::vector;
namespace boost_po = boost::program_options;

PXR_NAMESPACE_USING_DIRECTIVE

static unsigned int randomSeed;
static size_t numThreads;
static size_t msecsToRun = 2000;

TF_MAKE_STATIC_DATA(vector<TfToken>, nameTokens)
{
    nameTokens->push_back(TfToken("A"));
    nameTokens->push_back(TfToken("B"));
    nameTokens->push_back(TfToken("C"));

    // Create a large number of candidates to try to exercise paths
    // over the SD_PATH_BINARY_SEARCH_THRESHOLD.
    for (int i=0; i < 64; ++i) {
        std::string s = TfStringPrintf("x_%i", i);
        nameTokens->push_back(TfToken(s));
    }
}

static TfToken
_GetRandomNameToken()
{
    return (*nameTokens)[rand() % nameTokens->size()];
}

static SdfPath
_MakeRandomPrimPath()
{
    static const size_t maxDepth = 2;
    SdfPath ret = SdfPath::AbsoluteRootPath();
    for (size_t i = 0, depth = rand() % maxDepth; i <= depth; ++i)
        ret = ret.AppendChild(_GetRandomNameToken());
    return ret;
}

static SdfPath
_MakeRandomPrimOrPropertyPath()
{
    SdfPath ret = _MakeRandomPrimPath();
    return rand() & 1 ? ret : ret.AppendProperty(_GetRandomNameToken());
}

static SdfPath
_MakeRandomPath(SdfPath const &path = SdfPath::AbsoluteRootPath())
{
    SdfPath ret = path;

    // Absolute root -> prim path.
    if (path == SdfPath::AbsoluteRootPath())
        ret = _MakeRandomPrimPath();

    // Extend a PrimPath.
    if (ret.IsPrimPath() && (rand() & 1)) {
        ret = ret.AppendVariantSelection(_GetRandomNameToken().GetString(),
                                         _GetRandomNameToken().GetString());
    }

    // Extend a PrimPath or a PrimVariantSelectionPath.
    if ((ret.IsPrimPath() || ret.IsPrimVariantSelectionPath())) {
        return (rand() & 1) ? ret :
            _MakeRandomPath(ret.AppendProperty(_GetRandomNameToken()));
    }

    // Extend a PrimPropertyPath
    if (ret.IsPrimPropertyPath()) {
        // options: target path, mapper path, expression path, or leave alone.
        switch (rand() & 3) {
        case 0:
            return _MakeRandomPath(
                ret.AppendTarget(_MakeRandomPrimOrPropertyPath()));
        case 1:
            return _MakeRandomPath(
                ret.AppendMapper(_MakeRandomPrimOrPropertyPath()));
        case 2:
            return _MakeRandomPath(ret.AppendExpression());
        case 3:
            return ret;
        };
    }

    // Extend a TargetPath
    if (ret.IsTargetPath()) {
        return (rand() & 1) ? ret :
            _MakeRandomPath(
            ret.AppendRelationalAttribute(_GetRandomNameToken()));
    }

    // Extend a MapperPath
    if (ret.IsMapperPath()) {
        return (rand() & 1) ? ret :
            _MakeRandomPath(ret.AppendMapperArg(_GetRandomNameToken()));
    }

    // Extend a RelationalAttributePath
    if (ret.IsRelationalAttributePath()) {
        return (rand() & 1) ? ret :
            _MakeRandomPath(ret.AppendTarget(_MakeRandomPrimOrPropertyPath()));
    }

    return ret;
}

TF_MAKE_STATIC_DATA(SdfPathVector, pathCache)
{
    static const size_t pathCacheSize = 32;
    *pathCache = SdfPathVector(pathCacheSize);
    for (size_t i = 0; i != pathCache->size(); ++i)
        (*pathCache)[i] = _MakeRandomPath();
}

static TfStaticData<std::mutex> pathCacheMutex;

static void _PutPath(SdfPath const &path)
{
    std::lock_guard<std::mutex> lock(*pathCacheMutex);
    size_t index = rand() % pathCache->size();
    (*pathCache)[index] = path;
}

static SdfPath _GetPath()
{
    std::lock_guard<std::mutex> lock(*pathCacheMutex);
    size_t index = rand() % pathCache->size();
    return (*pathCache)[index];
}

static std::atomic_int nIters(0);

static TfStopwatch _DoPathOperations()
{
    TfStopwatch sw;

    while (static_cast<size_t>(sw.GetMilliseconds()) < msecsToRun) {
        sw.Start();
        SdfPath p = (rand() & 1) ? _GetPath() : SdfPath::AbsoluteRootPath();
        // If the path is not very extensible, trim it back to the prim path.
        if (p.IsExpressionPath() || p.IsMapperArgPath() || p.IsMapperPath())
            p = p.GetPrimPath();

        SdfPath randomP = _MakeRandomPath(p);
        _PutPath(randomP);

        sw.Stop();
        ++nIters;
    }

    return sw;
}

int main(int argc, char const **argv)
{
    // Set up arguments and their defaults
    boost_po::options_description desc("Options");
    desc.add_options()

        ("seed",
        boost_po::value<unsigned int>(&randomSeed)->default_value(time(NULL)),
        "Random seed")

        ("numThreads",
        boost_po::value<size_t>(&numThreads)->default_value(
            std::thread::hardware_concurrency()),
        "Number of threads to use")

        ("msec",
        boost_po::value<size_t>(&msecsToRun)->default_value(2000),
        "Milliseconds to run")
    ;

    boost_po::variables_map vm;
    try {
        boost_po::store(boost_po::parse_command_line(argc, argv, desc), vm);
        boost_po::notify(vm);
    } catch (const boost_po::error &e) {
        fprintf(stderr, "%s\n", e.what());
        fprintf(stderr, "%s\n", TfStringify(desc).c_str());
        exit(1);
    }

    // Initialize.
    srand(randomSeed);
    printf("Using random seed: %d\n", randomSeed);
    printf("Using %zu threads\n", numThreads);

    // Run.
    TfStopwatch sw;
    sw.Start();

    std::vector<std::thread> workers;
    for (size_t i = 0; i < numThreads; ++i) {
        workers.emplace_back(_DoPathOperations);
    }

    std::for_each(workers.begin(), workers.end(),
                  [](std::thread& t) { t.join(); });

    sw.Stop();

    // Report.
    printf("Ran %d SdfPath operations on %zu thread%s in %.3f sec "
           "(%.3f ops/sec)\n", (int)nIters, numThreads,
           numThreads > 1 ? "s" : "", sw.GetSeconds(),
           double((int)nIters) / sw.GetSeconds());
    return 0;
}

max_stars_repo_name: navefx/YuksUSD

max_issues_repo_name: piscees/USD

max_forks_repo_name: piscees/USD


text:
/*
 * MinePlant.cpp
 *
 *  Created on: Dec 13, 2017
 *      Author: ranjeet
 */

#include "mineplant.h"

#ifdef ETH_ETHASHCL
#include "libegihash-cl/OpenCLMiner.h"
#endif

#ifdef ETH_ETHASHCUDA
#include "libnrghash-cuda/CUDAMiner.h"
#endif

#include "nrgcore/miner.h"
#include "primitives/work.h"
#include "energiminer/CpuMiner.h"
#include "energiminer/TestMiner.h"

#include "common/common.h"
#include "common/Log.h"

#include <boost/bind.hpp>
#include <iostream>
#include <limits>

using namespace energi;

MinerPtr createMiner(EnumMinerEngine minerEngine, int index, const MinePlant &plant)
{
#if ETH_ETHASHCL
    if (minerEngine == EnumMinerEngine::kCL) {
        return MinerPtr(new OpenCLMiner(plant, index));
    }
#endif
#if ETH_ETHASHCUDA
    if (minerEngine == EnumMinerEngine::kCUDA) {
        return MinerPtr(new CUDAMiner(plant, index));
    }
#endif
    if (minerEngine == EnumMinerEngine::kCPU) {
        return MinerPtr(new CpuMiner(plant, index));
    }
    if (minerEngine == EnumMinerEngine::kTest) {
        return MinerPtr(new TestMiner(plant, index));
    }
    return nullptr;
}

MinePlant::MinePlant(boost::asio::io_service & io_service)
    : m_io_strand(io_service)
    , m_hashrateTimer(io_service)
{
    std::random_device engine;
    m_nonceScumbler = std::uniform_int_distribution<uint64_t>()(engine);

    // Init HWMON
    adlh = wrap_adl_create();
#if defined(__linux)
    sysfsh = wrap_amdsysfs_create();
#endif
    nvmlh = wrap_nvml_create();
}

MinePlant::~MinePlant()
{
    // Deinit HWMON
    if (adlh) {
        wrap_adl_destroy(adlh);
    }
#if defined(__linux)
    if (sysfsh) {
        wrap_amdsysfs_destroy(sysfsh);
    }
#endif
    if (nvmlh) {
        wrap_nvml_destroy(nvmlh);
    }
    stop();
}

bool MinePlant::start(const std::vector<EnumMinerEngine> &vMinerEngine)
{
    std::lock_guard<std::mutex> lock(x_minerWork);
    if (isMining()) {
        return true;
    }
    //m_started = true;
    for ( auto &minerEngine : vMinerEngine) {
        unsigned count = 0;
#if ETH_ETHASHCL
        if (minerEngine == EnumMinerEngine::kCL) {
            count = OpenCLMiner::instances();
        }
#endif
#if ETH_ETHASHCUDA
        if (minerEngine == EnumMinerEngine::kCUDA) {
            count = CUDAMiner::instances();
        }
#endif
        if (minerEngine == EnumMinerEngine::kTest) {
            count = 2;
        }
        if (minerEngine == EnumMinerEngine::kCPU) {
            count = std::thread::hardware_concurrency() - 1;
        }
        for ( unsigned i = 0; i < count; ++i ) {
            m_miners.push_back(createMiner(minerEngine, i, *this));
            m_miners.back()->startWorking();
        }
    }
    m_isMining.store(true, std::memory_order_relaxed);

    // Start hashrate collector
    m_hashrateTimer.cancel();
    m_hashrateTimer.expires_from_now(boost::posix_time::milliseconds(1000));
    m_hashrateTimer.async_wait(m_io_strand.wrap(boost::bind(&MinePlant::processHashRate, this, boost::asio::placeholders::error)));

    return true;
}

void MinePlant::stop()
{
    if (isMining()) {
        {
            std::lock_guard<std::mutex> lock(x_minerWork);
            m_miners.clear();
            m_isMining = false;
        }

        m_hashrateTimer.cancel();

        m_lastProgresses.clear();
    }
}

void MinePlant::setWork(const Work& work)
{
    //Collect hashrate before miner reset their work
    collectHashRate();
    std::lock_guard<std::mutex> lock(x_minerWork);
    // if new work hasnt changed, then ignore
    if (work == m_work) {
        for (auto& miner : m_miners) {
            miner->startWorking();
        }
    }
    cnote << "New Work assigned: Height: "
          << work.nHeight
          << "PrevHash:"
          << work.hashPrevBlock.ToString();
    m_work = work;

    // Propagate to all miners
    for (auto &miner: m_miners) {
        miner->setWork(work);
    }
}

void MinePlant::submitProof(const Solution& solution) const
{
    assert(m_onSolutionFound);
    m_onSolutionFound(solution);
}

void MinePlant::collectHashRate()
{
    std::lock_guard<std::mutex> lock(x_minerWork);

    auto now = std::chrono::steady_clock::now();

    WorkingProgress p;
    p.ms = std::chrono::duration_cast<std::chrono::milliseconds>(now - m_lastStart).count();
    m_lastStart = now;

    //Collect
    for (auto const& miner : m_miners) {
        auto minerHashCount = miner->RetrieveAndClearHashCount();
        p.hashes += minerHashCount;
        p.minersHashes.insert(std::make_pair<std::string, uint64_t>(miner->name(), std::move(minerHashCount)));
    }
    if (p.hashes > 0) {
        m_lastProgresses.push_back(p);
    }
    // We smooth the hashrate over the last x seconds
    uint64_t allMs = 0;
    for (auto const& cp : m_lastProgresses){
        allMs += cp.ms;
    }
    if (allMs > m_hashrateSmoothInterval) {
        m_lastProgresses.erase(m_lastProgresses.begin());
    }
}

/*
 * @brief Get information on the progress of mining this work.
 * @return The progress with mining so far.
 */
const WorkingProgress& MinePlant::miningProgress(bool hwmon, bool power) const
{
    std::lock_guard<std::mutex> lock(x_minerWork);
    WorkingProgress p;
    p.ms = 0;
    p.hashes = 0;
    for (auto const& i : m_miners) {
        p.miningIsPaused.insert(std::make_pair<std::string, bool>(i->name(), i->is_mining_paused()));
        p.minersHashes.insert(std::make_pair<std::string, uint64_t>(i->name(), 0));
        if (hwmon) {
            HwMonitorInfo hwInfo = i->hwmonInfo();
            HwMonitor hw;
            unsigned int tempC = 0, fanpcnt = 0, powerW = 0;
            if (hwInfo.deviceIndex >= 0) {
                if (hwInfo.deviceType == HwMonitorInfoType::NVIDIA && nvmlh) {
                    int typeidx = 0;
                    if (hwInfo.indexSource == HwMonitorIndexSource::CUDA){
                        typeidx = nvmlh->cuda_nvml_device_id[hwInfo.deviceIndex];
                    } else if (hwInfo.indexSource == HwMonitorIndexSource::OPENCL){
                        typeidx = nvmlh->opencl_nvml_device_id[hwInfo.deviceIndex];
                    } else {
                        //Unknown, don't map
                        typeidx = hwInfo.deviceIndex;
                    }
                    wrap_nvml_get_tempC(nvmlh, typeidx, &tempC);
                    wrap_nvml_get_fanpcnt(nvmlh, typeidx, &fanpcnt);
                    if (power) {
                        wrap_nvml_get_power_usage(nvmlh, typeidx, &powerW);
                    }
                } else if (hwInfo.deviceType == HwMonitorInfoType::AMD && adlh) {
                    int typeidx = 0;
                    if (hwInfo.indexSource == HwMonitorIndexSource::OPENCL) {
                        typeidx = adlh->opencl_adl_device_id[hwInfo.deviceIndex];
                    } else {
                        //Unknown, don't map
                        typeidx = hwInfo.deviceIndex;
                    }
                    wrap_adl_get_tempC(adlh, typeidx, &tempC);
                    wrap_adl_get_fanpcnt(adlh, typeidx, &fanpcnt);
                    if (power) {
                        wrap_adl_get_power_usage(adlh, typeidx, &powerW);
                    }
                }
#if defined(__linux)
                // Overwrite with sysfs data if present
                if (hwInfo.deviceType == HwMonitorInfoType::AMD && sysfsh) {
                    int typeidx = 0;
                    if (hwInfo.indexSource == HwMonitorIndexSource::OPENCL){
                        typeidx = sysfsh->opencl_sysfs_device_id[hwInfo.deviceIndex];
                    } else {
                        //Unknown, don't map
                        typeidx = hwInfo.deviceIndex;
                    }
                    wrap_amdsysfs_get_tempC(sysfsh, typeidx, &tempC);
                    wrap_amdsysfs_get_fanpcnt(sysfsh, typeidx, &fanpcnt);
                    if (power) {
                        wrap_amdsysfs_get_power_usage(sysfsh, typeidx, &powerW);
                    }
                }
#endif
            }
            i->update_temperature(tempC);

            hw.tempC = tempC;
            hw.fanP = fanpcnt;
            hw.powerW = powerW/((double)1000.0);
            p.minerMonitors[i->name()] = hw;
        }
    }

    for (auto const& cp : m_lastProgresses) {
        p.ms += cp.ms;
        p.hashes += cp.hashes;
        for (auto const & i : cp.minersHashes) {
            p.minersHashes.at(i.first) += i.second;
        }
    }
    m_progress = p;
    return m_progress;
}

void MinePlant::setTStartTStop(unsigned tstart, unsigned tstop)
{
    m_tstart = tstart;
    m_tstop = tstop;
}

void MinePlant::processHashRate(const boost::system::error_code& ec)
{
    if (!ec) {
        if (!isMining()) {
            return;
        }
        collectHashRate();
        // Restart timer
        m_hashrateTimer.expires_from_now(boost::posix_time::milliseconds(1000));
        m_hashrateTimer.async_wait(m_io_strand.wrap(boost::bind(&MinePlant::processHashRate, this, boost::asio::placeholders::error)));
    }
}

void MinePlant::restart()
{
    if (m_onMinerRestart) {
        m_onMinerRestart();
    }
}

bool MinePlant::isMining() const
{
    return m_isMining;
}

uint64_t MinePlant::get_start_nonce(const Work& work, unsigned idx) const
{
    static uint64_t range = std::numeric_limits<uint64_t>::max() / m_miners.size();
    return work.startNonce + range * idx;
}

uint64_t MinePlant::get_nonce_scumbler() const
{
    return m_nonceScumbler;
}

SolutionStats MinePlant::getSolutionStats()
{
    return m_solutionStats;
}

void MinePlant::failedSolution()
{
    m_solutionStats.failed();
}

void MinePlant::acceptedSolution(bool _stale)
{
    if (!_stale) {
        m_solutionStats.accepted();
    } else {
        m_solutionStats.acceptedStale();
    }
}

void MinePlant::rejectedSolution()
{
    m_solutionStats.rejected();
}

const Work& MinePlant::getWork() const
{
    std::lock_guard<std::mutex> lock(x_minerWork);
    return m_work;
}

std::chrono::steady_clock::time_point MinePlant::farmLaunched()
{
    return m_farm_launched;
}

std::string MinePlant::farmLaunchedFormatted() const
{
    auto d = std::chrono::steady_clock::now() - m_farm_launched;
    int hsize = 3;
    auto hhh = std::chrono::duration_cast<std::chrono::hours>(d);
    if (hhh.count() < 100) {
        hsize = 2;
    }
    d -= hhh;
    auto mm = std::chrono::duration_cast<std::chrono::minutes>(d);
    std::ostringstream stream;
    stream << "Time: " << std::setfill('0') << std::setw(hsize) << hhh.count() << ':' << std::setfill('0') << std::setw(2) << mm.count();
    return stream.str();
	}

void MinePlant::set_pool_addresses(const std::string& host, unsigned port)
{
    std::stringstream ssPoolAddresses;
    ssPoolAddresses << host << ':' << port;
    m_pool_addresses = ssPoolAddresses.str();
}

const std::string& MinePlant::get_pool_addresses() const
{
    return m_pool_addresses;
}

max_stars_repo_name: levongh/energiminer

max_issues_repo_name: levongh/energiminer

max_forks_repo_name: levongh/energiminer


text: #include <boost/spirit/home/classic/actor/increment_actor.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
// Copyright 2016 by Glukhov V. O. All Rights Reserved.
//
// 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 "image_loader.hpp"
#include <armadillo>
#include <memory>
namespace cnn
{
	namespace nn
	{
		class InputLayer
		{
		public:
			InputLayer(std::unique_ptr<BaseImageLoader> loader);

			bool LoadTestImage();
			bool LoadTrainImage();

			void SetCustomImage(std::shared_ptr<arma::Cube<double>> image);

			bool is_empty() const noexcept;
			std::shared_ptr<arma::Cube<double>> Output() const noexcept;
			const arma::Col<double>& Labels() const noexcept;

			const std::wstring& LabelName(std::size_t id) const;

		private:
			arma::Col<double> labels_;
			std::shared_ptr<arma::Cube<double>> output_;
			std::unique_ptr<BaseImageLoader> loader_;
		};

		inline
		InputLayer::InputLayer(std::unique_ptr<BaseImageLoader> loader)
			: loader_(std::move(loader)) {}

		inline bool InputLayer::LoadTestImage()
		{
			return loader_->LoadTestImage(output_, labels_);
		}

		inline bool InputLayer::LoadTrainImage()
		{
			return loader_->LoadTrainImage(output_, labels_);
		}

		inline void
		InputLayer::SetCustomImage(std::shared_ptr<arma::Cube<double>> image)
		{
			output_ = image;
			labels_.reset();
		}

		inline bool InputLayer::is_empty() const noexcept
		{
#ifndef NDEBUG
			assert(output_);
#endif
			return output_->is_empty();
		}

		inline std::shared_ptr<arma::Cube<double>> InputLayer::Output() const noexcept
		{
			return output_;
		}

		inline const arma::Col<double>& InputLayer::Labels() const noexcept
		{
			return labels_;
		}

		inline const std::wstring& InputLayer::LabelName(std::size_t id) const
		{
			return loader_->LabelName(id);
		}
	}
}

max_stars_repo_name: Matumba/CNN-Library

max_issues_repo_name: Matumba/CNN-Library

max_forks_repo_name: Matumba/CNN-Library


text:
//----------------------------------------------------------------------------
/// @file spin_sort.hpp
/// @brief Spin Sort algorithm
///
/// @author Copyright (c) 2016 Francisco José Tapia (fjtapia@gmail.com )\n
///         Distributed under the Boost Software License, Version 1.0.\n
///         ( See accompanying file LICENSE_1_0.txt or copy at
///           http://www.boost.org/LICENSE_1_0.txt  )
/// @version 0.1
///
/// @remarks
//-----------------------------------------------------------------------------
#ifndef __BOOST_SORT_PARALLEL_ALGORITHM_SPIN_SORT_HPP
#define __BOOST_SORT_PARALLEL_ALGORITHM_SPIN_SORT_HPP

#include <boost/sort/parallel/detail/indirect.hpp>
#include <boost/sort/parallel/detail/insertion_sort.hpp>
#include <boost/sort/parallel/detail/util/compare_traits.hpp>
#include <boost/sort/parallel/detail/util/nbits.hpp>
#include <boost/sort/parallel/detail/util/range.hpp>
#include <cstdlib>
#include <functional>
#include <iterator>
#include <memory>
#include <type_traits>
#include <vector>

namespace boost
{
namespace sort
{
namespace parallel
{
namespace detail
{
//
//----------------------------------------------------------------------------
//                USING SENTENCES
//----------------------------------------------------------------------------
using util::range;
using util::nbits64;
using std::iterator_traits;

//-----------------------------------------------------------------------------
//  function : range_sort
/// @brief this function divide r_input in two parts, sort it,and merge moving
///        the elements to range_buf
/// @param range_input : range with the elements to sort
/// @param range_buffer : range with the elements sorted
/// @param comp : object for to compare two elements
/// @param level : when is 1, sort with the insertion_sort algorithm
///                if not make a recursive call splitting the ranges
//-----------------------------------------------------------------------------
template < class Iter1_t, class Iter2_t, class Compare >
void range_sort (const range< Iter1_t > &range_input,
                 const range< Iter2_t > &range_buffer, Compare comp,
                 uint32_t level)
{
    typedef range< Iter1_t > range_it1;
    typedef range< Iter2_t > range_it2;
    assert (range_input.size ( ) == range_buffer.size ( ) and level != 0);

    size_t nelem1 = (range_input.size ( ) + 1) >> 1;
    range_it1 range_input1 (range_input.first, range_input.first + nelem1),
        range_input2 (range_input.first + nelem1, range_input.last);

    if (level < 2) {
        insertion_sort (range_input1.first, range_input1.last, comp);
        insertion_sort (range_input2.first, range_input2.last, comp);
    }
    else
    {
        range_sort (range_it2 (range_buffer.first, range_buffer.first + nelem1),
                    range_input1, comp, level - 1);

        range_sort (range_it2 (range_buffer.first + nelem1, range_buffer.last),
                    range_input2, comp, level - 1);
    };

    full_merge (range_buffer, range_input1, range_input2, comp);
};

//---------------------------------------------------------------------------
/// @struct spin_sort
/// @brief  This class implement s stable sort algorithm with 1 thread, with
///         an auxiliary memory of N/2 elements
//----------------------------------------------------------------------------
template < class Iter_t, typename Compare = util::compare_iter< Iter_t > >
class spin_sort
{
    //------------------------------------------------------------------------
    //               DEFINITIONS AND CONSTANTS
    //------------------------------------------------------------------------
    typedef typename iterator_traits< Iter_t >::value_type value_t;
    typedef range< Iter_t > range_it;
    typedef range< value_t * > range_buf;
    // When the number of elements to sort is smaller than Sort_min, are sorted
    // by the insertion sort algorithm
    static const uint32_t Sort_min = 36;

    //------------------------------------------------------------------------
    //                      VARIABLES
    //------------------------------------------------------------------------
    // Pointer to the auxiliary memory
    value_t *ptr;

    // Number of elements in the auxiliary memory
    size_t nptr;

    // construct indicate if the auxiliary memory in initialized, and owner
    // indicate if the auxiliary memory had been created inside the object or
    // had
    // been received as a parameter
    bool construct = false, owner = false;

    //------------------------------------------------------------------------
    //                   PRIVATE FUNCTIONS
    //-------------------------------------------------------------------------
    spin_sort (Iter_t first, Iter_t last, Compare comp, value_t *paux,
               size_t naux);

public:
    //------------------------------------------------------------------------
    //                   PUBLIC FUNCTIONS
    //-------------------------------------------------------------------------
    spin_sort (Iter_t first, Iter_t last, Compare comp = Compare ( ))
        : spin_sort (first, last, comp, nullptr, 0){};

    spin_sort (Iter_t first, Iter_t last, Compare comp, range_buf range_aux)
        : spin_sort (first, last, comp, range_aux.first, range_aux.size ( )){};
    //
    //-----------------------------------------------------------------------
    //  function :~spin_sort
    /// @brief destructor of the struct. Destroy the elements if construct is
    /// true,
    ///        and return the memory if owner is true
    //-----------------------------------------------------------------------
    ~spin_sort (void)
    {
        if (construct) {
            destroy (range< value_t * > (ptr, ptr + nptr));
            construct = false;
        };
        if (owner and ptr != nullptr) std::return_temporary_buffer (ptr);
    };
}; //        End of class spin_sort
//
//############################################################################
//                                                                          ##
//              N O N    I N L I N E      F U N C T I O N S                 ##
//                                                                          ##
//                                                                          ##
//############################################################################
//
//-----------------------------------------------------------------------------
//  function : spin_sort
/// @brief constructor of the struct
//
/// @param first : iterator to the first element of the range to sort
/// @param last : iterator after the last element to the range to sort
/// @param comp : object for to compare two elements pointed by Iter_t
///               iterators
/// @param paux : pointer to the auxiliary memory provided. If nullptr, the
///               memory is created inside the class
/// @param naux : number of elements pointed by paux
//-----------------------------------------------------------------------------
template < class Iter_t, class Compare >
spin_sort< Iter_t, Compare >
  ::spin_sort (Iter_t first, Iter_t last, Compare comp, value_t *paux,
               size_t naux)
    : ptr (paux), nptr (naux), construct (false), owner (false)
{
    range< Iter_t > range_input (first, last);
    assert (range_input.valid ( ));

    size_t nelem = range_input.size ( );
    owner = construct = false;

    nptr = (nelem + 1) >> 1;
    size_t nelem_1 = nptr;
    size_t nelem_2 = nelem - nelem_1;

    if (nelem <= (Sort_min << 1)) {
        insertion_sort (range_input.first, range_input.last, comp);
        return;
    };
    //------------------- check if sort --------------------------------------
    bool sw = true;
    for (Iter_t it1 = range_input.first, it2 = range_input.first + 1;
         it2 != range_input.last and (sw = not comp (*it2, *it1)); it1 = it2++)
        ;
    if (sw) return;

    if (ptr == nullptr) {
        ptr = std::get_temporary_buffer< value_t > (nptr).first;
        if (ptr == nullptr) throw std::bad_alloc ( );
        owner = true;
    };
    range_buf range_aux (ptr, (ptr + nptr));

    //------------------------------------------------------------------------
    //                  Process
    //------------------------------------------------------------------------
    uint32_t nlevel = nbits64 (((nelem + Sort_min - 1) / Sort_min) - 1) - 1;
    assert (nlevel != 0);

    if ((nlevel & 1) == 1) {
        //---------------------------------------------------------------------
        // if the number of levels is odd, the data are in the first parameter
        // of range_sort, and the results appear in the second parameter
        //---------------------------------------------------------------------
        range_it range_1 (first, first + nelem_2),
            range_2 (first + nelem_2, last);
        range_aux = uninit_move (range_aux, range_2);
        construct = true;

        range_sort (range_aux, range_2, comp, nlevel);
        range_buf rng_bx (range_aux.first, range_aux.first + nelem_2);

        range_sort (range_1, rng_bx, comp, nlevel);
        half_merge (range_input, rng_bx, range_2, comp);
    }
    else
    {
        //--------------------------------------------------------------------
        // If the number of levels is even, the data are in the second
        // parameter of range_sort, and the results are in the same parameter
        //---------------------------------------------------------------------
        range_it range_1 (first, first + nelem_1),
            range_2 (first + nelem_1, last);
        range_aux = uninit_move (range_aux, range_1);
        construct = true;

        range_sort (range_1, range_aux, comp, nlevel);

        range_1.last = range_1.first + range_2.size ( );
        range_sort (range_1, range_2, comp, nlevel);
        half_merge (range_input, range_aux, range_2, comp);
    };
};

//****************************************************************************
}; //    End namespace algorithm
}; //    End namespace parallel
}; //    End namespace sort
}; //    End namepspace boost
//****************************************************************************
//
#endif

max_stars_repo_name: mrzv/ripser

max_issues_repo_name: mrzv/ripser

max_forks_repo_name: mrzv/ripser


text:
// Small bench routine for Eigen available in Eigen
// (C) Desire NUENTSA WAKAM, INRIA

#include <unsupported/Eigen/SparseExtra>
#include <Eigen/SparseLU>
#include <bench/BenchTimer.h>
#ifdef EIGEN_METIS_SUPPORT
#include <Eigen/MetisSupport>
#endif

using namespace std;
using namespace Eigen;

int main(int argc, char **args)
{
//   typedef complex<double> scalar;
  typedef double scalar;
  SparseMatrix<scalar, ColMajor> A;
  typedef SparseMatrix<scalar, ColMajor>::Index Index;
  typedef Matrix<scalar, Dynamic, Dynamic> DenseMatrix;
  typedef Matrix<scalar, Dynamic, 1> DenseRhs;
  Matrix<scalar, Dynamic, 1> b, x, tmp;
//   SparseLU<SparseMatrix<scalar, ColMajor>, AMDOrdering<int> >   solver;
// #ifdef EIGEN_METIS_SUPPORT
//   SparseLU<SparseMatrix<scalar, ColMajor>, MetisOrdering<int> > solver;
//   std::cout<< "ORDERING : METIS\n";
// #else
  SparseLU<SparseMatrix<scalar, ColMajor>, COLAMDOrdering<int> >  solver;
  std::cout<< "ORDERING : COLAMD\n";
// #endif

  ifstream matrix_file;
  string line;
  int  n;
  BenchTimer timer;

  // Set parameters
  /* Fill the matrix with sparse matrix stored in Matrix-Market coordinate column-oriented format */
  if (argc < 2) assert(false && "please, give the matrix market file ");
  loadMarket(A, args[1]);
  cout << "End charging matrix " << endl;
  bool iscomplex=false, isvector=false;
  int sym;
  getMarketHeader(args[1], sym, iscomplex, isvector);
//   if (iscomplex) { cout<< " Not for complex matrices \n"; return -1; }
  if (isvector) { cout << "The provided file is not a matrix file\n"; return -1;}
  if (sym != 0) { // symmetric matrices, only the lower part is stored
    SparseMatrix<scalar, ColMajor> temp;
    temp = A;
    A = temp.selfadjointView<Lower>();
  }
  n = A.cols();
  /* Fill the right hand side */

  if (argc > 2)
    loadMarketVector(b, args[2]);
  else
  {
    b.resize(n);
    tmp.resize(n);
//       tmp.setRandom();
    for (int i = 0; i < n; i++) tmp(i) = i;
    b = A * tmp ;
  }

  /* Compute the factorization */
//   solver.isSymmetric(true);
  timer.start();
//   solver.compute(A);
  solver.analyzePattern(A);
  timer.stop();
  cout << "Time to analyze " << timer.value() << std::endl;
  timer.reset();
  timer.start();
  solver.factorize(A);
  timer.stop();
  cout << "Factorize Time " << timer.value() << std::endl;
  timer.reset();
  timer.start();
  x = solver.solve(b);
  timer.stop();
  cout << "solve time " << timer.value() << std::endl;
  /* Check the accuracy */
  Matrix<scalar, Dynamic, 1> tmp2 = b - A*x;
  scalar tempNorm = tmp2.norm()/b.norm();
  cout << "Relative norm of the computed solution : " << tempNorm <<"\n";
  cout << "Number of nonzeros in the factor : " << solver.nnzL() + solver.nnzU() << std::endl;

  return 0;
}

max_stars_repo_name: RokKos/eol-cloth

max_issues_repo_name: RokKos/eol-cloth

max_forks_repo_name: RokKos/eol-cloth


text:
/* test_poisson_distribution.cpp
 *
 * Copyright Steven Watanabe 2010
 * 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)
 *
 * $Id$
 *
 */

#include <boost/random/poisson_distribution.hpp>

#include <limits>

#define BOOST_RANDOM_DISTRIBUTION boost::random::poisson_distribution<>
#define BOOST_RANDOM_ARG1 mean
#define BOOST_RANDOM_ARG1_DEFAULT 1.0
#define BOOST_RANDOM_ARG1_VALUE 7.5

#define BOOST_RANDOM_DIST0_MIN 0
#define BOOST_RANDOM_DIST0_MAX (std::numeric_limits<int>::max)()
#define BOOST_RANDOM_DIST1_MIN 0
#define BOOST_RANDOM_DIST1_MAX (std::numeric_limits<int>::max)()

#define BOOST_RANDOM_TEST1_PARAMS
#define BOOST_RANDOM_TEST1_MIN 0.0
#define BOOST_RANDOM_TEST1_MAX 10.0

#define BOOST_RANDOM_TEST2_PARAMS (1000.0)
#define BOOST_RANDOM_TEST2_MIN 10.0

#include "test_distribution.ipp"