text:
/*
 * Software License Agreement (BSD License)
 *
 *  Copyright (c) 2014 Max-Planck-Institute for Intelligent Systems,
 *                     University of Southern California,
 *                     Karlsruhe Institute of Technology
 *    Jan Issac (jan.issac@gmail.com)
 *
 *  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 Willow Garage, Inc. 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.
 *
 */

/**
 * @date 05/04/2014
 * @author Jan Issac (jan.issac@gmail.com)
 * Max-Planck-Institute for Intelligent Systems, University of Southern California (USC),
 *   Karlsruhe Institute of Technology (KIT)
 */

#ifndef rqt_oni_vicon_playback_PLUGIN_HPP
#define rqt_oni_vicon_playback_PLUGIN_HPP

#include <ui_playback_controller.h>

#include <boost/thread/mutex.hpp>

#include <QWidget>
#include <QStandardItem>
#include <QStandardItemModel>
#include <QStringListModel>
#include <QListWidgetItem>
#include <QTreeWidgetItem>
#include <QMessageBox>

#include <ros/ros.h>
#include <rqt_gui_cpp/plugin.h>
#include <actionlib/client/simple_action_client.h>
#include <actionlib_macros/actionlib_macros.hpp>

#include <oni_vicon_playback/OpenAction.h>
#include <oni_vicon_playback/PlayAction.h>

namespace rqt_oni_vicon_playback
{
    class PlaybackController:
        public rqt_gui_cpp::Plugin
    {
    Q_OBJECT

    ACTION_IMPLEMENT_CLIENT(oni_vicon_playback, Open)
    ACTION_IMPLEMENT_CLIENT(oni_vicon_playback, Play)

    public:
        struct StatusItem
        {
            QStandardItem* object;
            QStandardItem* status;

            StatusItem& appendRow(StatusItem& status_item)
            {
                object->appendRow(QList<QStandardItem *>() << status_item.object
                                                           << status_item.status);

                return *this;
            }
        };

        PlaybackController();
        virtual void initPlugin(qt_gui_cpp::PluginContext& context);
        virtual void shutdownPlugin();
        virtual void saveSettings(qt_gui_cpp::Settings& plugin_settings,
                                  qt_gui_cpp::Settings& instance_settings) const;
        virtual void restoreSettings(const qt_gui_cpp::Settings& plugin_settings,
                                     const qt_gui_cpp::Settings& instance_settings);

    private slots:
        void onOpen();
        void onClose();
        void onPlay();
        void onPause();
        void onStop();
        void onSelectRecordingDirectory();
        void onUpdateStatus();
        void onUpdateOpeningProgress(int progress,
                                     int progress_max,
                                     double total_time,
                                     int total_vicon_frames,
                                     int total_depth_sensor_frames,
                                     double time_offet);
        void onUpdatePlayback(double time, int vicon_frame, int depth_sensor_frame);
        void onSetFrame(int frame);
        void onSetTime(double time);
        void onSetPlaybackSpeed(double speed);
        void onSetTimeOffset(double offset);
        void onSetStepsize(double stepsize);
        void onSaveOffset();

    signals:
        void updateOpeningProgress(int progress,
                                   int progress_max,
                                   double total_time,
                                   int total_vicon_frames,
                                   int total_depth_sensor_frames,
                                   double time_offet);
        void updatePlayback(double time, int vicon_frame, int depth_sensor_frame);

    private: /* implementation details */
        bool box(QString message, bool rval = false, QMessageBox::Icon type = QMessageBox::Warning);

        // fluent interface to simplify things
        StatusItem& statusItem(std::string item_name);
        StatusItem& statusTreeRoot(QStandardItem *root);
        QList<QStandardItem*> statusRow(std::string item_name);
        StatusItem& createStatusRow(std::string object_text, std::string status_text = "");

        void setActivity(std::string section_name, bool active);
        bool isActive(std::string section_name);

        bool validateRecordingDirectory(const std::string &dir);

    private:
        ros::NodeHandle node_handle_;

        Ui::PlaybackController ui_;
        QWidget* widget_;

        QIcon empty_icon_;
        QIcon ok_icon_;
        QIcon warn_icon_;
        QIcon failed_icon_;

        QTimer* timer_;

        QStandardItemModel* status_model_;
        std::map<std::string, StatusItem> status_tree_container_;
        std::map<std::string, bool> activity_status_map_;
    };
}

#endif


text:
#include <MasternodePayeeData.h>
#include <hash.h>
#include <boost/lexical_cast.hpp>
#include <protocol.h>
#include <Logging.h>
#include <masternode.h>
#include <net.h>
#include <MasternodeHelpers.h>

CMasternodePayee::CMasternodePayee()
{
    scriptPubKey = CScript();
    nVotes = 0;
}

CMasternodePayee::CMasternodePayee(const CScript& payee, int nVotesIn)
{
    scriptPubKey = payee;
    nVotes = nVotesIn;
}

CMasternodeBlockPayees::CMasternodeBlockPayees()
{
    nBlockHeight = 0;
    vecPayments.clear();
}

CMasternodeBlockPayees::CMasternodeBlockPayees(const CMasternodeBlockPayees& o)
    : nBlockHeight(o.nBlockHeight), vecPayments(o.vecPayments), voters(o.voters)
{
}
CMasternodeBlockPayees::CMasternodeBlockPayees(CMasternodeBlockPayees&& o)
    : nBlockHeight(o.nBlockHeight), vecPayments(std::move(o.vecPayments)), voters(std::move(o.voters))
{
}

CMasternodeBlockPayees::CMasternodeBlockPayees(int nBlockHeightIn)
{
    nBlockHeight = nBlockHeightIn;
    vecPayments.clear();
}

void CMasternodeBlockPayees::CountVote(const COutPoint& voter, const CScript& payeeIn)
{
    LOCK(cs_vecPayments);

    const auto ins = voters.insert(voter);
    assert(ins.second);

    for (auto& payee : vecPayments) {
        if (payee.scriptPubKey == payeeIn) {
            ++payee.nVotes;
            return;
        }
    }

    CMasternodePayee c(payeeIn, 1);
    vecPayments.push_back(c);
}

bool CMasternodeBlockPayees::CanVote(const COutPoint& voter) const
{
    LOCK(cs_vecPayments);
    return voters.count(voter) == 0;
}

bool CMasternodeBlockPayees::GetPayee(CScript& payee) const
{
    LOCK(cs_vecPayments);

    int nVotes = -1;
    for (const auto& p : vecPayments) {
        if (p.nVotes > nVotes) {
            payee = p.scriptPubKey;
            nVotes = p.nVotes;
        }
    }

    return (nVotes > -1);
}

bool CMasternodeBlockPayees::HasPayeeWithVotes(const CScript& payee, int nVotesReq) const
{
    LOCK(cs_vecPayments);

    for (const auto& p : vecPayments) {
        if (p.nVotes >= nVotesReq && p.scriptPubKey == payee) return true;
    }

    return false;
}

CMasternodePaymentWinner::CMasternodePaymentWinner()
    : vinMasternode()
    , seedHash()
    , nBlockHeight(0)
    , payee()
    , signature()
{
    seedHash.SetNull();
}
CMasternodePaymentWinner::CMasternodePaymentWinner(const CTxIn& vinIn, const int height, const uint256& hash)
    : vinMasternode(vinIn)
    , seedHash(hash)
    , nBlockHeight(height)
{

}

bool CMasternodePaymentWinner::ComputeScoreHash()
{
    if (GetBlockHashForScoring(seedHash, nBlockHeight))
        return true;

    LogPrint("masternode", "Failed to get scoring hash for winner of height %d\n", nBlockHeight);
    seedHash.SetNull();
    return false;
}

uint256 CMasternodePaymentWinner::GetHash() const
{
    CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION);
    ss << payee;
    ss << nBlockHeight;
    ss << vinMasternode.prevout;

    return ss.GetHash();
}

void CMasternodePaymentWinner::AddPayee(const CScript& payeeIn)
{
    payee = payeeIn;
}

const uint256&
CMasternodePaymentWinner::GetScoreHash() const
{
    assert(!seedHash.IsNull());
    return seedHash;
}

std::string CMasternodePaymentWinner::ToString() const
{
    std::string ret = "";
    ret += vinMasternode.ToString();
    ret += ", " + boost::lexical_cast<std::string>(nBlockHeight);
    ret += ", " + payee.ToString();
    ret += ", " + boost::lexical_cast<std::string>((int)signature.size());
    return ret;
}

std::string CMasternodePaymentWinner::getMessageToSign() const
{
    return vinMasternode.prevout.ToStringShort() +
            boost::lexical_cast<std::string>(nBlockHeight) +
            payee.ToString();
}

void CMasternodePaymentWinner::Relay() const
{
    CInv inv(MSG_MASTERNODE_WINNER, GetHash());
    RelayInv(inv);
}

ext: cpp


text:
#include <boost/test/unit_test.hpp>
#include <fec.h>
#include <test/util/setup_common.h>
#include <udprelay.h>
#include <util/system.h>

BOOST_AUTO_TEST_SUITE(udprelay_tests)

BOOST_AUTO_TEST_CASE(test_ischunkfilerecoverable)
{
    ChunkFileNameParts cfp;
    BOOST_CHECK(!IsChunkFileRecoverable("_8080_1234_body_2000", cfp));              // missing ip
    BOOST_CHECK(!IsChunkFileRecoverable("256.16.235.1_8080_1234_body_2000", cfp));  // invalid ip
    BOOST_CHECK(!IsChunkFileRecoverable("172.16.235.1_1234_body_2000", cfp));       // missing port
    BOOST_CHECK(!IsChunkFileRecoverable("172.16.235.1_8080_body_2000", cfp));       // missing hash_prefix
    BOOST_CHECK(!IsChunkFileRecoverable("172.16.235.1_8080_1234_2000", cfp));       // missing type
    BOOST_CHECK(!IsChunkFileRecoverable("172.16.235.1_8080_1234_body_", cfp));      // missing length
    BOOST_CHECK(!IsChunkFileRecoverable("172.16.235.1_8080-1234_body_2000", cfp));  // invalid delimiter
    BOOST_CHECK(!IsChunkFileRecoverable("172.16.235.1_8080_abc_body_2000", cfp));   // invalid hash_prefix
    BOOST_CHECK(!IsChunkFileRecoverable("172.16.235.1_8080_1234_test_2000", cfp));  // invalid type
    BOOST_CHECK(!IsChunkFileRecoverable("172.16.235.1_8080_1234_body_g2000", cfp)); // invalid length
    BOOST_CHECK(!IsChunkFileRecoverable("172.16.235:1_8080_1234_body_2000", cfp));  // previous valid format (no longer supported)
    BOOST_CHECK(IsChunkFileRecoverable("172.16.235.1_8080_1234_body_2000", cfp));   // valid case
    BOOST_CHECK(cfp.ipv4Addr.s_addr == 32182444 && cfp.port == 8080 && cfp.hash_prefix == 1234 && cfp.is_header == false && cfp.length == 2000);
    BOOST_CHECK(IsChunkFileRecoverable("172.16.235.1_9560_12345678_header_2097152", cfp)); // valid case
    BOOST_CHECK(cfp.ipv4Addr.s_addr == 32182444 && cfp.port == 9560 && cfp.hash_prefix == 12345678 && cfp.is_header == true && cfp.length == 2097152);
    BOOST_CHECK(IsChunkFileRecoverable("0.0.0.0_0_12345678_header_10000", cfp)); // valid case (trusted peer)
}

BOOST_FIXTURE_TEST_CASE(test_recovery_invalid_files_get_removed, BasicTestingSetup)
{
    std::string obj_id1 = "172.16.235.1_8080_1234_body";

    FECDecoder decoder1(FEC_CHUNK_SIZE * 2, MemoryUsageMode::USE_MMAP, obj_id1);
    FECDecoder decoder2(FEC_CHUNK_SIZE * 2, MemoryUsageMode::USE_MMAP);
    FECDecoder decoder3(FEC_CHUNK_SIZE * 2, MemoryUsageMode::USE_MMAP, "1234_body");

    // Assume the application was aborted/closed, leaving partial block data in
    // disk. Next, reload the partial blocks, as if relaunching the application.
    LoadPartialBlocks(nullptr);

    // Given that decoder1 is the only decoder applying the chunk file naming
    // convention expected by the udprelay logic (more specifically by
    // IsChunkFileRecoverable()), the expectation is that decoder1's FEC data is
    // successfully reloaded after calling "LoadPartialBlocks", in which case
    // its chunk file remains. In contrast, the chunk files from decoder2 and
    // decoder3 shall be considered non-recoverable and removed by
    // LoadPartialBlocks().
    BOOST_CHECK(fs::exists(decoder1.GetFileName()));
    BOOST_CHECK(!fs::exists(decoder2.GetFileName()));
    BOOST_CHECK(!fs::exists(decoder3.GetFileName()));

    // cleanup mapPartialBlocks
    ResetPartialBlocks();
}

BOOST_FIXTURE_TEST_CASE(test_recovery_handles_body_and_header, BasicTestingSetup)
{
    // Define a hash prefix and peer address
    char ip_addr[INET_ADDRSTRLEN] = "172.16.235.1";
    const uint64_t hash_prefix = 1234;
    unsigned short port = 8080;

    struct in_addr ipv4Addr;
    inet_pton(AF_INET, ip_addr, &(ipv4Addr));
    CService peer(ipv4Addr, port);

    // Construct two decoders for the same hash prefix, one for the header data,
    // the other for body data. Persist the chunk files in disk.
    size_t n_body_chunks = 5;
    size_t n_header_chunks = 2;
    std::string chunk_file_prefix = peer.ToStringIP() + "_" + peer.ToStringPort() + "_" + std::to_string(hash_prefix);
    std::string obj_id1 = chunk_file_prefix + "_body";
    std::string obj_id2 = chunk_file_prefix + "_header";
    {
        const bool keep_mmap_file = true;
        FECDecoder decoder1(FEC_CHUNK_SIZE * n_body_chunks, MemoryUsageMode::USE_MMAP, obj_id1, keep_mmap_file);
        FECDecoder decoder2(FEC_CHUNK_SIZE * n_header_chunks, MemoryUsageMode::USE_MMAP, obj_id2, keep_mmap_file);
    }

    // Assume the application was aborted/closed, leaving partial block data in
    // disk. Next, reload the partial blocks, as if relaunching the application.
    auto partial_block_state = AllBlkChunkStatsToJSON();
    BOOST_CHECK(partial_block_state.size() == 0);

    LoadPartialBlocks(nullptr);

    // The body and header belonging to the same block (i.e., with the same hash
    // prefix) should not instantiate two distinct PartialBlockData objects. The
    // first FEC object (body or header) should instantiate the PartialBlockData
    // object, and the second FEC object should reuse the previous
    // PartialBlockData object while setting the proper data fields (header or
    // body decoder data). Hence, the expectation is that the data recovered
    // from decoder1 and decoder2 is succesfully loaded into the same
    // PartialBlockData object.
    partial_block_state = AllBlkChunkStatsToJSON();
    BOOST_CHECK(partial_block_state.size() == 1); // two decoders belonging to the same block insert only 1 PartialBlockData

    const std::pair<uint64_t, CService> hash_peer_pair = std::make_pair(hash_prefix, peer);
    auto partial_block = GetPartialBlockData(hash_peer_pair);
    BOOST_CHECK(partial_block != nullptr);
    BOOST_CHECK(partial_block->blk_initialized);
    BOOST_CHECK(partial_block->header_initialized);
    BOOST_CHECK(partial_block->blk_len == FEC_CHUNK_SIZE * n_body_chunks);
    BOOST_CHECK(partial_block->header_len == FEC_CHUNK_SIZE * n_header_chunks);
    BOOST_CHECK(partial_block->body_decoder.GetFileName().filename().c_str() == obj_id1 + "_" + std::to_string(FEC_CHUNK_SIZE * n_body_chunks));
    BOOST_CHECK(partial_block->header_decoder.GetFileName().filename().c_str() == obj_id2 + "_" + std::to_string(FEC_CHUNK_SIZE * n_header_chunks));
    BOOST_CHECK(partial_block->body_decoder.GetChunkCount() == n_body_chunks);
    BOOST_CHECK(partial_block->header_decoder.GetChunkCount() == n_header_chunks);

    // cleanup mapPartialBlocks
    ResetPartialBlocks();
}

BOOST_FIXTURE_TEST_CASE(test_recovery_of_decodable_state, BasicTestingSetup)
{
    // Define a hash prefix and peer address
    char ip_addr[INET_ADDRSTRLEN] = "172.16.235.1";
    const uint64_t hash_prefix = 1234;
    unsigned short port = 8080;

    struct in_addr ipv4Addr;
    inet_pton(AF_INET, ip_addr, &(ipv4Addr));
    CService peer(ipv4Addr, port);

    // Construct two decoders for the same hash prefix, one for the header data,
    // the other for body data. Provide all the header chunks. Then, destroy the
    // decoders while persisting their chunk files in disk.
    std::vector<unsigned char> dummy_chunk(FEC_CHUNK_SIZE);
    size_t n_body_chunks = 5;
    size_t n_header_chunks = 2;
    std::string chunk_file_prefix = peer.ToStringIP() + "_" + peer.ToStringPort() + "_" + std::to_string(hash_prefix);
    std::string obj_id1 = chunk_file_prefix + "_body";
    std::string obj_id2 = chunk_file_prefix + "_header";
    {
        const bool keep_mmap_file = true;
        FECDecoder decoder1(FEC_CHUNK_SIZE * n_body_chunks, MemoryUsageMode::USE_MMAP, obj_id1, keep_mmap_file);
        FECDecoder decoder2(FEC_CHUNK_SIZE * n_header_chunks, MemoryUsageMode::USE_MMAP, obj_id2, keep_mmap_file);

        for (size_t chunk_id = 0; chunk_id < n_header_chunks; chunk_id++) {
            decoder2.ProvideChunk(dummy_chunk.data(), chunk_id);
        }
        BOOST_CHECK(!decoder1.DecodeReady());
        BOOST_CHECK(decoder2.DecodeReady());
    }

    // Assume the application was aborted/closed, leaving partial block data in
    // disk. Next, reload the partial blocks, as if relaunching the application.
    LoadPartialBlocks(nullptr);

    // The recovered partial block should indicate that its header is ready to
    // be processed/decoded, while the body is still not decodable.
    const std::pair<uint64_t, CService> hash_peer_pair = std::make_pair(hash_prefix, peer);
    auto partial_block = GetPartialBlockData(hash_peer_pair);
    BOOST_CHECK(partial_block != nullptr);
    BOOST_CHECK(partial_block->is_header_processing);
    BOOST_CHECK(!partial_block->is_decodeable);

    // cleanup mapPartialBlocks
    ResetPartialBlocks();
}

BOOST_FIXTURE_TEST_CASE(test_recovery_multiple_blocks, BasicTestingSetup)
{
    size_t n_decoders = 2000;
    size_t n_body_chunks = 5;
    std::vector<std::unique_ptr<FECDecoder>> decoders_vec;

    // generate "n_decoders" unique hash_prefixes
    std::unordered_set<uint64_t> hash_prefixes_set;
    std::vector<uint64_t> hash_prefixes;
    while (hash_prefixes_set.size() < n_decoders)
        hash_prefixes_set.insert(1000 + (rand() % 10000));
    hash_prefixes.insert(hash_prefixes.end(), hash_prefixes_set.begin(), hash_prefixes_set.end());

    // Construct many decoders while persisting their chunk files in disk
    {
        const bool keep_mmap_file = true;
        for (size_t i = 0; i < n_decoders; i++) {
            std::string obj_id = "172.16.235.1_8080_" + std::to_string(hash_prefixes[i]) + "_body";
            decoders_vec.emplace_back(std::move(MakeUnique<FECDecoder>(FEC_CHUNK_SIZE * n_body_chunks, MemoryUsageMode::USE_MMAP, obj_id, keep_mmap_file)));
        }
    }

    // Assume the application was aborted/closed, leaving partial block data in
    // disk. Next, reload the partial blocks, as if relaunching the application.
    auto partial_block_state = AllBlkChunkStatsToJSON();
    BOOST_CHECK(partial_block_state.size() == 0);

    LoadPartialBlocks(nullptr);

    // All the previous decoders should be recovered
    partial_block_state = AllBlkChunkStatsToJSON();
    BOOST_CHECK(partial_block_state.size() == n_decoders);

    struct in_addr ipv4Addr;
    inet_pton(AF_INET, "172.16.235.1", &(ipv4Addr));
    CService peer(ipv4Addr, 8080);

    for (size_t i = 0; i < n_decoders; i++) {
        const std::pair<uint64_t, CService> hash_peer_pair = std::make_pair(hash_prefixes[i], peer);
        auto partial_block = GetPartialBlockData(hash_peer_pair);
        BOOST_CHECK(partial_block != nullptr);
        BOOST_CHECK(partial_block->blk_initialized);
        BOOST_CHECK(!partial_block->header_initialized);
        BOOST_CHECK(partial_block->header_len == 0);
        BOOST_CHECK(partial_block->blk_len == FEC_CHUNK_SIZE * n_body_chunks);
        std::string obj_id = peer.ToStringIP() + "_" + peer.ToStringPort() + "_" + std::to_string(hash_prefixes[i]) + "_body";
        BOOST_CHECK(partial_block->body_decoder.GetFileName().filename().c_str() == obj_id + "_" + std::to_string(FEC_CHUNK_SIZE * n_body_chunks));
        BOOST_CHECK(partial_block->body_decoder.GetChunkCount() == n_body_chunks);
    }

    // cleanup mapPartialBlocks
    ResetPartialBlocks();
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: Blockstream/bitcoinsatellite


text:
#include <map>
#include <string>
#include <boost/test/unit_test.hpp>
#include "json/json_spirit_writer_template.h"

#include "main.h"
#include "wallet.h"

using namespace std;
using namespace json_spirit;

// In script_tests.cpp
extern Array read_json(const std::string& filename);
extern CScript ParseScript(string s);

BOOST_AUTO_TEST_SUITE(transaction_tests)

BOOST_AUTO_TEST_CASE(tx_valid)
{
    // Read tests from test/data/tx_valid.json
    // Format is an array of arrays
    // Inner arrays are either [ "comment" ]
    // or [[[prevout hash, prevout index, prevout scriptPubKey], [input 2], ...],"], serializedTransaction, enforceP2SH
    // ... where all scripts are stringified scripts.
    Array tests = read_json("tx_valid.json");

    BOOST_FOREACH(Value& tv, tests)
    {
        Array test = tv.get_array();
        string strTest = write_string(tv, false);
        if (test[0].type() == array_type)
        {
            if (test.size() != 3 || test[1].type() != str_type || test[2].type() != bool_type)
            {
                BOOST_ERROR("Bad test: " << strTest);
                continue;
            }

            map<COutPoint, CScript> mapprevOutScriptPubKeys;
            Array inputs = test[0].get_array();
            bool fValid = true;
            BOOST_FOREACH(Value& input, inputs)
            {
                if (input.type() != array_type)
                {
                    fValid = false;
                    break;
                }
                Array vinput = input.get_array();
                if (vinput.size() != 3)
                {
                    fValid = false;
                    break;
                }

                mapprevOutScriptPubKeys[COutPoint(uint256(vinput[0].get_str()), vinput[1].get_int())] = ParseScript(vinput[2].get_str());
            }
            if (!fValid)
            {
                BOOST_ERROR("Bad test: " << strTest);
                continue;
            }

            string transaction = test[1].get_str();
            CDataStream stream(ParseHex(transaction), SER_NETWORK, PROTOCOL_VERSION);
            CTransaction tx;
            stream >> tx;

            CValidationState state;
            BOOST_CHECK_MESSAGE(CheckTransaction(tx, state), strTest);
            BOOST_CHECK(state.IsValid());

            for (unsigned int i = 0; i < tx.vin.size(); i++)
            {
                if (!mapprevOutScriptPubKeys.count(tx.vin[i].prevout))
                {
                    BOOST_ERROR("Bad test: " << strTest);
                    break;
                }

                BOOST_CHECK_MESSAGE(VerifyScript(tx.vin[i].scriptSig, mapprevOutScriptPubKeys[tx.vin[i].prevout], tx, i, test[2].get_bool() ? SCRIPT_VERIFY_P2SH : SCRIPT_VERIFY_NONE, 0), strTest);
            }
        }
    }
}

BOOST_AUTO_TEST_CASE(tx_invalid)
{
    // Read tests from test/data/tx_invalid.json
    // Format is an array of arrays
    // Inner arrays are either [ "comment" ]
    // or [[[prevout hash, prevout index, prevout scriptPubKey], [input 2], ...],"], serializedTransaction, enforceP2SH
    // ... where all scripts are stringified scripts.
    Array tests = read_json("tx_invalid.json");

    BOOST_FOREACH(Value& tv, tests)
    {
        Array test = tv.get_array();
        string strTest = write_string(tv, false);
        if (test[0].type() == array_type)
        {
            if (test.size() != 3 || test[1].type() != str_type || test[2].type() != bool_type)
            {
                BOOST_ERROR("Bad test: " << strTest);
                continue;
            }

            map<COutPoint, CScript> mapprevOutScriptPubKeys;
            Array inputs = test[0].get_array();
            bool fValid = true;
            BOOST_FOREACH(Value& input, inputs)
            {
                if (input.type() != array_type)
                {
                    fValid = false;
                    break;
                }
                Array vinput = input.get_array();
                if (vinput.size() != 3)
                {
                    fValid = false;
                    break;
                }

                mapprevOutScriptPubKeys[COutPoint(uint256(vinput[0].get_str()), vinput[1].get_int())] = ParseScript(vinput[2].get_str());
            }
            if (!fValid)
            {
                BOOST_ERROR("Bad test: " << strTest);
                continue;
            }

            string transaction = test[1].get_str();
            CDataStream stream(ParseHex(transaction), SER_NETWORK, PROTOCOL_VERSION);
            CTransaction tx;
            stream >> tx;

            CValidationState state;
            fValid = CheckTransaction(tx, state) && state.IsValid();

            for (unsigned int i = 0; i < tx.vin.size() && fValid; i++)
            {
                if (!mapprevOutScriptPubKeys.count(tx.vin[i].prevout))
                {
                    BOOST_ERROR("Bad test: " << strTest);
                    break;
                }

                fValid = VerifyScript(tx.vin[i].scriptSig, mapprevOutScriptPubKeys[tx.vin[i].prevout], tx, i, test[2].get_bool() ? SCRIPT_VERIFY_P2SH : SCRIPT_VERIFY_NONE, 0);
            }

            BOOST_CHECK_MESSAGE(!fValid, strTest);
        }
    }
}

BOOST_AUTO_TEST_CASE(basic_transaction_tests)
{
    // Random real TDC transaction (71f22c2d47fb4351c3fa369a18e85ed57e3d6e5b08524ffec877d4c92968481d)
    unsigned char ch[] = {0x01, 0x00, 0x00, 0x00, 0x01, 0x5e, 0x13, 0x60, 0xa2, 0xee, 0x21, 0x53, 0x3e, 0x4c, 0xde, 0x14, 0x17, 0x59, 0x21, 0x40, 0x9c, 0x82, 0x4a, 0xc6, 0xe5, 0x85, 0xac, 0x11, 0x7c, 0x49, 0xae, 0x45, 0x4e, 0x8b, 0xc2, 0xc9, 0x5c, 0x01, 0x00, 0x00, 0x00, 0x6a, 0x47, 0x30, 0x44, 0x02, 0x20, 0x79, 0xb3, 0x73, 0xf6, 0xe3, 0x0f, 0x8f, 0xd4, 0xf9, 0x7e, 0xd0, 0xb4, 0xf5, 0x05, 0xdb, 0x87, 0x64, 0x43, 0x28, 0x22, 0x42, 0xd2, 0x7b, 0xee, 0xa7, 0xcc, 0x79, 0xfc, 0x58, 0xb1, 0x21, 0x29, 0x02, 0x20, 0x65, 0x1b, 0xd7, 0x95, 0x99, 0x8b, 0x1b, 0x8c, 0x81, 0x9b, 0xe2, 0xaa, 0x16, 0x9f, 0x21, 0x42, 0xa9, 0x02, 0xcc, 0xf0, 0x28, 0x07, 0x42, 0xa5, 0xa6, 0x72, 0x23, 0xb5, 0x8a, 0xb4, 0x0f, 0x95, 0x01, 0x21, 0x02, 0x29, 0x1f, 0x79, 0x2f, 0x0d, 0x40, 0x14, 0x1d, 0x44, 0xb2, 0x3f, 0x60, 0x2e, 0x35, 0x0c, 0xd3, 0xc0, 0x27, 0xb8, 0x73, 0x9f, 0x21, 0x30, 0x5f, 0x58, 0xd6, 0x08, 0x98, 0x33, 0xf6, 0x78, 0x56, 0xff, 0xff, 0xff, 0xff, 0x02, 0x70, 0xaa, 0xf0, 0x08, 0x00, 0x00, 0x00, 0x00, 0x19, 0x76, 0xa9, 0x14, 0x78, 0x47, 0x8e, 0x86, 0xd3, 0xcd, 0xc2, 0x15, 0xd3, 0xbc, 0xe2, 0x3c, 0x7f, 0xd3, 0x5f, 0x63, 0x39, 0x78, 0xbc, 0xd7, 0x88, 0xac, 0x80, 0xf0, 0xfa, 0x02, 0x00, 0x00, 0x00, 0x00, 0x19, 0x76, 0xa9, 0x14, 0xd6, 0x24, 0xd6, 0x5d, 0x22, 0x22, 0xa5, 0xff, 0xca, 0x94, 0x5b, 0xb0, 0x5b, 0x2d, 0xf1, 0xc8, 0x2a, 0xa8, 0xf0, 0x97, 0x88, 0xac, 0xe1, 0x9e, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};

    vector<unsigned char> vch(ch, ch + sizeof(ch) -1);
    CDataStream stream(vch, SER_DISK, CLIENT_VERSION);
    CTransaction tx;
    stream >> tx;
    CValidationState state;
    BOOST_CHECK_MESSAGE(CheckTransaction(tx, state) && state.IsValid(), "Simple deserialized transaction should be valid.");

    // Check that duplicate txins fail
    tx.vin.push_back(tx.vin[0]);
    BOOST_CHECK_MESSAGE(!CheckTransaction(tx, state) || !state.IsValid(), "Transaction with duplicate txins should be invalid.");
}

//
// Helper: create two dummy transactions, each with
// two outputs.  The first has 11 and 50 CENT outputs
// paid to a TX_PUBKEY, the second 21 and 22 CENT outputs
// paid to a TX_PUBKEYHASH.
//
static std::vector<CTransaction>
SetupDummyInputs(CBasicKeyStore& keystoreRet, CCoinsView & coinsRet)
{
    std::vector<CTransaction> dummyTransactions;
    dummyTransactions.resize(2);

    // Add some keys to the keystore:
    CKey key[4];
    for (int i = 0; i < 4; i++)
    {
        key[i].MakeNewKey(i % 2);
        keystoreRet.AddKey(key[i]);
    }

    // Create some dummy input transactions
    dummyTransactions[0].vout.resize(2);
    dummyTransactions[0].vout[0].nValue = 11*CENT;
    dummyTransactions[0].vout[0].scriptPubKey << key[0].GetPubKey() << OP_CHECKSIG;
    dummyTransactions[0].vout[1].nValue = 50*CENT;
    dummyTransactions[0].vout[1].scriptPubKey << key[1].GetPubKey() << OP_CHECKSIG;
    coinsRet.SetCoins(dummyTransactions[0].GetHash(), CCoins(dummyTransactions[0], 0));

    dummyTransactions[1].vout.resize(2);
    dummyTransactions[1].vout[0].nValue = 21*CENT;
    dummyTransactions[1].vout[0].scriptPubKey.SetDestination(key[2].GetPubKey().GetID());
    dummyTransactions[1].vout[1].nValue = 22*CENT;
    dummyTransactions[1].vout[1].scriptPubKey.SetDestination(key[3].GetPubKey().GetID());
    coinsRet.SetCoins(dummyTransactions[1].GetHash(), CCoins(dummyTransactions[1], 0));

    return dummyTransactions;
}

BOOST_AUTO_TEST_CASE(test_Get)
{
    CBasicKeyStore keystore;
    CCoinsView coinsDummy;
    CCoinsViewCache coins(coinsDummy);
    std::vector<CTransaction> dummyTransactions = SetupDummyInputs(keystore, coins);

    CTransaction t1;
    t1.vin.resize(3);
    t1.vin[0].prevout.hash = dummyTransactions[0].GetHash();
    t1.vin[0].prevout.n = 1;
    t1.vin[0].scriptSig << std::vector<unsigned char>(65, 0);
    t1.vin[1].prevout.hash = dummyTransactions[1].GetHash();
    t1.vin[1].prevout.n = 0;
    t1.vin[1].scriptSig << std::vector<unsigned char>(65, 0) << std::vector<unsigned char>(33, 4);
    t1.vin[2].prevout.hash = dummyTransactions[1].GetHash();
    t1.vin[2].prevout.n = 1;
    t1.vin[2].scriptSig << std::vector<unsigned char>(65, 0) << std::vector<unsigned char>(33, 4);
    t1.vout.resize(2);
    t1.vout[0].nValue = 90*CENT;
    t1.vout[0].scriptPubKey << OP_1;

    BOOST_CHECK(AreInputsStandard(t1, coins));
    BOOST_CHECK_EQUAL(coins.GetValueIn(t1), (50+21+22)*CENT);

    // Adding extra junk to the scriptSig should make it non-standard:
    t1.vin[0].scriptSig << OP_11;
    BOOST_CHECK(!AreInputsStandard(t1, coins));

    // ... as should not having enough:
    t1.vin[0].scriptSig = CScript();
    BOOST_CHECK(!AreInputsStandard(t1, coins));
}

BOOST_AUTO_TEST_CASE(test_IsStandard)
{
    CBasicKeyStore keystore;
    CCoinsView coinsDummy;
    CCoinsViewCache coins(coinsDummy);
    std::vector<CTransaction> dummyTransactions = SetupDummyInputs(keystore, coins);

    CTransaction t;
    t.vin.resize(1);
    t.vin[0].prevout.hash = dummyTransactions[0].GetHash();
    t.vin[0].prevout.n = 1;
    t.vin[0].scriptSig << std::vector<unsigned char>(65, 0);
    t.vout.resize(1);
    t.vout[0].nValue = 90*CENT;
    CKey key;
    key.MakeNewKey(true);
    t.vout[0].scriptPubKey.SetDestination(key.GetPubKey().GetID());

    string reason;
    BOOST_CHECK(IsStandardTx(t, reason));

    t.vout[0].nValue = 5011; // dust
    BOOST_CHECK(!IsStandardTx(t, reason));

    t.vout[0].nValue = 6011; // not dust
    BOOST_CHECK(IsStandardTx(t, reason));

    t.vout[0].scriptPubKey = CScript() << OP_1;
    BOOST_CHECK(!IsStandardTx(t, reason));
}

BOOST_AUTO_TEST_SUITE_END()


text:
//            Copyright Fernando Vilas 2012.
//     Based on stoer_wagner_test.cpp by Daniel Trebbien.
// Distributed under the Boost Software License, Version 1.0.
//   (See accompanying file LICENSE_1_0.txt or the copy at
//         http://www.boost.org/LICENSE_1_0.txt)

#include <fstream>
#include <iostream>
#include <map>
#include <vector>
#include <string>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/connected_components.hpp>
#include <boost/graph/exception.hpp>
#include <boost/graph/graph_traits.hpp>
#include <boost/graph/read_dimacs.hpp>
#include <boost/graph/maximum_adjacency_search.hpp>
#include <boost/graph/visitors.hpp>
#include <boost/graph/property_maps/constant_property_map.hpp>
#include <boost/property_map/property_map.hpp>
#include <boost/test/unit_test.hpp>
#include <boost/tuple/tuple.hpp>
#include <boost/tuple/tuple_comparison.hpp>
#include <boost/tuple/tuple_io.hpp>

#include <boost/graph/iteration_macros.hpp>

typedef boost::adjacency_list< boost::vecS, boost::vecS, boost::undirectedS,
    boost::no_property, boost::property< boost::edge_weight_t, int > >
    undirected_graph;
typedef boost::property_map< undirected_graph, boost::edge_weight_t >::type
    weight_map_type;
typedef boost::property_traits< weight_map_type >::value_type weight_type;

typedef boost::adjacency_list< boost::vecS, boost::vecS, boost::undirectedS >
    undirected_unweighted_graph;

std::string test_dir;

boost::unit_test::test_suite* init_unit_test_suite(int argc, char* argv[])
{
    if (argc != 2)
    {
        std::cerr << "Usage: " << argv[0] << " path-to-libs-graph-test"
                  << std::endl;
        throw boost::unit_test::framework::setup_error(
            "Invalid command line arguments");
    }
    test_dir = argv[1];
    return 0;
}

struct edge_t
{
    unsigned long first;
    unsigned long second;
};

template < typename Graph, typename KeyedUpdatablePriorityQueue >
class mas_edge_connectivity_visitor : public boost::default_mas_visitor
{
public:
    typedef typename boost::graph_traits< Graph >::vertex_descriptor
        vertex_descriptor;
    typedef typename KeyedUpdatablePriorityQueue::key_type weight_type;
#if 0
    mas_edge_connectivity_visitor(const mas_edge_connectivity_visitor<Graph, KeyedUpdatablePriorityQueue>& r)
      : m_pq(r.m_pq), m_curr(r.m_curr), m_prev(r.m_prev),
        m_reach_weight(r.m_reach_weight) {
          BOOST_TEST_MESSAGE( "COPY CTOR" );
        }
#endif
    explicit mas_edge_connectivity_visitor(KeyedUpdatablePriorityQueue& pq)
    : m_pq(pq)
    , m_curr(new vertex_descriptor(0))
    , m_prev(new vertex_descriptor(0))
    , m_reach_weight(new weight_type(0))
    {
        //    BOOST_TEST_MESSAGE( "CTOR" );
    }

    void clear()
    {
        *m_curr = 0;
        *m_prev = 0;
        *m_reach_weight = 0;
    }

    // template <typename Vertex> //, typename Graph>
    // void start_vertex(Vertex u, const Graph& g) {
    void start_vertex(vertex_descriptor u, const Graph& g)
    {
        *m_prev = *m_curr;
        *m_curr = u;
        // BOOST_TEST_MESSAGE( "Initializing Vertex(weight): " << u << "(" <<
        // *m_reach_weight << ")" );
        *m_reach_weight = get(m_pq.keys(), u);
    }

    vertex_descriptor curr() const { return *m_curr; }
    vertex_descriptor prev() const { return *m_prev; }
    weight_type reach_weight() const { return *m_reach_weight; }

private:
    const KeyedUpdatablePriorityQueue& m_pq;
    boost::shared_ptr< vertex_descriptor > m_curr, m_prev;
    boost::shared_ptr< weight_type > m_reach_weight;
};

// the example from Stoer & Wagner (1997)
// Check various implementations of the ArgPack where
// the weights are provided in it, and one case where
// they are not.
BOOST_AUTO_TEST_CASE(test0)
{
    typedef boost::graph_traits< undirected_graph >::vertex_descriptor
        vertex_descriptor;
    typedef boost::graph_traits< undirected_graph >::edge_descriptor
        edge_descriptor;

    edge_t edges[] = { { 0, 1 }, { 1, 2 }, { 2, 3 }, { 0, 4 }, { 1, 4 },
        { 1, 5 }, { 2, 6 }, { 3, 6 }, { 3, 7 }, { 4, 5 }, { 5, 6 }, { 6, 7 } };
    weight_type ws[] = { 2, 3, 4, 3, 2, 2, 2, 2, 2, 3, 1, 3 };
    undirected_graph g(edges, edges + 12, ws, 8, 12);

    weight_map_type weights = get(boost::edge_weight, g);

    std::map< vertex_descriptor, vertex_descriptor > assignment;
    boost::associative_property_map<
        std::map< vertex_descriptor, vertex_descriptor > >
        assignments(assignment);

    typedef boost::shared_array_property_map< weight_type,
        boost::property_map< undirected_graph,
            boost::vertex_index_t >::const_type >
        distances_type;
    distances_type distances = boost::make_shared_array_property_map(
        num_vertices(g), weight_type(0), get(boost::vertex_index, g));
    typedef std::vector< vertex_descriptor >::size_type index_in_heap_type;
    typedef boost::shared_array_property_map< index_in_heap_type,
        boost::property_map< undirected_graph,
            boost::vertex_index_t >::const_type >
        indicesInHeap_type;
    indicesInHeap_type indicesInHeap = boost::make_shared_array_property_map(
        num_vertices(g), index_in_heap_type(-1), get(boost::vertex_index, g));
    boost::d_ary_heap_indirect< vertex_descriptor, 22, indicesInHeap_type,
        distances_type, std::greater< weight_type > >
        pq(distances, indicesInHeap);

    mas_edge_connectivity_visitor< undirected_graph,
        boost::d_ary_heap_indirect< vertex_descriptor, 22, indicesInHeap_type,
            distances_type, std::greater< weight_type > > >
        test_vis(pq);

    boost::maximum_adjacency_search(g,
        boost::weight_map(weights)
            .visitor(test_vis)
            .root_vertex(*vertices(g).first)
            .vertex_assignment_map(assignments)
            .max_priority_queue(pq));

    BOOST_CHECK_EQUAL(test_vis.curr(), vertex_descriptor(7));
    BOOST_CHECK_EQUAL(test_vis.prev(), vertex_descriptor(6));
    BOOST_CHECK_EQUAL(test_vis.reach_weight(), 5);

    test_vis.clear();
    boost::maximum_adjacency_search(g,
        boost::weight_map(weights)
            .visitor(test_vis)
            .root_vertex(*vertices(g).first)
            .max_priority_queue(pq));

    BOOST_CHECK_EQUAL(test_vis.curr(), vertex_descriptor(7));
    BOOST_CHECK_EQUAL(test_vis.prev(), vertex_descriptor(6));
    BOOST_CHECK_EQUAL(test_vis.reach_weight(), 5);

    test_vis.clear();
    boost::maximum_adjacency_search(
        g, boost::weight_map(weights).visitor(test_vis).max_priority_queue(pq));

    BOOST_CHECK_EQUAL(test_vis.curr(), vertex_descriptor(7));
    BOOST_CHECK_EQUAL(test_vis.prev(), vertex_descriptor(6));
    BOOST_CHECK_EQUAL(test_vis.reach_weight(), 5);

    boost::maximum_adjacency_search(g,
        boost::weight_map(weights).visitor(
            boost::make_mas_visitor(boost::null_visitor())));

    boost::maximum_adjacency_search(g, boost::weight_map(weights));

    boost::maximum_adjacency_search(g, boost::root_vertex(*vertices(g).first));

    test_vis.clear();
    boost::maximum_adjacency_search(g,
        boost::weight_map(
            boost::make_constant_property< edge_descriptor >(weight_type(1)))
            .visitor(test_vis)
            .max_priority_queue(pq));
    BOOST_CHECK_EQUAL(test_vis.curr(), vertex_descriptor(7));
    BOOST_CHECK_EQUAL(test_vis.prev(), vertex_descriptor(3));
    BOOST_CHECK_EQUAL(test_vis.reach_weight(), 2);
}

// Check the unweighted case
// with and without providing a weight_map
BOOST_AUTO_TEST_CASE(test1)
{
    typedef boost::graph_traits<
        undirected_unweighted_graph >::vertex_descriptor vertex_descriptor;
    typedef boost::graph_traits< undirected_unweighted_graph >::edge_descriptor
        edge_descriptor;

    edge_t edge_list[] = { { 0, 1 }, { 1, 2 }, { 2, 3 }, { 0, 4 }, { 1, 4 },
        { 1, 5 }, { 2, 6 }, { 3, 6 }, { 3, 7 }, { 4, 5 }, { 5, 6 }, { 6, 7 } };
    undirected_unweighted_graph g(edge_list, edge_list + 12, 8);

    std::map< vertex_descriptor, vertex_descriptor > assignment;
    boost::associative_property_map<
        std::map< vertex_descriptor, vertex_descriptor > >
        assignments(assignment);

    typedef unsigned weight_type;
    typedef boost::shared_array_property_map< weight_type,
        boost::property_map< undirected_graph,
            boost::vertex_index_t >::const_type >
        distances_type;
    distances_type distances = boost::make_shared_array_property_map(
        num_vertices(g), weight_type(0), get(boost::vertex_index, g));
    typedef std::vector< vertex_descriptor >::size_type index_in_heap_type;
    typedef boost::shared_array_property_map< index_in_heap_type,
        boost::property_map< undirected_graph,
            boost::vertex_index_t >::const_type >
        indicesInHeap_type;
    indicesInHeap_type indicesInHeap = boost::make_shared_array_property_map(
        num_vertices(g), index_in_heap_type(-1), get(boost::vertex_index, g));
    boost::d_ary_heap_indirect< vertex_descriptor, 22, indicesInHeap_type,
        distances_type, std::greater< weight_type > >
        pq(distances, indicesInHeap);

    mas_edge_connectivity_visitor< undirected_unweighted_graph,
        boost::d_ary_heap_indirect< vertex_descriptor, 22, indicesInHeap_type,
            distances_type, std::greater< weight_type > > >
        test_vis(pq);

    boost::maximum_adjacency_search(g,
        boost::weight_map(
            boost::make_constant_property< edge_descriptor >(weight_type(1)))
            .visitor(test_vis)
            .max_priority_queue(pq));

    BOOST_CHECK_EQUAL(test_vis.curr(), vertex_descriptor(7));
    BOOST_CHECK_EQUAL(test_vis.prev(), vertex_descriptor(3));
    BOOST_CHECK_EQUAL(test_vis.reach_weight(), weight_type(2));

    weight_type ws[] = { 2, 3, 4, 3, 2, 2, 2, 2, 2, 3, 1, 3 };
    std::map< edge_descriptor, weight_type > wm;

    weight_type i = 0;
    BGL_FORALL_EDGES(e, g, undirected_unweighted_graph)
    {
        wm[e] = ws[i];
        ++i;
    }
    boost::associative_property_map< std::map< edge_descriptor, weight_type > >
        ws_map(wm);

    boost::maximum_adjacency_search(
        g, boost::weight_map(ws_map).visitor(test_vis).max_priority_queue(pq));
    BOOST_CHECK_EQUAL(test_vis.curr(), vertex_descriptor(7));
    BOOST_CHECK_EQUAL(test_vis.prev(), vertex_descriptor(6));
    BOOST_CHECK_EQUAL(test_vis.reach_weight(), weight_type(5));
}

#include <boost/graph/iteration_macros_undef.hpp>

max_issues_repo_name: qingkouwei/mediaones


text:
#include "dht_impl.hpp"

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

#include <albert/dht/config.hpp>
#include <albert/dht/dht.hpp>
#include <albert/dht/routing_table/routing_table.hpp>
#include <albert/log/log.hpp>
#include <albert/utils/utils.hpp>

namespace albert::dht {

void DHTImpl::handle_report_stat_timer(const Timer::Cancel &cancel) {
  if (dht_->config_.debug) {
    LOG(info) << "Main routing table debug mode enabled";
    dht_->main_routing_table_->stat();
    LOG(info) << "self NodeInfo " << dht_->self_info_.to_string();
    LOG(info) << "total ping query sent: " << dht_->total_ping_query_sent_;
    LOG(info) << "total ping query received: " << dht_->total_ping_query_received_;
    LOG(info) << "total ping response received: " << dht_->total_ping_response_received_;
    for (auto &rt : dht_->routing_tables_) {
      LOG(info) << "Routing table '" + rt->name() + "' debug mode enabled";
      rt->stat();
      LOG(info) << "self NodeInfo " << dht_->self_info_.to_string();
      LOG(info) << "total ping query sent: " << dht_->total_ping_query_sent_;
      LOG(info) << "total ping query received: " << dht_->total_ping_query_received_;
      LOG(info) << "total ping response received: " << dht_->total_ping_response_received_;
    }
//    std::stringstream black_list_s;
//    for (auto &item : dht_->black_list_) {
//      uint32_t ip = 0;
//      uint16_t port = 0;
//      std::tie(ip, port) = item;
//      black_list_s << boost::asio::ip::address_v4(ip) << ":" << port << " ";
//    }
    LOG(info) << "black list " << dht_->blacklist_.size() << " in total";
  } else {
    LOG(info) << "main routing table "
              << dht_->main_routing_table_->max_prefix_length() << " "
              << dht_->main_routing_table_->good_node_count() << " "
              << dht_->main_routing_table_->known_node_count() << " "
              << dht_->main_routing_table_->bucket_count() << " "
              << "banned " << dht_->blacklist_.size() << " "
              << "mem " << utils::pretty_size(dht_->main_routing_table_->memory_size()) << " "
              << "tx: (n,mem) " << dht_->transaction_manager.size() << "," << utils::pretty_size(dht_->transaction_manager.memory_size())
          ;
    for (auto &rt : dht_->routing_tables_) {
      if (rt->name() != dht_->main_routing_table_->name()) {
        LOG(info) << "Routing table '" << rt->name() << "' "
                  << rt->max_prefix_length() << " "
                  << rt->good_node_count() << " "
                  << rt->known_node_count() << " "
                  << rt->bucket_count();
      }
    }
  }
  LOG(debug) << "DHT RPSThrottler: " << throttler_.stat();
}
void DHTImpl::handle_expand_route_timer(const Timer::Cancel &cancel) {
  for (auto &rt : dht_->routing_tables_) {
    if (!rt->is_full()) {
      LOG(debug) << "sending find node query and find_self()...";
      auto targets = rt->select_expand_route_targets();
      for (auto &item : targets) {
        auto &node = std::get<0>(item);
        auto &target_id = std::get<1>(item);

        udp::endpoint ep{boost::asio::ip::make_address_v4(node.ip()), node.port()};
        find_node(*rt, ep, target_id);
        find_self(*rt, ep);
      }
    }
  }
}

void DHTImpl::handle_refresh_nodes_timer(const Timer::Cancel &cancel) {
  dht_->blacklist_.gc();

  for (auto &rt : dht_->routing_tables_) {
    rt->gc();

    // try refreshing questionable nodes
    size_t n = 0;
    rt->iterate_nodes([this, &n](const routing_table::Entry &node) {
      if (!node.is_good() && !node.is_bad()) {
        // FIXME: const_cast
        if (const_cast<routing_table::Entry&>(node).require_response_now()) {
          ping(krpc::NodeInfo{node.id(), node.ip(), node.port()});
          n++;
        }
      }
    });
  }

  if (dht_->main_routing_table_->known_node_count() == 0) {
    bootstrap_routing_table(*dht_->main_routing_table_);
  }

  dht_->transaction_manager.gc();
}

}


text:
#include <boost/test/auto_unit_test.hpp>

#include <test/testsuite.hh>
#include <typelib/pluginmanager.hh>

using namespace Typelib;

BOOST_AUTO_TEST_CASE( test_manager )
{
    PluginManager::self manager;
    BOOST_REQUIRE_THROW(manager->importer("BLAH"), PluginNotFound);
}

ext: cc

max_stars_repo_name: meyerj/typelib

max_issues_repo_name: meyerj/typelib

max_forks_repo_name: meyerj/typelib


text:
//==============================================================================
//         Copyright 2003 - 2012   LASMEA UMR 6602 CNRS/Univ. Clermont II
//         Copyright 2009 - 2012   LRI    UMR 8623 CNRS/Univ Paris Sud XI
//
//          Distributed under the Boost Software License, Version 1.0.
//                 See accompanying file LICENSE.txt or copy at
//                     http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
#define NT2_UNIT_MODULE "nt2::zeros function"

#include <nt2/table.hpp>
#include <nt2/include/functions/size.hpp>
#include <nt2/include/functions/zeros.hpp>

#include <nt2/sdk/unit/module.hpp>
#include <nt2/sdk/unit/tests/basic.hpp>
#include <nt2/sdk/unit/tests/relation.hpp>
#include <nt2/sdk/unit/tests/type_expr.hpp>
#include <nt2/sdk/unit/tests/exceptions.hpp>
#include <boost/dispatch/meta/nth_hierarchy.hpp>

NT2_TEST_CASE( hierarchy )
{
  using boost::mpl::_;
  using boost::mpl::int_;
  using boost::dispatch::meta::nth_hierarchy;

  NT2_TEST_EXPR_TYPE( (nt2::tag::Zero() )
                    , (nth_hierarchy<_,int_<0> >)
                    , (nt2::tag::Zero)
                    );

  NT2_TEST_EXPR_TYPE( (nt2::tag::Zero() )
                    , (nth_hierarchy<_,int_<1> >)
                    , (nt2::ext::pure_constant_< nt2::tag::Zero >
                      )
                    );

  NT2_TEST_EXPR_TYPE( (nt2::tag::Zero() )
                    , (nth_hierarchy<_,int_<2> >)
                    , (nt2::ext::constant_< nt2::tag::Zero >
                      )
                    );

  NT2_TEST_EXPR_TYPE( (nt2::tag::Zero() )
                    , (nth_hierarchy<_,int_<3> >)
                    , (nt2::ext::elementwise_<nt2::tag::Zero>)
                    );

  NT2_TEST_EXPR_TYPE( (nt2::tag::Zero() )
                    , (nth_hierarchy<_,int_<4> >)
                    , (nt2::ext::unspecified_<nt2::tag::Zero>)
                    );
}

NT2_TEST_CASE_TPL( _0d_typed, NT2_TYPES )
{
  using boost::mpl::_;
  using nt2::meta::as_;
  using nt2::meta::value_type_;
  nt2::table< T > x1 = nt2::zeros( as_<T>() );

  NT2_TEST_EXPR_TYPE( nt2::zeros( as_<T>() ), (value_type_<_>), (T) );
  NT2_TEST_EXPR_TYPE( x1, (value_type_<_>), (T) );
  NT2_TEST_EQUAL( nt2::extent(x1), nt2::of_size(1) );
  NT2_TEST_EQUAL( x1(1), nt2::Zero<T>() );
}

NT2_TEST_CASE( untyped_square )
{
  using boost::mpl::_;
  using nt2::meta::value_type_;

  nt2::table< double > ref( nt2::of_size(3,3) );
  for(int i=1;i<= 3;++i)
    for(int j=1;j<= 3;++j)
      ref(i,j) = nt2::Zero<double>();

  nt2::table< double > x0 = nt2::zeros(3);

  NT2_TEST_EXPR_TYPE( (nt2::zeros( 3 )), (value_type_<_>), (double) );
  NT2_TEST_EQUAL( nt2::extent(x0), nt2::of_size(3,3) );
  NT2_TEST_EQUAL( x0,ref );
}

NT2_TEST_CASE( nd_untyped )
{
  using boost::mpl::_;
  using nt2::meta::value_type_;

  nt2::table< double > ref( nt2::of_size(8,4) );
  for(int j=1;j<= 4;++j)
    for(int i=1;i<= 8;++i)
      ref(i,j) = nt2::Zero<double>();

  nt2::table< double > x1 = nt2::zeros(8, 4);

  NT2_TEST_EXPR_TYPE( (nt2::zeros(8,4)), (value_type_<_>), (double) );
  NT2_TEST_EQUAL( nt2::extent(x1), nt2::of_size(8,4) );
  NT2_TEST_EQUAL(x1,ref);

  ref.resize( nt2::of_size(1,4) );
    for(int j=1;j<= 4;++j)
      ref(1,j) = nt2::Zero<double>();

  nt2::table< double > x2 = nt2::zeros(1, 4);
  NT2_TEST_EQUAL( nt2::extent(x2), nt2::of_size(1,4) );
  NT2_TEST_EQUAL(x2,ref);

  ref.resize( nt2::of_size(7,1) );
    for(int i=1;i<= 7;++i)
      ref(i,1) = nt2::Zero<double>();

  nt2::table< double > x3 = nt2::zeros(7,1);
  NT2_TEST_EQUAL( nt2::extent(x3), nt2::of_size(7,1) );
  NT2_TEST_EQUAL(x3,ref);
}

NT2_TEST_CASE_TPL( nd_typed, NT2_TYPES )
{
  using boost::mpl::_;
  using nt2::meta::as_;
  using nt2::meta::value_type_;

  nt2::table< T > ref( nt2::of_size(8,8) );
  for(int j=1;j<= 8;++j)
    for(int i=1;i<= 8;++i)
      ref(i,j) = nt2::Zero<T>();

  nt2::table< T > x1 = nt2::zeros(nt2::of_size(8, 8), as_<T>() );

  NT2_TEST_EXPR_TYPE( (nt2::zeros( nt2::of_size(8, 8), as_<T>() )), (value_type_<_>), (T) );
  NT2_TEST_EQUAL(x1,ref);

  nt2::table< T > x2 = nt2::zeros(8, 8, as_<T>() );
  NT2_TEST_EQUAL(x2,ref);

  nt2::table< T > x3 = nt2::zeros(8, as_<T>() );
  NT2_TEST_EQUAL(x3,ref);
}

NT2_TEST_CASE( expr )
{
  using boost::mpl::_;
  using nt2::meta::value_type_;

  nt2::table< double > ref( nt2::of_size(8,8) );
  for(int j=1;j<= 8;++j)
    for(int i=1;i<= 8;++i)
      ref(i,j) = nt2::Zero<double>();

  nt2::table<int> t1(nt2::of_size(1) );
  t1(1) = 8;

  nt2::table< double > x1 = nt2::zeros( t1 );

  NT2_TEST_EXPR_TYPE( (nt2::zeros( t1 )), (value_type_<_>), (double) );
  NT2_TEST_EQUAL(x1,ref);

  nt2::table<int> t2(nt2::of_size(1,2) );
  t2(1) = 4;
  t2(2) = 3;

  ref.resize( nt2::of_size(4,3) );
  for(int j=1;j<= 3;++j)
    for(int i=1;i<= 4;++i)
      ref(i,j) = nt2::Zero<double>();

  nt2::table< double > x2 = nt2::zeros( t2 );
  NT2_TEST_EQUAL(x2,ref);

  NT2_TEST_ASSERT( x1 = nt2::zeros(x2) );
}

NT2_TEST_CASE_TPL( typed_expr, NT2_TYPES )
{
  using boost::mpl::_;
  using nt2::meta::as_;
  using nt2::meta::value_type_;

  nt2::table< T > ref( nt2::of_size(8,8) );
  for(int j=1;j<= 8;++j)
    for(int i=1;i<= 8;++i)
      ref(i,j) = nt2::Zero<T>();

  nt2::table<int> t1(nt2::of_size(1) );
  t1(1) = 8;

  nt2::table< T > x1 = nt2::zeros( t1, as_<T>() );

  NT2_TEST_EXPR_TYPE( (nt2::zeros( t1, as_<T>() )), (value_type_<_>), (T) );
  NT2_TEST_EQUAL(x1,ref);

  nt2::table<int> t2(nt2::of_size(1,2) );
  t2(1) = 4;
  t2(2) = 3;

  ref.resize( nt2::of_size(4,3) );
  for(int j=1;j<= 3;++j)
    for(int i=1;i<= 4;++i)
      ref(i,j) = nt2::Zero<T>();

  nt2::table< T > x2 = nt2::zeros( t2, as_<T>() );
  NT2_TEST_EQUAL(x2,ref);

  NT2_TEST_ASSERT( x1 = nt2::zeros(x2, as_<T>()) );
}