text:
/*
// Copyright (c) 2019 Intel Corporation
//
// 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.
*/

#include <boost/algorithm/string/join.hpp>
#include <me_to_redfish_hooks.hpp>
#include <phosphor-logging/log.hpp>

#include <string_view>

namespace intel_oem::ipmi::sel::redfish_hooks::me
{
namespace health_event
{
namespace smbus_failure
{

static bool messageHook(const SELData& selData, std::string& eventId,
                        std::vector<std::string>& args)
{
    static const boost::container::flat_map<uint8_t, std::string> smlink = {
        {0x01, "SmLink0/0B"},
        {0x02, "SmLink1"},
        {0x03, "SmLink2"},
        {0x04, "SmLink3"},
        {0x05, "SmLink4"}};

    const auto errorDetails = selData.eventData3;
    const auto faultySmlink = smlink.find(selData.eventData2);
    if (faultySmlink == smlink.end())
    {
        return false;
    }

    eventId = "MESmbusLinkFailure";

    args.push_back(faultySmlink->second);
    args.push_back(utils::toHex(errorDetails));

    return true;
}
} // namespace smbus_failure

namespace fw_status
{
static const boost::container::flat_map<uint8_t, std::string>
    manufacturingError = {
        {0x00, "Generic error"},
        {0x01, "Wrong or missing VSCC table"},
        {0x02, "Wrong sensor scanning period in PIA"},
        {0x03, "Wrong device definition in PIA"},
        {0x04, "Reserved (Wrong SMART/CLST configuration)"},
        {0x05, "Intel ME FW configuration is inconsistent or out of range"},
        {0x06, "Reserved"},
        {0x07, "Intel ME FW configuration is corrupted"},
        {0x08, "SMLink0/0B misconfiguration"}};

static const boost::container::flat_map<uint8_t, std::string> peciOverDmiError =
    {{0x01, "DRAM Init Done HECI message not received by Intel ME before EOP"},
     {0x02, "System PCIe bus configuration not known or not valid on DID HECI "
            "message arrival to Intel ME"},
     {0x03, "PECI over DMI run-time failure"}};

static const boost::container::flat_map<uint8_t, std::string>
    mctpInterfaceError = {
        {0x01, "No DID HECI message received before EOP"},
        {0x02, "No MCTP_SET_BUS_OWNER HECI message received by Intel ME on EOP "
               "arrival "
               "to ME while MCTP stack is configured in Bus Owner Proxy mode"}};

static const boost::container::flat_map<uint8_t, std::string>
    unsupportedFeature = {{0x00, "Other Segment Defined Feature"},
                          {0x01, "Fast NM limiting"},
                          {0x02, "Volumetric Airflow and Outlet Temperature"},
                          {0x03, "CUPS"},
                          {0x04, "Thermal policies and Inlet Temperature"},
                          {0x05, "Platform limiting with MICs"},
                          {0x07, "Shared power supplies"},
                          {0x08, "MIC Proxy"},
                          {0x09, "Reset warning"},
                          {0x0A, "PMBus Proxy"},
                          {0x0B, "Always on"},
                          {0x0C, "IPMI Intel ME FW update"},
                          {0x0D, "MCTP bus owner"},
                          {0x0E, "MCTP bus owner proxy"},
                          {0x0F, "Dual BIOS"},
                          {0x10, "Battery less"}};

static const boost::container::flat_map<uint8_t, std::string> umaError = {
    {0x00, "UMA Read integrity error. Checksum of data read from UMA differs "
           "from expected one."},
    {0x01, "UMA Read/Write timeout. Timeout occurred during copying data "
           "from/to UMA."},
    {0x02,
     "UMA not granted. BIOS did not grant any UMA or DRAM INIT done message "
     "was not received from BIOS before EOP. Intel ME FW goes to recovery."},
    {0x03, "UMA size granted by BIOS differs from requested. ME FW goes to "
           "recovery."}};

static const boost::container::flat_map<uint8_t, std::string> pttHealthEvent = {
    {0x00, "Intel PTT disabled (PTT region is not present)."},
    {0x01, "Intel PTT downgrade (PTT data should be not available)."},
    {0x02, "Intel PTT disabled (battery less configuration)."}};

static const boost::container::flat_map<uint8_t, std::string>
    bootGuardHealthEvent = {
        {0x00, "Boot Guard flow error (possible reasons: verification timeout; "
               "verification error; BIOS Protection error)."}};

static const boost::container::flat_map<uint8_t, std::string> restrictedMode = {
    {0x01, "Firmware entered restricted mode – UMA is not available. "
           "Restricted features set."},
    {0x02, "Firmware exited restricted mode."}};

static const boost::container::flat_map<uint8_t, std::string>
    multiPchModeMisconfig = {
        {0x01, "BIOS did not set reset synchronization in multiPCH mode"},
        {0x02,
         "PMC indicates different non/legacy mode for the PCH than BMC set "
         "on the GPIO"},
        {0x03,
         "Misconfiguration MPCH support enabled due to BTG support enabled"}};

static const boost::container::flat_map<uint8_t, std::string>
    flashVerificationError = {
        {0x00, "OEM Public Key verification error"},
        {0x01, "Flash Descriptor Region Manifest verification error"},
        {0x02, "Soft Straps verification error"}};

namespace autoconfiguration
{

bool messageHook(const SELData& selData, std::string& eventId,
                 std::vector<std::string>& args)
{
    static const boost::container::flat_map<uint8_t, std::string> dcSource = {
        {0b00, "BMC"}, {0b01, "PSU"}, {0b10, "On-board power sensor"}};

    static const boost::container::flat_map<uint8_t, std::string>
        chassisSource = {{0b00, "BMC"},
                         {0b01, "PSU"},
                         {0b10, "On-board power sensor"},
                         {0b11, "Not supported"}};

    static const boost::container::flat_map<uint8_t, std::string>
        efficiencySource = {
            {0b00, "BMC"}, {0b01, "PSU"}, {0b11, "Not supported"}};

    static const boost::container::flat_map<uint8_t, std::string>
        unmanagedSource = {{0b00, "BMC"}, {0b01, "Estimated"}};

    static const boost::container::flat_map<uint8_t, std::string>
        failureReason = {{0b00, "BMC discovery failure"},
                         {0b01, "Insufficient factory configuration"},
                         {0b10, "Unknown sensor type"},
                         {0b11, "Other error encountered"}};

    auto succeeded = selData.eventData3 >> 7 & 0b1;
    if (succeeded)
    {
        eventId = "MEAutoConfigSuccess";

        auto dc = dcSource.find(selData.eventData3 >> 5 & 0b11);
        auto chassis = chassisSource.find(selData.eventData3 >> 3 & 0b11);
        auto efficiency = efficiencySource.find(selData.eventData3 >> 1 & 0b11);
        auto unmanaged = unmanagedSource.find(selData.eventData3 & 0b1);
        if (dc == dcSource.end() || chassis == chassisSource.end() ||
            efficiency == efficiencySource.end() ||
            unmanaged == unmanagedSource.end())
        {
            return false;
        }

        args.push_back(dc->second);
        args.push_back(chassis->second);
        args.push_back(efficiency->second);
        args.push_back(unmanaged->second);
    }
    else
    {
        eventId = "MEAutoConfigFailed";

        const auto it = failureReason.find(selData.eventData3 >> 5 & 0b11);
        if (it == failureReason.end())
        {
            return false;
        }

        args.push_back(it->second);
    }

    return true;
}
} // namespace autoconfiguration

namespace factory_reset
{
bool messageHook(const SELData& selData, std::string& eventId,
                 std::vector<std::string>& args)
{
    static const boost::container::flat_map<uint8_t, std::string>
        restoreToFactoryPreset = {
            {0x00,
             "Flash file system error detected. Automatic restore to factory "
             "presets has been triggered."},
            {0x01, "Automatic restore to factory presets has been completed."},
            {0x02, "Restore to factory presets triggered by Force ME Recovery "
                   "IPMI command has been completed."},
            {0x03,
             "Restore to factory presets triggered by AC power cycle with "
             "Recovery jumper asserted has been completed."}};

    auto param = restoreToFactoryPreset.find(selData.eventData3);
    if (param == restoreToFactoryPreset.end())
    {
        return false;
    }

    if (selData.eventData3 == 0x00)
    {
        eventId = "MEFactoryResetError";
    }
    else
    {
        eventId = "MEFactoryRestore";
    }

    args.push_back(param->second);
    return true;
}
} // namespace factory_reset

namespace flash_state
{
bool messageHook(const SELData& selData, std::string& eventId,
                 std::vector<std::string>& args)
{
    static const boost::container::flat_map<uint8_t, std::string>
        flashStateInformation = {
            {0x00,
             "Flash partition table, recovery image or factory presets image "
             "corrupted"},
            {0x01, "Flash erase limit has been reached"},
            {0x02,
             "Flash write limit has been reached. Writing to flash has been "
             "disabled"},
            {0x03, "Writing to the flash has been enabled"}};

    auto param = flashStateInformation.find(selData.eventData3);
    if (param == flashStateInformation.end())
    {
        return false;
    }

    if (selData.eventData3 == 0x03)
    {
        eventId = "MEFlashStateInformationWritingEnabled";
    }
    else
    {
        eventId = "MEFlashStateInformation";
    }

    args.push_back(param->second);
    return true;
}
} // namespace flash_state

static bool messageHook(const SELData& selData, std::string& eventId,
                        std::vector<std::string>& args)
{
    static const boost::container::flat_map<
        uint8_t,
        std::pair<std::string, std::optional<std::variant<utils::ParserFunc,
                                                          utils::MessageMap>>>>
        eventMap = {
            {0x00, {"MERecoveryGpioForced", {}}},
            {0x01, {"MEImageExecutionFailed", {}}},
            {0x02, {"MEFlashEraseError", {}}},
            {0x03, {{}, flash_state::messageHook}},
            {0x04, {"MEInternalError", {}}},
            {0x05, {"MEExceptionDuringShutdown", {}}},
            {0x06, {"MEDirectFlashUpdateRequested", {}}},
            {0x07, {"MEManufacturingError", manufacturingError}},
            {0x08, {{}, factory_reset::messageHook}},
            {0x09, {"MEFirmwareException", utils::logByteHex<2>}},
            {0x0A, {"MEFlashWearOutWarning", utils::logByteDec<2>}},
            {0x0D, {"MEPeciOverDmiError", peciOverDmiError}},
            {0x0E, {"MEMctpInterfaceError", mctpInterfaceError}},
            {0x0F, {{}, autoconfiguration::messageHook}},
            {0x10, {"MEUnsupportedFeature", unsupportedFeature}},
            {0x12, {"MECpuDebugCapabilityDisabled", {}}},
            {0x13, {"MEUmaError", umaError}},
            {0x16, {"MEPttHealthEvent", pttHealthEvent}},
            {0x17, {"MEBootGuardHealthEvent", bootGuardHealthEvent}},
            {0x18, {"MERestrictedMode", restrictedMode}},
            {0x19, {"MEMultiPchModeMisconfig", multiPchModeMisconfig}},
            {0x1A, {"MEFlashVerificationError", flashVerificationError}}};

    return utils::genericMessageHook(eventMap, selData, eventId, args);
}
} // namespace fw_status

static bool messageHook(const SELData& selData, std::string& eventId,
                        std::vector<std::string>& args)
{
    const HealthEventType healthEventType =
        static_cast<HealthEventType>(selData.offset);

    switch (healthEventType)
    {
        case HealthEventType::FirmwareStatus:
            return fw_status::messageHook(selData, eventId, args);
            break;

        case HealthEventType::SmbusLinkFailure:
            return smbus_failure::messageHook(selData, eventId, args);
            break;
    }

    return false;
}
} // namespace health_event

/**
 * @brief Main entry point for parsing ME IPMI Platform Events
 *
 * @brief selData - IPMI Platform Event structure
 * @brief ipmiRaw - the same event in raw binary form
 *
 * @returns true if event was successfully parsed and consumed
 */
bool messageHook(const SELData& selData, const std::string& ipmiRaw)
{
    const EventSensor meSensor = static_cast<EventSensor>(selData.sensorNum);
    std::string eventId;
    std::vector<std::string> args;

    switch (meSensor)
    {
        case EventSensor::MeFirmwareHealth:
            if (health_event::messageHook(selData, eventId, args))
            {
                utils::storeRedfishEvent(ipmiRaw, eventId, args);
                return true;
            }
            break;
    }

    return defaultMessageHook(ipmiRaw);
}
} // namespace intel_oem::ipmi::sel::redfish_hooks::me

max_stars_repo_name: Eyerunmyden/HWMgmt-MegaRAC-OpenEdition

max_issues_repo_name: Eyerunmyden/HWMgmt-MegaRAC-OpenEdition

max_forks_repo_name: Eyerunmyden/HWMgmt-MegaRAC-OpenEdition


text:
//  Copyright Neil Groves 2009. Use, modification and
//  distribution is subject to the Boost Software License, Version
//  1.0. (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//
//
// For more information, see http://www.boost.org/libs/range/
//
#ifndef BOOST_RANGE_ALGORITHM_ROTATE_COPY_HPP_INCLUDED
#define BOOST_RANGE_ALGORITHM_ROTATE_COPY_HPP_INCLUDED

#include <boost/concept_check.hpp>
#include <boost/range/begin.hpp>
#include <boost/range/end.hpp>
#include <boost/range/concepts.hpp>
#include <boost/range/iterator.hpp>
#include <algorithm>

namespace boost
{
    namespace range
    {

    /// \brief template function rotate
    ///
    /// range-based version of the rotate std algorithm
    ///
    /// \pre Rng meets the requirements for a Forward range
    template<typename ForwardRange, typename OutputIterator>
    inline OutputIterator rotate_copy(
        const ForwardRange&                                 rng,
        typename range_iterator<const ForwardRange>::type   middle,
        OutputIterator                                      target
        )
    {
        BOOST_RANGE_CONCEPT_ASSERT(( ForwardRangeConcept<const ForwardRange> ));
        return std::rotate_copy(boost::begin(rng), middle, boost::end(rng), target);
    }

    } // namespace range
    using range::rotate_copy;
} // namespace boost

#endif // include guard

ext: hpp

max_stars_repo_name: jonstewart/boost-svn

max_issues_repo_name: jonstewart/boost-svn

max_forks_repo_name: jonstewart/boost-svn


text:
#include <fc/crypto/elliptic.hpp>
#include <bts/utilities/key_conversion.hpp>
#include <fc/io/json.hpp>
#include <fc/exception/exception.hpp>
#include <fc/io/raw_variant.hpp>
#include <fc/network/ip.hpp>
#include <fc/network/resolve.hpp>
#include <fstream>
#include <iostream>
#include <queue>

#include <bts/blockchain/chain_database.hpp>
#include <bts/net/peer_connection.hpp>
#include <bts/client/client.hpp>

#include <boost/program_options/options_description.hpp>

#define PARAM_GENESIS   "genesis"
#define PARAM_PORT      "port"
#define PARAM_SEEDER    "seeder"

class peer_probe : public bts::net::peer_connection_delegate
{
public:
  bool _peer_closed_connection;
  bool _we_closed_connection;
  bts::net::peer_connection_ptr _connection;
  std::vector<bts::net::address_info> _peers;
  fc::ecc::public_key _node_id;
  bool _connection_was_rejected;
  bool _done;
  fc::promise<void>::ptr _probe_complete_promise;

public:
  peer_probe() :
    _peer_closed_connection(false),
    _we_closed_connection(false),
    _connection(bts::net::peer_connection::make_shared(this)),
    _connection_was_rejected(false),
    _done(false),
    _probe_complete_promise(fc::promise<void>::ptr(new fc::promise<void>("probe_complete")))
  {}

  void start(const fc::ip::endpoint& endpoint_to_probe,
             const fc::ecc::private_key& my_node_id,
             const bts::blockchain::digest_type& chain_id)
  {
    fc::future<void> connect_task = fc::async([=](){ _connection->connect_to(endpoint_to_probe); }, "connect_task");
    try
    {
      connect_task.wait(fc::seconds(10));
    }
    catch (const fc::timeout_exception&)
    {
      ilog("timeout connecting to node ${endpoint}", ("endpoint", endpoint_to_probe));
      connect_task.cancel(__FUNCTION__);
      throw;
    }

    fc::sha256::encoder shared_secret_encoder;
    fc::sha512 shared_secret = _connection->get_shared_secret();
    shared_secret_encoder.write(shared_secret.data(), sizeof(shared_secret));
    fc::ecc::compact_signature signature = my_node_id.sign_compact(shared_secret_encoder.result());

    bts::net::hello_message hello("map_bts_network",
                                  BTS_NET_PROTOCOL_VERSION,
                                  fc::ip::address(), 0, 0,
                                  my_node_id.get_public_key(),
                                  signature,
                                  chain_id,
                                  fc::variant_object());

    _connection->send_message(hello);
  }

  void on_message(bts::net::peer_connection* originating_peer,
                  const bts::net::message& received_message) override
  {
    bts::net::message_hash_type message_hash = received_message.id();
    dlog( "handling message ${type} ${hash} size ${size} from peer ${endpoint}",
          ( "type", bts::net::core_message_type_enum(received_message.msg_type ) )("hash", message_hash )("size", received_message.size )("endpoint", originating_peer->get_remote_endpoint() ) );
    switch ( received_message.msg_type )
    {
    case bts::net::core_message_type_enum::hello_message_type:
      on_hello_message( originating_peer, received_message.as<bts::net::hello_message>() );
      break;
    case bts::net::core_message_type_enum::connection_accepted_message_type:
      on_connection_accepted_message( originating_peer, received_message.as<bts::net::connection_accepted_message>() );
      break;
    case bts::net::core_message_type_enum::connection_rejected_message_type:
      on_connection_rejected_message( originating_peer, received_message.as<bts::net::connection_rejected_message>() );
      break;
    case bts::net::core_message_type_enum::address_request_message_type:
      on_address_request_message( originating_peer, received_message.as<bts::net::address_request_message>() );
      break;
    case bts::net::core_message_type_enum::address_message_type:
      on_address_message( originating_peer, received_message.as<bts::net::address_message>() );
      break;
    case bts::net::core_message_type_enum::closing_connection_message_type:
      on_closing_connection_message( originating_peer, received_message.as<bts::net::closing_connection_message>() );
      break;
    case bts::net::core_message_type_enum::current_time_request_message_type:
      on_current_time_request_message( originating_peer, received_message.as<bts::net::current_time_request_message>() );
      break;
    case bts::net::core_message_type_enum::current_time_reply_message_type:
      on_current_time_reply_message( originating_peer, received_message.as<bts::net::current_time_reply_message>() );
      break;
    }
  }

  void on_hello_message(bts::net::peer_connection* originating_peer,
                        const bts::net::hello_message& hello_message_received)
  {
    _node_id = hello_message_received.node_public_key;
    if (hello_message_received.user_data.contains("node_id"))
      originating_peer->node_id = hello_message_received.user_data["node_id"].as<bts::net::node_id_t>();
    originating_peer->send_message(bts::net::connection_rejected_message());
  }

  void on_connection_accepted_message(bts::net::peer_connection* originating_peer,
                                      const bts::net::connection_accepted_message& connection_accepted_message_received)
  {
    _connection_was_rejected = false;
    originating_peer->send_message(bts::net::address_request_message());
  }

  void on_connection_rejected_message( bts::net::peer_connection* originating_peer,
                                       const bts::net::connection_rejected_message& connection_rejected_message_received )
  {
    _connection_was_rejected = true;
    originating_peer->send_message(bts::net::address_request_message());
  }

  void on_address_request_message(bts::net::peer_connection* originating_peer,
                                  const bts::net::address_request_message& address_request_message_received)
  {
    originating_peer->send_message(bts::net::address_message());
  }

  void on_address_message(bts::net::peer_connection* originating_peer,
                          const bts::net::address_message& address_message_received)
  {
    _peers = address_message_received.addresses;
    originating_peer->send_message(bts::net::closing_connection_message("Thanks for the info"));
    _we_closed_connection = true;
  }

  void on_closing_connection_message(bts::net::peer_connection* originating_peer,
                                     const bts::net::closing_connection_message& closing_connection_message_received)
  {
    if (_we_closed_connection)
      _connection->close_connection();
    else
      _peer_closed_connection = true;
  }

  void on_current_time_request_message(bts::net::peer_connection* originating_peer,
                                       const bts::net::current_time_request_message& current_time_request_message_received)
  {
  }

  void on_current_time_reply_message(bts::net::peer_connection* originating_peer,
                                     const bts::net::current_time_reply_message& current_time_reply_message_received)
  {
  }

  void on_connection_closed(bts::net::peer_connection* originating_peer) override
  {
    _done = true;
    _probe_complete_promise->set_value();
  }

  void wait()
  {
    _probe_complete_promise->wait();
  }
};

static boost::program_options::variables_map parse_command_line(int argc, char **argv) {
boost::program_options::options_description desc("Allowed options");

    desc.add_options()
    ("help", "Show usage information")
    (PARAM_GENESIS, boost::program_options::value<std::string>(),
            "Genesis file (JSON)")
    (PARAM_PORT, boost::program_options::value<uint16_t>(),
            "Default network port number")
    (PARAM_SEEDER, boost::program_options::value<std::vector<std::string>>(),
            "Seed node address or hostname");

    boost::program_options::positional_options_description p;
    p.add(PARAM_SEEDER, -1);

    boost::program_options::variables_map vm;
    boost::program_options::store(boost::program_options::command_line_parser(argc, argv)
                                        .options(desc).positional(p).run(), vm);
    boost::program_options::notify(vm);

    if (vm.count("help")) {
        std::cout << desc << std::endl;
        exit(0);
    }

    return vm;
}

static void validate_options(boost::program_options::variables_map &opts) {
  int error = 0;

  if (!opts.count(PARAM_GENESIS)) {
      std::cerr << "No genesis block specified!" << std::endl;
      error++;
  }
  if (!opts.count(PARAM_PORT)) {
      std::cerr << "No port number specified!" << std::endl;
      error++;
  }
  if (!opts.count(PARAM_SEEDER)) {
      std::cerr << "No seeder specified!" << std::endl;
      error++;
  }

  if (error) { exit(1); }
}

int main(int argc, char** argv)
{
  boost::program_options::variables_map opts = parse_command_line(argc, argv);

  validate_options(opts);

  std::queue<fc::ip::endpoint> nodes_to_visit;
  std::set<fc::ip::endpoint> nodes_to_visit_set;
  std::set<fc::ip::endpoint> nodes_already_visited;

  fc::path data_dir = fc::temp_directory_path() / "map_bts_network";
  fc::create_directories(data_dir);

  bts::client::config default_client_config;
  for (const std::string default_peer : default_client_config.default_peers) {
    auto pos = default_peer.find(':');
    uint16_t port = boost::lexical_cast<uint16_t>( default_peer.substr( pos+1, default_peer.size() ) );
    std::vector<fc::ip::endpoint> endpoints = fc::resolve(default_peer.substr(0, pos), port);
    for( auto endpoint = endpoints.begin(); endpoint != endpoints.end(); ++endpoint ) {
      nodes_to_visit.push(*endpoint);
    }
  }
  fc::ip::endpoint seed_node1 = nodes_to_visit.front();

  fc::ecc::private_key my_node_id = fc::ecc::private_key::generate();
  bts::blockchain::chain_database_ptr chain_db = std::make_shared<bts::blockchain::chain_database>();
  chain_db->open(data_dir / "chain", fc::optional<fc::path>(opts[PARAM_GENESIS].as<std::string>()));

  std::map<bts::net::node_id_t, bts::net::address_info> address_info_by_node_id;
  std::map<bts::net::node_id_t, std::vector<bts::net::address_info> > connections_by_node_id;
  //std::map<bts::net::node_id_t, fc::ip::endpoint> all_known_nodes;

  while (!nodes_to_visit.empty())
  {
    bts::net::address_info this_node_info;
    this_node_info.direction = bts::net::peer_connection_direction::outbound;
    this_node_info.firewalled = bts::net::firewalled_state::not_firewalled;

    this_node_info.remote_endpoint = nodes_to_visit.front();;
    nodes_to_visit.pop();
    nodes_to_visit_set.erase(this_node_info.remote_endpoint);
    nodes_already_visited.insert(this_node_info.remote_endpoint);

    peer_probe probe;
    try
    {
      probe.start(this_node_info.remote_endpoint,
                  my_node_id,
                  chain_db->chain_id());
      probe.wait();

      this_node_info.node_id = probe._node_id;

      connections_by_node_id[this_node_info.node_id] = probe._peers;
      if (address_info_by_node_id.find(probe._node_id) == address_info_by_node_id.end())
        address_info_by_node_id[probe._node_id] = this_node_info;

      for (const bts::net::address_info& info : probe._peers)
      {
        if (nodes_already_visited.find(info.remote_endpoint) == nodes_already_visited.end() &&
            info.firewalled == bts::net::firewalled_state::not_firewalled &&
            nodes_to_visit_set.find(info.remote_endpoint) == nodes_to_visit_set.end())
        {
          nodes_to_visit.push(info.remote_endpoint);
          nodes_to_visit_set.insert(info.remote_endpoint);
        }
        if (address_info_by_node_id.find(info.node_id) == address_info_by_node_id.end())
          address_info_by_node_id[info.node_id] = info;
      }
    }
    catch (const fc::exception&)
    {
    }
    std::cout << "Traversed " << nodes_already_visited.size() << " of " << (nodes_already_visited.size() + nodes_to_visit.size()) << " known nodes\n";
  }

  bts::net::node_id_t seed_node_id;
  std::set<bts::net::node_id_t> non_firewalled_nodes_set;
  for (const auto& address_info_for_node : address_info_by_node_id)
  {
    if (address_info_for_node.second.remote_endpoint == seed_node1)
      seed_node_id = address_info_for_node.first;
    if (address_info_for_node.second.firewalled == bts::net::firewalled_state::not_firewalled)
      non_firewalled_nodes_set.insert(address_info_for_node.first);
  }
  std::set<bts::net::node_id_t> seed_node_connections;
  for (const bts::net::address_info& info : connections_by_node_id[seed_node_id])
    seed_node_connections.insert(info.node_id);
  std::set<bts::net::node_id_t> seed_node_missing_connections;
  std::set_difference(non_firewalled_nodes_set.begin(), non_firewalled_nodes_set.end(),
                      seed_node_connections.begin(), seed_node_connections.end(),
                      std::inserter(seed_node_missing_connections, seed_node_missing_connections.end()));
  seed_node_missing_connections.erase(seed_node_id);

  std::ofstream dot_stream((data_dir / "network_graph.dot").string().c_str());
  std::map<bts::net::node_id_t, fc::ip::endpoint> all_known_nodes;

  dot_stream << "graph G {\n";
  dot_stream << "  // Total " << address_info_by_node_id.size() << " nodes, firewalled: " << (address_info_by_node_id.size() - non_firewalled_nodes_set.size())
                              << ", non-firewalled: " << non_firewalled_nodes_set.size() << "\n";
  dot_stream << "  // Seed node is " << (std::string)address_info_by_node_id[seed_node_id].remote_endpoint << " id: " << fc::variant(seed_node_id).as_string() << "\n";
  dot_stream << "  // Seed node is connected to " << connections_by_node_id[seed_node_id].size() << " nodes\n";
  dot_stream << "  // Seed node is missing connections to " << seed_node_missing_connections.size() << " non-firewalled nodes:\n";
  for (const bts::net::node_id_t& id : seed_node_missing_connections)
    dot_stream << "  //           " << (std::string)address_info_by_node_id[id].remote_endpoint << "\n";

  dot_stream << "  layout=\"circo\";\n";
  //for (const auto& node_and_connections : connections_by_node_id)
  //  all_known_nodes[node_and_connections.first] = address_info_by_node_id[node_and_connections.first].remote_endpoint;

  for (const auto& address_info_for_node : address_info_by_node_id)
  {
    dot_stream << "  \"" << fc::variant(address_info_for_node.first).as_string() << "\"[label=\"" << (std::string)address_info_for_node.second.remote_endpoint << "\"";
    if (address_info_for_node.second.firewalled != bts::net::firewalled_state::not_firewalled)
      dot_stream << ",shape=rectangle";
    dot_stream << "];\n";
  }
  for (auto& node_and_connections : connections_by_node_id)
    for (const bts::net::address_info& this_connection : node_and_connections.second)
      dot_stream << "  \"" << fc::variant(node_and_connections.first).as_string() << "\" -- \"" << fc::variant(this_connection.node_id).as_string() << "\";\n";

  dot_stream << "}\n";

#if 0
  for (auto& node_and_connections : connections_by_node_id)
  {
    out << "  " << (std::string)node_and_connections.first.node_id.data << "[label=\"" << (std::string)node_and_connections.first.remote_endpoint << "\"];\n";
    //node_and_connections.first.node_id
  }
#endif

  return 0;
}

ext: cpp

max_stars_repo_name: larkx/LarkX

max_issues_repo_name: larkx/LarkX

max_forks_repo_name: larkx/LarkX


text:
/*********************************************************************
 * Software License Agreement (BSD License)
 *
 *  Copyright (c) 2009, 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.
 *********************************************************************/
/*
 * Author: Sachin Chitta and Matthew Piccoli
 */

#include <boost/shared_ptr.hpp>

#include <pr2_mechanism_controllers/base_kinematics.h>
#include <kdl/tree.hpp>

using namespace controller;

bool Wheel::init(pr2_mechanism_model::RobotState *robot_state, ros::NodeHandle &node, std::string link_name)
{
  wheel_stuck_ = 0;
  direction_multiplier_ = 1;
  wheel_speed_filtered_ = 0;
  wheel_speed_error_ = 0;
  wheel_speed_cmd_ = 0;
  wheel_speed_actual_ = 0;

#if URDFDOM_1_0_0_API
  urdf::LinkConstSharedPtr link;
#else
  boost::shared_ptr<const urdf::Link> link;
#endif
  link = robot_state->model_->robot_model_.getLink(link_name);
  if (!link){
    ROS_ERROR("Could not find link with name %s",link_name.c_str());
    return false;
  }

  if(!link->collision)
  {
    ROS_ERROR("Link %s does not have collision description. Add collision description for link to urdf.",link_name.c_str());
    return false;
  }
  if(!link->collision->geometry)
  {
    ROS_ERROR("Link %s does not have collision geometry description. Add collision geometry description for link to urdf.",link_name.c_str());
    return false;
  }
  if(link->collision->geometry->type != urdf::Geometry::CYLINDER)
  {
    ROS_ERROR("Link %s does not have cylinder geometry",link_name.c_str());
    return false;
  }
  wheel_radius_ = (dynamic_cast<urdf::Cylinder*>(link->collision->geometry.get()))->radius;
  ROS_DEBUG("wheel name: %s, radius: %f",link_name.c_str(),wheel_radius_);
  link_name_ = link_name;
  joint_name_ = link->parent_joint->name;

  joint_ = robot_state->getJointState(joint_name_);
  if (!joint_){
    ROS_ERROR("Could not find joint with name %s",joint_name_.c_str());
    return false;
  }

  urdf::Vector3 offset = link->parent_joint->parent_to_joint_origin_transform.position;
  offset_.x = offset.x;
  offset_.y = offset.y;
  offset_.z = offset.z;
//  node.param<double> ("wheel_radius_scaler", wheel_radius_scaler_, 1.0);
  ROS_DEBUG("Loading wheel: %s",link_name_.c_str());
  ROS_DEBUG("offset_.x: %f, offset_.y: %f, offset_.z: %f", offset_.x, offset_.y, offset_.z);
  return true;
}

bool Caster::init(pr2_mechanism_model::RobotState *robot_state,  ros::NodeHandle &node, std::string link_name)
{
  caster_stuck_ = 0;
  caster_speed_ = 0;
  caster_speed_filtered_ = 0;
  caster_speed_error_ = 0;
  caster_position_error_ = 0;
  steer_angle_stored_ = 0;
  steer_velocity_desired_ = 0;
  steer_angle_actual_ = 0;
  num_children_ = 0;

#if URDFDOM_1_0_0_API
  urdf::LinkConstSharedPtr link;
#else
  boost::shared_ptr<const urdf::Link> link;
#endif
  link = robot_state->model_->robot_model_.getLink(link_name);
  if (!link){
    ROS_ERROR("Could not find link with name %s",link_name.c_str());
    return false;
  }
  ROS_DEBUG("caster name: %s",link_name.c_str());
  link_name_ = link_name;
  joint_name_ = link->parent_joint->name;

  joint_ = robot_state->getJointState(joint_name_);
  if (!joint_){
    ROS_ERROR("Could not find joint with name %s",joint_name_.c_str());
    return false;
  }
  urdf::Vector3 offset = link->parent_joint->parent_to_joint_origin_transform.position;
  offset_.x = offset.x;
  offset_.y = offset.y;
  offset_.z = offset.z;

  for(unsigned int i=0; i < link->child_links.size(); i++)
  {
#if URDFDOM_1_0_0_API
    urdf::LinkSharedPtr child = link->child_links[i];
#else
    boost::shared_ptr<urdf::Link> child = link->child_links[i];
#endif
    Wheel tmp;
    parent_->wheel_.push_back(tmp);
    if(!parent_->wheel_[parent_->num_wheels_].init(robot_state, node, child->name))
    {
      ROS_ERROR("Could not initialize caster %s",link_name.c_str());
      return false;
    }
    parent_->num_wheels_++;
    num_children_++;
  }
  return true;
}

bool BaseKinematics::init(pr2_mechanism_model::RobotState *robot_state, ros::NodeHandle &node)
{
  std::string caster_names_string;
  std::vector<std::string> caster_names;
  name_ = node.getNamespace();
  //Initialize stuff
  MAX_DT_ = 0.01;
  num_wheels_ = 0;
  num_casters_ = 0;

  robot_state_ = robot_state;

  node.param<std::string> ("caster_names",caster_names_string,"");
  std::stringstream ss(caster_names_string);
  std::string tmp;
  while(ss >> tmp)
  {
    caster_names.push_back(tmp);
  }

  for(unsigned int i=0; i < caster_names.size(); i++)
  {
    Caster tmp;
    caster_.push_back(tmp);
    caster_[num_casters_].parent_ = this;
    ROS_DEBUG("caster name: %s",caster_names[i].c_str());
    ros::NodeHandle n(name_);
    if(!caster_[num_casters_].init(robot_state, n, caster_names[i]))
    {
      ROS_ERROR("Could not initialize base kinematics");
      return false;
    }
    num_casters_++;
  }

  //  node.param<double> ("wheel_radius", wheel_radius_, 0.074792);
  double multiplier;
  node.param<double> ("wheel_radius_multiplier", multiplier, 1.0);
  int wheel_counter = 0;
  for(int j = 0; j < num_casters_; j++)
  {
    for(int i = 0; i < caster_[j].num_children_; i++)
    {
      wheel_[wheel_counter].parent_ = &(caster_[j]);
      wheel_[wheel_counter].wheel_radius_*=multiplier;
      wheel_counter++;
    }
  }
  return true;
}

void Wheel::updatePosition()
{
  geometry_msgs::Point result = parent_->offset_;
  double costh = cos(parent_->joint_->position_);
  double sinth = sin(parent_->joint_->position_);
  result.x += costh * offset_.x - sinth * offset_.y;
  result.y += sinth * offset_.x + costh * offset_.y;
  result.z = 0.0;
  position_ = result;
}

void BaseKinematics::computeWheelPositions()
{
  for(int i = 0; i < num_wheels_; i++)
  {
    wheel_[i].updatePosition();
  }

}

geometry_msgs::Twist BaseKinematics::pointVel2D(const geometry_msgs::Point& pos, const geometry_msgs::Twist& vel)
{
  geometry_msgs::Twist result;
  result.linear.x = vel.linear.x - pos.y * vel.angular.z;
  result.linear.y = vel.linear.y + pos.x * vel.angular.z;
  result.angular.z = 0;
  return result;
}


text:
// Copyright (c) 2012-2018 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <merkleblock.h>
#include <uint256.h>
#include <test/test_dollar.h>

#include <boost/test/unit_test.hpp>

BOOST_FIXTURE_TEST_SUITE(merkleblock_tests, BasicTestingSetup)

/**
 * Create a CMerkleBlock using a list of txids which will be found in the
 * given block.
 */
BOOST_AUTO_TEST_CASE(merkleblock_construct_from_txids_found)
{
    CBlock block = getBlock13b8a();

    std::set<uint256> txids;

    // Last txn in block.
    uint256 txhash1 = uint256S("0x74d681e0e03bafa802c8aa084379aa98d9fcd632ddc2ed9782b586ec87451f20");

    // Second txn in block.
    uint256 txhash2 = uint256S("0xf9fc751cb7dc372406a9f8d738d5e6f8f63bab71986a39cf36ee70ee17036d07");

    txids.insert(txhash1);
    txids.insert(txhash2);

    CMerkleBlock merkleBlock(block, txids);

    BOOST_CHECK_EQUAL(merkleBlock.header.GetHash().GetHex(), block.GetHash().GetHex());

    // vMatchedTxn is only used when bloom filter is specified.
    BOOST_CHECK_EQUAL(merkleBlock.vMatchedTxn.size(), 0U);

    std::vector<uint256> vMatched;
    std::vector<unsigned int> vIndex;

    BOOST_CHECK_EQUAL(merkleBlock.txn.ExtractMatches(vMatched, vIndex).GetHex(), block.hashMerkleRoot.GetHex());
    BOOST_CHECK_EQUAL(vMatched.size(), 2U);

    // Ordered by occurrence in depth-first tree traversal.
    BOOST_CHECK_EQUAL(vMatched[0].ToString(), txhash2.ToString());
    BOOST_CHECK_EQUAL(vIndex[0], 1U);

    BOOST_CHECK_EQUAL(vMatched[1].ToString(), txhash1.ToString());
    BOOST_CHECK_EQUAL(vIndex[1], 8U);
}

/**
 * Create a CMerkleBlock using a list of txids which will not be found in the
 * given block.
 */
BOOST_AUTO_TEST_CASE(merkleblock_construct_from_txids_not_found)
{
    CBlock block = getBlock13b8a();

    std::set<uint256> txids2;
    txids2.insert(uint256S("0xc0ffee00003bafa802c8aa084379aa98d9fcd632ddc2ed9782b586ec87451f20"));
    CMerkleBlock merkleBlock(block, txids2);

    BOOST_CHECK_EQUAL(merkleBlock.header.GetHash().GetHex(), block.GetHash().GetHex());
    BOOST_CHECK_EQUAL(merkleBlock.vMatchedTxn.size(), 0U);

    std::vector<uint256> vMatched;
    std::vector<unsigned int> vIndex;

    BOOST_CHECK_EQUAL(merkleBlock.txn.ExtractMatches(vMatched, vIndex).GetHex(), block.hashMerkleRoot.GetHex());
    BOOST_CHECK_EQUAL(vMatched.size(), 0U);
    BOOST_CHECK_EQUAL(vIndex.size(), 0U);
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: Dollar-coin/Dollar

max_issues_repo_name: Dollar-coin/Dollar

max_forks_repo_name: Dollar-coin/Dollar


text:
#pragma once
#include <condition_variable>
#include <thread>
#include <boost/multi_index/hashed_index.hpp>
#include <boost/multi_index/member.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <boost/multi_index_container.hpp>

#include <rai/common/numbers.hpp>
#include <rai/common/blocks.hpp>
#include <rai/common/errors.hpp>
#include <rai/common/util.hpp>
#include <rai/secure/common.hpp>
#include <rai/node/blockquery.hpp>

namespace rai
{
class Node;

typedef std::function<rai::ErrorCode(std::shared_ptr<rai::Block>&)>
    RewarderAction;
typedef std::function<void(rai::ErrorCode, const std::shared_ptr<rai::Block>&)>
    RewarderCallback;

class RewarderInfo
{
public:
    uint64_t timestamp_;
    rai::BlockHash hash_;
    rai::Amount amount_;
};

class RewarderInfoByTime
{
};

class RewarderInfoByAmount
{
};

typedef boost::multi_index_container<
    rai::RewarderInfo,
    boost::multi_index::indexed_by<
        boost::multi_index::hashed_unique<boost::multi_index::member<
            rai::RewarderInfo, rai::BlockHash, &rai::RewarderInfo::hash_>>,
        boost::multi_index::ordered_non_unique<
            boost::multi_index::tag<rai::RewarderInfoByTime>,
            boost::multi_index::member<rai::RewarderInfo, uint64_t,
                                       &rai::RewarderInfo::timestamp_>>,
        boost::multi_index::ordered_non_unique<
            boost::multi_index::tag<rai::RewarderInfoByAmount>,
            boost::multi_index::member<rai::RewarderInfo, rai::Amount,
                                       &rai::RewarderInfo::amount_>,
            std::greater<rai::Amount>>>>
    RewarderInfos;

class Rewarder
{
public:
    Rewarder(rai::Node&, const rai::Account&, uint32_t);

    void Add(const rai::BlockHash&, const rai::Amount&, uint64_t);
    void Add(const rai::RewarderInfo&);
    void UpToDate();
    void KeepUpToDate() const;
    void QueueAction(const rai::RewarderAction&, const rai::RewarderCallback&);
    void Run();
    void Send();
    uint32_t SendInterval() const;
    void Start();
    void Status(rai::Ptree&) const;
    void Stop();
    void Sync();

private:
    bool Confirm_(std::unique_lock<std::mutex>&);
    rai::ErrorCode ProcessReward_(const rai::Amount&, const rai::BlockHash&,
                                  std::shared_ptr<rai::Block>&);
    rai::ErrorCode ProcessSend_(const rai::Account&,
                                std::shared_ptr<rai::Block>&);
    rai::QueryCallback QueryCallback_(const rai::Account&, uint64_t,
                                      const rai::BlockHash&) const;

    rai::Node& node_;
    uint32_t daily_send_times_;
    rai::Fan fan_;
    std::condition_variable condition_;
    mutable std::mutex mutex_;
    bool stopped_;
    bool up_to_date_;
    std::shared_ptr<rai::Block> block_;
    std::deque<std::pair<rai::RewarderAction, rai::RewarderCallback>> actions_;
    rai::RewarderInfos rewardables_;
    rai::RewarderInfos waitings_;
    std::thread thread_;
};
}  // namespace rai

max_stars_repo_name: gokoo/Raicoin


text:
//
// Copyright (c) 2018-2020 CNRS INRIA
//

#include "pinocchio/bindings/python/algorithm/algorithms.hpp"
#include "pinocchio/algorithm/kinematics-derivatives.hpp"
#include "pinocchio/algorithm/center-of-mass-derivatives.hpp"

#include <boost/python/tuple.hpp>

namespace pinocchio
{
  namespace python
  {
    namespace bp = boost::python;

    bp::tuple getJointVelocityDerivatives_proxy(const Model & model,
                                                Data & data,
                                                const Model::JointIndex jointId,
                                                ReferenceFrame rf)
    {
      typedef Data::Matrix6x Matrix6x;

      Matrix6x partial_dq(Matrix6x::Zero(6,model.nv));
      Matrix6x partial_dv(Matrix6x::Zero(6,model.nv));

      getJointVelocityDerivatives(model,data,jointId,rf,
                                  partial_dq,partial_dv);

      return bp::make_tuple(partial_dq,partial_dv);
    }

    bp::tuple getJointAccelerationDerivatives_proxy(const Model & model,
                                                    Data & data,
                                                    const Model::JointIndex jointId,
                                                    ReferenceFrame rf)
    {
      typedef Data::Matrix6x Matrix6x;

      Matrix6x v_partial_dq(Matrix6x::Zero(6,model.nv));
      Matrix6x a_partial_dq(Matrix6x::Zero(6,model.nv));
      Matrix6x a_partial_dv(Matrix6x::Zero(6,model.nv));
      Matrix6x a_partial_da(Matrix6x::Zero(6,model.nv));

      getJointAccelerationDerivatives(model,data,jointId,rf,
                                      v_partial_dq,a_partial_dq,
                                      a_partial_dv,a_partial_da);

      return bp::make_tuple(v_partial_dq,a_partial_dq,a_partial_dv,a_partial_da);
    }

    Data::Matrix3x getCoMVelocityDerivatives_proxy(const Model & model,
                                                   Data & data)
    {
      typedef Data::Matrix3x Matrix3x;
      Matrix3x partial_dq(Matrix3x::Zero(3,model.nv));
      getCenterOfMassVelocityDerivatives(model,data,partial_dq);
      return partial_dq;
    }

    void exposeKinematicsDerivatives()
    {
      using namespace Eigen;

      bp::def("computeForwardKinematicsDerivatives",
              &computeForwardKinematicsDerivatives<double,0,JointCollectionDefaultTpl,VectorXd,VectorXd,VectorXd>,
              bp::args("model","data","q","v","a"),
              "Computes all the terms required to compute the derivatives of the placement, spatial velocity and acceleration\n"
              "for any joint of the model.\n"
              "The results are stored in data.\n\n"
              "Parameters:\n"
              "\tmodel: model of the kinematic tree\n"
              "\tdata: data related to the model\n"
              "\tq: the joint configuration vector (size model.nq)\n"
              "\tv: the joint velocity vector (size model.nv)\n"
              "\ta: the joint acceleration vector (size model.nv)\n");

      bp::def("getJointVelocityDerivatives",
              getJointVelocityDerivatives_proxy,
              bp::args("model","data","joint_id","reference_frame"),
              "Computes the partial derivatives of the spatial velocity of a given joint with respect to\n"
              "the joint configuration and velocity and returns them as a tuple.\n"
              "The Jacobians can be either expressed in the LOCAL frame of the joint, in the LOCAL_WORLD_ALIGNED frame or in the WORLD coordinate frame depending on the value of reference_frame.\n"
              "You must first call computeForwardKinematicsDerivatives before calling this function.\n\n"
              "Parameters:\n"
              "\tmodel: model of the kinematic tree\n"
              "\tdata: data related to the model\n"
              "\tjoint_id: index of the joint\n"
              "\treference_frame: reference frame in which the resulting derivatives are expressed\n");

      bp::def("getJointAccelerationDerivatives",
              getJointAccelerationDerivatives_proxy,
              bp::args("model","data","joint_id","reference_frame"),
              "Computes the partial derivatives of the spatial acceleration of a given joint with respect to\n"
              "the joint configuration, velocity and acceleration and returns them as a tuple.\n"
              "The Jacobians can be either expressed in the LOCAL frame of the joint, in the LOCAL_WORLD_ALIGNED frame or in the WORLD coordinate frame depending on the value of reference_frame.\n"
              "You must first call computeForwardKinematicsDerivatives before calling this function.\n\n"
              "Parameters:\n"
              "\tmodel: model of the kinematic tree\n"
              "\tdata: data related to the model\n"
              "\tjoint_id: index of the joint\n"
              "\treference_frame: reference frame in which the resulting derivatives are expressed\n");

      bp::def("getCenterOfMassVelocityDerivatives",
              getCoMVelocityDerivatives_proxy,
              bp::args("model","data"),
              "Computes the partial derivaties of the center of mass velocity with respect to\n"
              "the joint configuration.\n"
              "You must first call computeForwardKinematicsDerivatives and centerOfMass(q,v) "
              "before calling this function.\n\n"
              "Parameters:\n"
              "\tmodel: model of the kinematic tree\n"
              "\tdata: data related to the model\n");

    }

  } // namespace python
} // namespace pinocchio

max_stars_repo_name: RIVeR-Lab/pinocchio


text:
//==================================================================================================
/**
  Copyright 2016 NumScale SAS

  Distributed under the Boost Software License, Version 1.0.
  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
**/
//==================================================================================================
#ifndef BOOST_SIMD_ARCH_COMMON_SIMD_FUNCTION_BITWISE_XOR_HPP_INCLUDED
#define BOOST_SIMD_ARCH_COMMON_SIMD_FUNCTION_BITWISE_XOR_HPP_INCLUDED

#include <boost/simd/function/bitwise_cast.hpp>
#include <boost/simd/detail/overload.hpp>
#include <boost/simd/detail/traits.hpp>
#include <boost/simd/detail/nsm.hpp>

namespace boost { namespace simd { namespace ext
{
  namespace bs = boost::simd;
  namespace bd = boost::dispatch;

  BOOST_DISPATCH_OVERLOAD_IF( bitwise_xor_
                            , (typename A0,typename A1,typename X, typename Y)
                            , (nsm::and_< nsm::not_ < std::is_same<A0,A1> >
                                            , nsm::and_ < detail::is_native<X>
                                                            , detail::is_native<Y>
                                                            >
                                            >
                              )
                            , bd::cpu_
                            , bs::pack_<bd::arithmetic_<A0>,X>
                            , bs::pack_<bd::arithmetic_<A1>,Y>
                            )
  {
    BOOST_FORCEINLINE A0 operator()(const A0& a0, const A1& a1) const BOOST_NOEXCEPT
    {
      return bitwise_xor(a0, bitwise_cast<A0>(a1));
    }
  };
} } }

#endif

max_stars_repo_name: SylvainCorlay/pythran

max_issues_repo_name: SylvainCorlay/pythran

max_forks_repo_name: SylvainCorlay/pythran


text:
//==================================================================================================
/**
  Copyright 2016 Numscale SAS

  Distributed under the Boost Software License, Version 1.0.
  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
**/
//==================================================================================================
#ifndef BOOST_SIMD_ARCH_X86_SSE2_SIMD_FUNCTION_PACK_CAST_HPP_INCLUDED
#define BOOST_SIMD_ARCH_X86_SSE2_SIMD_FUNCTION_PACK_CAST_HPP_INCLUDED

#include <boost/simd/detail/overload.hpp>

namespace boost { namespace simd { namespace ext
{
  namespace bd =  boost::dispatch;
  namespace bs =  boost::simd;

  //------------------------------------------------------------------------------------------------
  //  float --> int32
  BOOST_DISPATCH_OVERLOAD ( pack_cast_
                          , (typename A0, typename A1)
                          , bs::sse2_
                          , bs::pack_<bd::single_<A0>, bs::sse_>
                          , bd::target_<bd::scalar_<bd::int32_<A1>>>
                          )
  {
    using result = typename A0::template rebind<typename A1::type>;
    BOOST_FORCEINLINE result operator() ( const A0 & a0, A1 const& ) const BOOST_NOEXCEPT
    {
      return _mm_cvttps_epi32(a0);
    }
  };

  //------------------------------------------------------------------------------------------------
  //  int32 --> float
  BOOST_DISPATCH_OVERLOAD ( pack_cast_
                          , (typename A0, typename A1)
                          , bs::sse2_
                          , bs::pack_<bd::int32_<A0>, bs::sse_>
                          , bd::target_<bd::scalar_<bd::single_<A1>>>
                          )
  {
    using result = typename A0::template rebind<typename A1::type>;
    BOOST_FORCEINLINE result operator() ( const A0 & a0, A1 const& ) const BOOST_NOEXCEPT
    {
      return _mm_cvtepi32_ps(a0);
    }
  };
} } }

#endif


text:
#include <ros/ros.h>
#include <pluginlib/class_loader.h>
#include <moveit/kinematics_base/kinematics_base.h>
#include <boost/python.hpp>
#include <boost/python/stl_iterator.hpp>
#include <string>
#include <vector>

/**
 * \file        Python wrapper for IK/FK in kinematics::KinematicsBase
 * \author      Nicolas Alt
 * \date        2014-08-26
 */

namespace py = boost::python;

// http://stackoverflow.com/questions/3761391/boostpython-python-list-to-stdvector
template< typename T > inline std::vector< T > to_std_vector( const py::object& iterable ) {
    return std::vector< T >( py::stl_input_iterator< T >( iterable ),
                             py::stl_input_iterator< T >( ) );
}

// http://stackoverflow.com/questions/6157409/stdvector-to-boostpythonlist
template<typename T> py::list to_py_list(const std::vector<T>& v) {
	py::list l;
	typename std::vector<T>::const_iterator it;
	for (it = v.begin(); it != v.end(); ++it)
	    l.append(*it);
	return l;
}

// The plugin file defines PLUGINLIB_EXPORT_CLASS(ikfast_kinematics_plugin::IKFastKinematicsPlugin, ...
// lmtclam_moveit_ikfast/package.xml exports the plugin in the name of moveit_core
pluginlib::ClassLoader<kinematics::KinematicsBase> loader("moveit_core", "kinematics::KinematicsBase");

/** \brief Helper class for methods in kinematics::KinematicsBase. These methods are exported to Python.
 *  \param plugin_name <package>/<pluginname> of IKfast plugin, e.g. lmtclam_arm_kinematics/IKFastKinematicsPlugin
 */
class kinematics_wrapper
{
    private:
        boost::shared_ptr<kinematics::KinematicsBase> ik;

	public:
		kinematics_wrapper(std::string node_name, std::string plugin_name)
        {
			int c = 0;
			ros::init(c, NULL, node_name, ros::init_options::NoSigintHandler);

            try {
                ik = loader.createInstance(plugin_name);
            } catch(pluginlib::PluginlibException& ex) {
                ROS_ERROR("The plugin failed to load. Error: %s", ex.what());
            }
            //printf("ik:%x\n", (void*)ik.get());
			//ik = new ikfast_kinematics_plugin::IKFastKinematicsPlugin();
		}
		~kinematics_wrapper()  {  }
		std::string greet() { return "Hello world"; }
		std::string getBaseFrame() { return ik->getBaseFrame(); }
		bool initialize(std::string robot_description, std::string group_name, std::string base_name, std::string tip_name, double search_discretization) {
            if (!ik) {
                ROS_ERROR("KinematicsBase object is NULL");
                return false;
            }
			return ik->initialize(robot_description, group_name, base_name, tip_name, search_discretization);
        }

		py::object getPositionFK(std::string link_name, py::list joint_angles)
		{
			std::vector< geometry_msgs::Pose > _poses;
			std::vector < double > _joint_angles = to_std_vector<double>(joint_angles);
			std::vector < std::string > _link_names; _link_names.push_back(link_name);

			bool r = ik->getPositionFK(_link_names, _joint_angles, _poses);

			if (r && _poses.size() >= 1) {
				py::dict pose;
				py::list pose_t, pose_q;
				pose_t.append<double>(_poses[0].position.x);
				pose_t.append<double>(_poses[0].position.y);
				pose_t.append<double>(_poses[0].position.z);
				pose_q.append<double>(_poses[0].orientation.w);
				pose_q.append<double>(_poses[0].orientation.x);
				pose_q.append<double>(_poses[0].orientation.y);
				pose_q.append<double>(_poses[0].orientation.z);

				pose["position"] = pose_t;
				pose["orientation"] = pose_q;
				return pose;
			} else
				return py::object();
		}

		py::object searchPositionIK(py::list ik_position, py::list ik_orientation, py::list ik_seed_state, double timeout) {
			return getPositionIK(ik_position, ik_orientation, ik_seed_state,timeout, false);
		}

	    py::object searchApproximatePositionIK(py::list ik_position, py::list ik_orientation, py::list ik_seed_state, double timeout)
		{
			return getPositionIK(ik_position, ik_orientation, ik_seed_state,timeout, true);
		}

		py::object getPositionIK(py::list ik_position, py::list ik_orientation, py::list ik_seed_state, double timeout, bool approximate_solution = false)
		{
			geometry_msgs::Pose _ik_pose;
			_ik_pose.position.x = py::extract<double>(ik_position[0]);
			_ik_pose.position.y = py::extract<double>(ik_position[1]);
			_ik_pose.position.z = py::extract<double>(ik_position[2]);
			_ik_pose.orientation.w = py::extract<double>(ik_orientation[0]);
			_ik_pose.orientation.x = py::extract<double>(ik_orientation[1]);
			_ik_pose.orientation.y = py::extract<double>(ik_orientation[2]);
			_ik_pose.orientation.z = py::extract<double>(ik_orientation[3]);
			std::vector< double > _ik_seed_state = to_std_vector<double>(ik_seed_state);
			std::vector< double > _consistency_limits, _solution;
			moveit_msgs::MoveItErrorCodes _error_code;
			kinematics::KinematicsQueryOptions _options;
			_options.return_approximate_solution = approximate_solution;
			bool r = ik->searchPositionIK (_ik_pose, _ik_seed_state, timeout, _consistency_limits, _solution, _error_code, _options);
			if (r)
				return to_py_list<double>(_solution);
			else
				return py::object();
		}
};

// typedef kinematics::KinematicsBase KinematicsType;
// typedef ikfast_kinematics_plugin::IKFastKinematicsPlugin KinematicsType;
// typedef test_class KinematicsType;

/*struct kb_callback : KinematicsType {
    kb_callback(PyObject *p) : self(p) {}
    //int pure(int x) { return call_method<int>(self, "pure", x); }
    PyObject *self;
};*/

typedef kinematics_wrapper KinematicsType;

/** \brief Defines the Python module */
BOOST_PYTHON_MODULE(kinematics_py)
{
    // Create the Python type object for our extension class and define __init__ function.
    //class_<KinematicsType, boost::noncopyable, boost::shared_ptr<kb_callback> >("kinematics_base")
    //class_<kinematics::KinematicsBase  , boost::noncopyable>("kinematics_base", no_init)
    //class_<KinematicsType, boost::noncopyable, boost::shared_ptr<kb_callback> >("kinematics_base")
    py::class_<KinematicsType>("Kinematics", py::init<std::string, std::string>())
    	.def("greet", &KinematicsType::greet)
    	.def("initialize", &KinematicsType::initialize)
        .def("getBaseFrame", &KinematicsType::getBaseFrame)
        .def("getPositionFK", &KinematicsType::getPositionFK)
        .def("searchPositionIK", &KinematicsType::searchPositionIK)
		.def("searchApproximatePositionIK", &KinematicsType::searchApproximatePositionIK)
    ;
}


text:
#pragma once

#include <iostream>
#include <sstream>
#include <ostream>
#include <chrono>
#include <iomanip>
#include <boost/thread.hpp>

enum class InfoLevel
{
	INF,
	DBG,
	WRN,
	ERR
};

class ServerLog
{
public:
	static ServerLog S_LOG;

	ServerLog() : info_level{ InfoLevel::INF }, o_stream{} {}

	ServerLog& operator()(InfoLevel il);
	template<typename T>
	ServerLog& operator<<(T&& value);
	ServerLog& operator<<(std::ostream& (*os)(std::ostream&));

private:
	InfoLevel info_level;
	std::ostringstream o_stream;

	std::string return_curr_time_and_date() const;
	std::string return_info_level_str() const;
	std::string return_curr_thread_id() const;
	std::string return_arrow_pointer() const;
};

inline ServerLog& ServerLog::operator()(InfoLevel il)
{
	info_level = il;
	return *this;
}

template<typename T>
inline ServerLog& ServerLog::operator<<(T&& value)
{
	o_stream << value;
	return *this;
}

inline ServerLog& ServerLog::operator<<(std::ostream& (*os)(std::ostream&))
{
	std::cout <<
		return_curr_time_and_date() <<
		return_info_level_str() <<
		return_curr_thread_id() <<
		return_arrow_pointer() <<
		o_stream.str() << os;
	o_stream.str("");
	info_level = InfoLevel::INF;
	return *this;
}

struct Logger
{
	static ServerLog S_LOG;
};


text:
#include <nav_msgs/Odometry.h>
#include <ros/ros.h>
#include <tf2/LinearMath/Quaternion.h>
#include <tf2_ros/static_transform_broadcaster.h>
#include <Eigen/Core>
#include <cmath>
#include <iostream>

using namespace Eigen;

double deg2rad(const double degree) { return degree * M_PI / 180.0; }

double rad2deg(const double radian) { return radian * 180.0 / M_PI; }

double angle_limit_pi(double angle)
{
  while (angle >= M_PI) { angle -= 2 * M_PI; }
  while (angle <= -M_PI) { angle += 2 * M_PI; }
  return angle;
}

double sdlab_uniform()
{
  double ret = ((double)rand() + 1.0) / ((double)RAND_MAX + 2.0);
  return ret;
}

// gauss noise
double gauss(double mu, double sigma)
{
  double z = std::sqrt(-2.0 * std::log(sdlab_uniform())) * std::sin(2.0 * M_PI * sdlab_uniform());
  return mu + sigma * z;
}

class FakeSensorPublisher
{
public:
  FakeSensorPublisher()
  : grund_truth(Matrix<double, 3, 1>::Zero()),
    odom(Matrix<double, 3, 1>::Zero()),
    gps(Matrix<double, 3, 1>::Zero())
  {
    Q << 0.1, 0, 0, deg2rad(30);
    Q = Q * Q;
    R << 2.0, 0.0, 0.0, 0.0, 2.0, 0.0, 0.0, 0.0, deg2rad(5);
    R = R * R;

    ground_truth_pub_ = pnh_.advertise<nav_msgs::Odometry>("grund_truth", 10);
    odom_pub_ = pnh_.advertise<nav_msgs::Odometry>("odom", 10);
    gps_pub_ = pnh_.advertise<nav_msgs::Odometry>("gps", 10);

    previous_stamp_ = ros::Time::now();

    timer_ = nh_.createTimer(ros::Duration(0.01), &FakeSensorPublisher::timerCallback, this);
  }
  ~FakeSensorPublisher() {}
  nav_msgs::Odometry inputToNavMsgs(Matrix<double, 3, 1> pose_2d, Matrix<double, 2, 1> input)
  {
    nav_msgs::Odometry msg;
    msg.header.frame_id = "world";
    msg.child_frame_id = "odom";
    msg.pose.pose.position.x = pose_2d[0];
    msg.pose.pose.position.y = pose_2d[1];

    tf2::Quaternion quat;
    quat.setRPY(0.0, 0.0, angle_limit_pi(pose_2d[2]));
    msg.pose.pose.orientation.w = quat.w();
    msg.pose.pose.orientation.x = quat.x();
    msg.pose.pose.orientation.y = quat.y();
    msg.pose.pose.orientation.z = quat.z();
    msg.twist.twist.linear.x = input[0];
    msg.twist.twist.angular.z = input[1];

    return msg;
  }
  void timerCallback(const ros::TimerEvent & e)
  {
    ros::Time current_stamp = ros::Time::now();

    nav_msgs::Odometry grund_truth_msg;
    nav_msgs::Odometry odom_msg;
    nav_msgs::Odometry gps_msgs;

    Matrix<double, 2, 1> u(1.0, deg2rad(5));

    const double dt = current_stamp.toSec() - previous_stamp_.toSec();

    // ground truth
    ROS_INFO("delta time: %f", dt);
    grund_truth = motionModel(grund_truth, u, dt);
    grund_truth_msg = inputToNavMsgs(grund_truth, u);

    // dead recogning
    Matrix<double, 2, 1> ud = motionNoise(u, Q);
    odom = motionModel(odom, ud, dt);
    odom_msg = inputToNavMsgs(odom, ud);

    // observation
    Matrix<double, 3, 1> gps = observationNoise(grund_truth, R);
    gps_msgs = inputToNavMsgs(gps, Matrix<double, 2, 1>::Zero());

    ground_truth_pub_.publish(grund_truth_msg);
    odom_pub_.publish(odom_msg);
    gps_pub_.publish(gps_msgs);

    previous_stamp_ = current_stamp;
  }
  Matrix<double, 3, 1> motionModel(Matrix<double, 3, 1> x, Matrix<double, 2, 1> u, double dt)
  {
    Matrix<double, 3, 3> F = Matrix<double, 3, 3>::Identity();
    Matrix<double, 3, 2> B;
    B << dt * std::cos(x[2]), 0, dt * std::sin(x[2]), 0, 0, dt;

    x = F * x + B * u;
    x[2] = angle_limit_pi(x[2]);
    return x;
  }
  Matrix<double, 2, 1> motionNoise(Matrix<double, 2, 1> u, Matrix<double, 2, 2> Q)
  {
    Matrix<double, 2, 1> uw(gauss(0.0, Q(0, 0)), gauss(0.0, Q(1, 1)));
    return u + uw;
  }
  Matrix<double, 3, 1> observationNoise(Matrix<double, 3, 1> x, Matrix<double, 3, 3> R)
  {
    Matrix<double, 3, 1> xw(gauss(0.0, R(0, 0)), gauss(0.0, R(1, 1)), gauss(0.0, R(2, 2)));
    return x + xw;
  }

private:
  ros::NodeHandle nh_{};
  ros::NodeHandle pnh_{"~"};
  ros::Timer timer_;
  ros::Time previous_stamp_;

  ros::Publisher ground_truth_pub_;
  ros::Publisher odom_pub_;
  ros::Publisher gps_pub_;

  Matrix<double, 2, 2> Q;
  Matrix<double, 3, 3> R;
  Matrix<double, 3, 1> grund_truth;
  Matrix<double, 3, 1> odom;
  Matrix<double, 3, 1> gps;
};

int main(int argc, char ** argv)
{
  ros::init(argc, argv, "fake_sensor_publisher_node");
  FakeSensorPublisher fake_sensor_publisher;
  ros::spin();
  return 0;
}


text:
//
// Created by alex on 11/17/18.
//
#define CATCH_CONFIG_MAIN

#include <catch2/catch.hpp>

#include <gie/Program.h>

#include <boost/python.hpp>

#include <cassert>
#include <vector>

#include <iostream>

TEST_CASE("GIE API tests", "[program]")
{

    Program program;
    program.context().module("builtins", false);

    auto sys = program.context().module("sys", false);
    auto os = program.context().module("os", false);

    sys.attr("path").attr("insert")(1, os.attr("getcwd")());

    program.import("basic", "test_modules/basic.py");

    boost::python::object input(10);

    SECTION("a couple of nodes")
    {
        NodeId castToString, castToInt;
        castToString = program.addNode("basic.to_string", {ArgumentValue{Value{input}}});
        SECTION("1 node run") {
            program.addResult("1 node run", castToString);
            auto result = program.run();
            REQUIRE(std::to_string(boost::python::extract<int>(input)) ==
                    std::string{boost::python::extract<std::string>(program.getCache(castToString).value()->object())});
        }

        castToInt = program.addNode("basic.to_int", {castToString});

        SECTION("2 nodes run")
        {
            program.addResult("1 nodes run", castToInt);
            auto result = program.run();
            REQUIRE(boost::python::extract<int>(input) == boost::python::extract<int>(program.getCache(castToInt).value()->object()));
        }

        SECTION("removing node")
        {
            program.removeNode(castToInt).discard();
            program.addResult("toString", castToString);
            auto result = program.run();
            REQUIRE(std::to_string(boost::python::extract<int>(input)) ==
                    std::string{boost::python::extract<std::string>(program.getCache(castToString).value()->object())});

            program.removeResult("toString");
            program.removeNode(castToString).discard();
            auto result2 = program.run();
        }
    }

    SECTION("many nodes")
    {
        std::vector<NodeId> castToString;
        std::vector<NodeId> castToInt;

        castToString.push_back(
                program.addNode("basic.to_string", {ArgumentValue{Value{input}}}));
        castToInt.push_back(program.addNode("basic.to_int", {castToString.back()}));
        for (int i = 0; i < 100; i++)
        {
            castToString.push_back(program.addNode("basic.to_string", {castToInt.back()}));
            castToInt.push_back(program.addNode("basic.to_int", {castToString.back()}));
        }

        program.addResult("result", castToInt.back());

        SECTION("run")
        {
            auto result = program.run();
            REQUIRE(boost::python::extract<int>(input) == boost::python::extract<int>(program.getCache(castToInt.back()).value()->object()));
        }

        SECTION("removing nodes in the middle")
        {
            auto stringId = castToString[50];
            auto intId = castToInt[50];

            program.removeNode(stringId).discard();
            program.removeNode(intId).discard();

            program.editNode(castToString[51], ArgumentId{0}, ArgumentValue{castToInt[49]}).discard();

            auto result = program.run();
            REQUIRE(std::to_string(boost::python::extract<int>(input)) ==
                    std::to_string(boost::python::extract<int>(program.getCache(castToInt.back()).value()->object())));
        }

        SECTION("removing all nodes")
        {
            program.removeResult("result");

            for (auto i: castToString)
                program.removeNode(i).discard();
            for (auto i: castToInt)
                program.removeNode(i).discard();

            auto result = program.run();
            REQUIRE(!result.errorSet());
        }
    }
}

max_stars_repo_name: Kerdek/gie

max_issues_repo_name: Kerdek/gie

max_forks_repo_name: Kerdek/gie