text:
#include <iostream>
#include <memory>
#include <chrono>
#include <stdio.h>
#include <cuda_runtime.h>
#include <caffe/caffe.hpp>
#include <caffe/layers/memory_data_layer.hpp>
#include <boost/timer.hpp>

using namespace caffe;
using namespace std;

int main(int argc, char** argv)
{
    FLAGS_alsologtostderr = 1;
    GlobalInit(&argc, &argv);

    Caffe::set_mode(Caffe::GPU);

    // Layer1 : [intput1]
    caffe::LayerParameter data_layer_param1;
    caffe::MemoryDataParameter &memory_data_param1 = (*data_layer_param1.mutable_memory_data_param());
    data_layer_param1.set_name("input1");
    data_layer_param1.set_type("MemoryData");
    data_layer_param1.add_top("data");
    data_layer_param1.add_top("dummy_label1");
    memory_data_param1.set_batch_size(1);
    memory_data_param1.set_channels(2);
    memory_data_param1.set_height(1);
    memory_data_param1.set_width(1);
    printf("CAFFE Layer1 initialized\n");

    // Layer2 : [intput2]
    caffe::LayerParameter data_layer_param2;
    caffe::MemoryDataParameter &memory_data_param2 = (*data_layer_param2.mutable_memory_data_param());
    data_layer_param2.set_name("input2");
    data_layer_param2.set_type("MemoryData");
    data_layer_param2.add_top("label");
    data_layer_param2.add_top("dummy_label2");
    memory_data_param2.set_batch_size(1);
    memory_data_param2.set_channels(2);
    memory_data_param2.set_height(1);
    memory_data_param2.set_width(1);
    printf("CAFFE Layer2 initialized\n");

    // Layer3 : [res]
    caffe::LayerParameter res_layer_param;
    caffe::ReshapeParameter &res_param = (*res_layer_param.mutable_reshape_param());
    res_layer_param.set_name("res");
    res_layer_param.set_type("Reshape");
    res_layer_param.add_bottom("data");
    res_layer_param.add_top("datax");
    caffe::BlobShape bs1;
    bs1.add_dim(1);
    bs1.add_dim(2);
    bs1.add_dim(1);
    bs1.add_dim(1);
    (*res_param.mutable_shape()) = bs1;
    printf("CAFFE Layer3 initialized\n");

    // Layer4 : [resx]
    caffe::LayerParameter resx_layer_param;
    caffe::ReshapeParameter &resx_param = (*resx_layer_param.mutable_reshape_param());
    resx_layer_param.set_name("resx");
    resx_layer_param.set_type("Reshape");
    resx_layer_param.add_bottom("label");
    resx_layer_param.add_top("labelx");
    caffe::BlobShape bs2;
    bs2.add_dim(1);
    bs2.add_dim(2);
    (*resx_param.mutable_shape()) = bs2;
    printf("CAFFE Layer4 initialized\n");

    // Layer5 : [rnn]
    caffe::LayerParameter rnn_layer_param;
    caffe::RecurrentParameter &rnn_param = (*rnn_layer_param.mutable_recurrent_param());
    caffe::FillerParameter &rnn_weight_filler_param = (*rnn_param.mutable_weight_filler());
    caffe::FillerParameter &rnn_bias_filler_param = (*rnn_param.mutable_bias_filler());
    rnn_layer_param.set_name("rnn");
    rnn_layer_param.set_type("LSTM");
    rnn_layer_param.add_bottom("data");
    rnn_layer_param.add_bottom("labelx");
    rnn_layer_param.add_top("rnn1");
    rnn_param.set_num_output(2);
    rnn_weight_filler_param.set_type("uniform");
    rnn_weight_filler_param.set_min(-0.08);
    rnn_weight_filler_param.set_max(0.08);
    rnn_bias_filler_param.set_type("constant");
    rnn_bias_filler_param.set_value(0);
    printf("CAFFE Layer5 initialized\n");

    // Layer6 : [ip1]
    caffe::LayerParameter ip_layer_param1;
    caffe::InnerProductParameter &ip_param1 = (*ip_layer_param1.mutable_inner_product_param());
    caffe::FillerParameter &ip_weight_filler1 = (*ip_param1.mutable_weight_filler());
    caffe::FillerParameter &ip_bias_filler1 = (*ip_param1.mutable_bias_filler());
    ip_layer_param1.set_name("ip1");
    ip_layer_param1.set_type("InnerProduct");
    (*ip_layer_param1.add_bottom()) = "rnn1";
    (*ip_layer_param1.add_top()) = "ip1";
    ip_param1.set_num_output(30);
    ip_weight_filler1.set_type("xavier");
    ip_bias_filler1.set_type("constant");
    printf("CAFFE Layer6 initialized\n");

    // Layer 7 : [relu1]
    caffe::LayerParameter relu_layer_param1;
    relu_layer_param1.set_name("relu1");
    relu_layer_param1.set_type("ReLU");
    (*relu_layer_param1.add_bottom()) = "ip1";
    (*relu_layer_param1.add_top()) = "ip1";
    printf("CAFFE Layer7 initialized\n");

    // Layer 8 : [ip2]
    caffe::LayerParameter ip_layer_param2;
    caffe::InnerProductParameter &ip_param2 = (*ip_layer_param2.mutable_inner_product_param());
    caffe::FillerParameter &ip_weight_filler2 = (*ip_param2.mutable_weight_filler());
    caffe::FillerParameter &ip_bias_filler2 = (*ip_param2.mutable_bias_filler());
    ip_layer_param2.set_name("ip2");
    ip_layer_param2.set_type("InnerProduct");
    (*ip_layer_param2.add_bottom()) = "ip1";
    (*ip_layer_param2.add_top()) = "ip2";
    ip_param2.set_num_output(2);
    ip_weight_filler2.set_type("xavier");
    ip_bias_filler2.set_type("constant");
    printf("CAFFE Layer8 initialized\n");

    // Layer 9 : [slicer_label]
    caffe::LayerParameter slicer_layer_param;
    caffe::SliceParameter &slicer_param = (*slicer_layer_param.mutable_slice_param());
    slicer_layer_param.set_name("slicer_label");
    slicer_layer_param.set_type("Slice");
    (*slicer_layer_param.add_bottom()) = "label";
    (*slicer_layer_param.add_top()) = "label1";
    (*slicer_layer_param.add_top()) = "label2";
    slicer_param.set_axis(1);
    slicer_param.add_slice_point(1);
    printf("CAFFE Layer9 initialized\n");

    // Layer 10 : [loss]
    caffe::LayerParameter loss_layer_param;
    caffe::NetStateRule nsr3;
    loss_layer_param.set_name("loss");
    loss_layer_param.set_type("SoftmaxWithLoss");
    (*loss_layer_param.add_bottom()) = "ip2";
    (*loss_layer_param.add_bottom()) = "label1";
    (*loss_layer_param.add_top()) = "loss";
    nsr3.set_phase(TRAIN);
    (*loss_layer_param.add_include()) = nsr3;
    printf("CAFFE Layer10 initialized\n");

    // Layer 11 : [accuracy]
    caffe::LayerParameter accuracy_layer_param;
    caffe::NetStateRule nsr4;
    accuracy_layer_param.set_name("accuracy");
    accuracy_layer_param.set_type("Accuracy");
    (*accuracy_layer_param.add_bottom()) = "ip2";
    (*accuracy_layer_param.add_bottom()) = "label1";
    (*accuracy_layer_param.add_top()) = "accuracy";
    //nsr4.set_phase(Phase::TRAIN);
    nsr4.set_phase(TRAIN);

    (*accuracy_layer_param.add_include()) = nsr4;
    printf("CAFFE Layer11 initialized\n");

    // Layer 12 : [prob]
    caffe::LayerParameter softmax_layer_param;
    caffe::NetStateRule nsr5;
    softmax_layer_param.set_name("prob");
    softmax_layer_param.set_type("Softmax");
    (*softmax_layer_param.add_bottom()) = "ip2";
    (*softmax_layer_param.add_top()) = "prob";
    nsr5.set_phase(TEST);
    (*softmax_layer_param.add_include()) = nsr5;
    printf("CAFFE Layer12 initialized\n");

    // ネットステートの作成
    caffe::NetState *state_train = new caffe::NetState();
    caffe::NetState *state_test = new caffe::NetState();

    // 学習用ネットワークの作成
    NetParameter net_param_train;
    state_train->set_phase(TRAIN);
    net_param_train.set_allocated_state(state_train);
    (*net_param_train.add_layer()) = data_layer_param1;
    (*net_param_train.add_layer()) = data_layer_param2;
    (*net_param_train.add_layer()) = res_layer_param;
    (*net_param_train.add_layer()) = resx_layer_param;
    (*net_param_train.add_layer()) = rnn_layer_param;
    (*net_param_train.add_layer()) = ip_layer_param1;
    (*net_param_train.add_layer()) = relu_layer_param1;
    (*net_param_train.add_layer()) = ip_layer_param2;
    (*net_param_train.add_layer()) = slicer_layer_param;
    (*net_param_train.add_layer()) = loss_layer_param;
    (*net_param_train.add_layer()) = accuracy_layer_param;
    (*net_param_train.add_layer()) = softmax_layer_param;
    printf("CAFFE TRAIN net initialized\n");

    // 予測用ネットワークの作成
    NetParameter net_param_test;
    state_test->set_phase(TEST);
    net_param_test.set_allocated_state(state_test);
    (*net_param_test.add_layer()) = data_layer_param1;
    (*net_param_test.add_layer()) = data_layer_param2;
    (*net_param_test.add_layer()) = res_layer_param;
    (*net_param_test.add_layer()) = resx_layer_param;
    (*net_param_test.add_layer()) = rnn_layer_param;
    (*net_param_test.add_layer()) = ip_layer_param1;
    (*net_param_test.add_layer()) = relu_layer_param1;
    (*net_param_test.add_layer()) = ip_layer_param2;
    (*net_param_test.add_layer()) = slicer_layer_param;
    (*net_param_test.add_layer()) = loss_layer_param;
    (*net_param_test.add_layer()) = accuracy_layer_param;
    (*net_param_test.add_layer()) = softmax_layer_param;
    printf("CAFFE TEST net initialized\n");

    // ソルバーを設定
    SolverParameter solver_param;
    (*solver_param.mutable_type()) = "SGD";
    solver_param.set_lr_policy("fixed");
    solver_param.set_base_lr(0.01f);
    solver_param.set_gamma(0.1);
    solver_param.set_display(0);
    (*solver_param.mutable_net_param()) = net_param_train;
    //caffe::shared_ptr<caffe::Solver<float>> solver(caffe::SolverRegistry<float>::CreateSolver(solver_param));
    caffe::shared_ptr<Solver<float>> solver(SolverRegistry<float>::CreateSolver(solver_param));

    // 学習用ネットワーク
    caffe::shared_ptr<caffe::Net<float>> net_train;
    net_train = solver->net();

    // 入力データ領域の準備
    const auto input_layer1 =
            boost::dynamic_pointer_cast<caffe::MemoryDataLayer<float>>(net_train->layer_by_name("input1"));
    const auto input_layer2 =
            boost::dynamic_pointer_cast<caffe::MemoryDataLayer<float>>(net_train->layer_by_name("input2"));

    // 入力データ(EX-OR)
    const int data_size = 4;
    const int input_num = 2;
    float input_data[data_size][input_num] = {{0.0f,0.0f},{1.0f,0.0f},{0.0f,1.0f},{1.0f,1.0f}};
    float label[data_size][input_num] = { {0.0f,0.0f}, {1.0f,1.0f}, {1.0f,1.0f}, {0.0f,0.0f}};
    float dummy_label[data_size] = {0.0f,0.0f,0.0f,0.0f};

    input_layer1->Reset((float*)input_data,(float*)dummy_label,data_size);
    input_layer2->Reset((float*)label,(float*)dummy_label,data_size);

    // Initialize bias for the forget gate to 5 as described in the clockwork RNN paper
    const caffe::vector<caffe::shared_ptr<Layer<float> > >& layers = net_train->layers();
    for (int i = 0; i < layers.size(); ++i) {
        if (strcmp(layers[i]->type(), "LSTM") != 0) {
            continue;
        }
        const int h = layers[i]->layer_param().recurrent_param().num_output();
        caffe::shared_ptr<Blob<float> > bias = layers[i]->blobs()[2];
        caffe_set(h, 5.0f, bias->mutable_cpu_data() + h);
    }

    // 学習
    std::chrono::system_clock::time_point  start, end;
    start = std::chrono::system_clock::now();

    float loss = 10000.0f;
    float accuracy = 0.0f;
    int iter = 0;
    while((loss > 0.0005) || (accuracy < 0.95f))
    {
        // 学習の実行
        solver->Step(1);

        loss = net_train->blob_by_name("loss")->cpu_data()[0];
        accuracy = net_train->blob_by_name("accuracy")->cpu_data()[0];
        if(iter < 0.0005)
        {
            printf("iter : %d loss : %f  accuracy : %f\n",iter,loss,accuracy);
        }
        else
        {
            if ((iter % 1000) == 0)
                printf("iter : %d loss : %f  accuracy : %f\n",iter,loss,accuracy);
        }
        iter++;
    }
    net_train->blob_by_name("loss")->cpu_data();
    end = std::chrono::system_clock::now();
    double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end-start).count();
    printf("learning time : %f[msec]\n",elapsed);

    // 学習結果を書き込み
    char chr[256];
    sprintf(chr,"_iter_%d.caffemodel",iter);
    string str = chr;
    solver->Snapshot();

    // 学習結果を読み込み
    caffe::shared_ptr<Net<float>> net_test(new Net<float>(net_param_test));
    net_test->CopyTrainedLayersFrom(str);

    // 予測用入力データ領域の準備
    const auto input_test_layer =
            boost::dynamic_pointer_cast<MemoryDataLayer<float>>(net_test->layer_by_name("input1"));
    const auto dummy_test_layer =
            boost::dynamic_pointer_cast<MemoryDataLayer<float>>(net_test->layer_by_name("input2"));

    // 予測結果の表示
    for (int idx = 0; idx < data_size; idx++)
    {
        float loss;
        input_test_layer->Reset((float*)input_data[idx], (float*)dummy_label, 1);
        dummy_test_layer->Reset((float*)dummy_label, (float*)dummy_label, 1);

        // 予測の実行
        const vector<Blob<float>*> result = net_test->Forward(&loss);

        const auto data = result[result.size() - 1]->cpu_data();
        int ans = (data[0] > data[1]) ? 0:1;
        std::cout << idx << " : " << data[0] << ", " << data[1] << " (ans) : " << ans << std::endl;
    }
}


text:
#include <compose/detail/lean_tuple.hpp>

#include <boost/core/lightweight_test.hpp>
#include <memory>

struct tag
{
};

int
main()
{
    struct empty
    {
    };
    struct explicit_constructible
    {
        explicit_constructible(std::nullptr_t)
          : i_(0)
        {
        }

        explicit explicit_constructible(int i)
          : i_(i)
        {
        }

        int i_;
    };

    BOOST_TEST(sizeof(compose::detail::lean_tuple<int, empty>) == sizeof(int));
    compose::detail::lean_tuple<explicit_constructible, int> t{nullptr, 42};
    BOOST_TEST(compose::detail::get<1>(t) == 42);
    BOOST_TEST(compose::detail::get<0>(t).i_ == 0);

    t = compose::detail::lean_tuple<explicit_constructible, int>{
      explicit_constructible(42), 43};
    BOOST_TEST(compose::detail::get<1>(t) == 43);
    BOOST_TEST(compose::detail::get<0>(t).i_ == 42);

    int i = 43, j = 42;
    compose::detail::lean_tuple<int&, int&> t2{i, j};
    BOOST_TEST(compose::detail::get<1>(t2) == 42);
    BOOST_TEST(compose::detail::get<0>(t2) == 43);
    return boost::report_errors();
}

ext: cpp

max_stars_repo_name: djarek/Compose

max_issues_repo_name: djarek/Compose

max_forks_repo_name: djarek/Compose


text:
/**
 * Author: Aravinth Panchadcharam
 * Email: me@aravinth.info
 * Date: 22/12/14.
 * Project: Gesture Recogntion for Human-Robot Interaction
 */

#include <iostream>
#include <string>
#include <boost/bind.hpp>
#include <boost/thread.hpp>
#include <boost/log/trivial.hpp>
#include "udp_server.h"
#include "skeleton_tracker.h"
#include "gesture_tracker.h"
#include "utils.h"

/**
 * Constructor
 *
 */

udp_server::udp_server(boost::asio::io_service& io_service):
client_port(getConfigValue<int>("clientPort")),
server_port(getConfigValue<int>("serverPort")),
socket_server(io_service, udp::endpoint(udp::v4(), server_port))
{
    clientConnected = false;
    receive();
    BOOST_LOG_TRIVIAL(info) << "UDP Server started at port : " << server_port;
}

/**
 * Create UDP connection and start receive
 *
 */

void udp_server::receive()
{
    socket_server.async_receive_from(
                                     boost::asio::buffer(receive_buffer),
                                     client_endpoint,
                                     boost::bind(
                                                 &udp_server::handle_receive,
                                                 this,
                                                 boost::asio::placeholders::error,
                                                 boost::asio::placeholders::bytes_transferred
                                                 )
                                     );
}

/**
 * Send data to the conneted end point
 *
 */

void udp_server::send(boost::shared_ptr<std::string> message){
    if(isClientConnected()){
        socket_server.async_send_to(boost::asio::buffer(*message),
                                    client_endpoint,
                                    boost::bind(
                                                &udp_server::handle_send,
                                                this,
                                                message,
                                                boost::asio::placeholders::error,
                                                boost::asio::placeholders::bytes_transferred
                                                )
                                    );
    }
    else
    {
        BOOST_LOG_TRIVIAL(debug) << *message;
    }

}

/**
 * Create UDP connection handler for receiving data
 *
 */

void udp_server::handle_receive(const boost::system::error_code& error, std::size_t bytes_transferred)
{
    if (!error || error == boost::asio::error::message_size)
    {
        std::string data_received(receive_buffer.begin(), receive_buffer.end());
        BOOST_LOG_TRIVIAL(debug) << "Received : " << data_received << " : " << bytes_transferred << " bytes : " << client_endpoint;

        BOOST_LOG_TRIVIAL(info) << "UDP Client connected" ;
        clientConnected = true;

        receive();
    }
    else
    {
        BOOST_LOG_TRIVIAL(error) << error;
    }
}

/**
 * Create UDP connection handler for sending data
 *
 */

void udp_server::handle_send(boost::shared_ptr<std::string> message, const boost::system::error_code& error, std::size_t bytes_transferred)
{
    BOOST_LOG_TRIVIAL(info) << "Sent : " << *message;
}

/**
 * Check whether client is connected
 *
 */

bool udp_server::isClientConnected(){
    return clientConnected;
}


text:
/*  Sirikata
 *  MigrationMonitor.hpp
 *
 *  Copyright (c) 2009, Ewen Cheslack-Postava
 *  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 Sirikata nor the names of its contributors may
 *    be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
 * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
 * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#ifndef _SIRIKATA_MIGRATION_MONITOR_HPP_
#define _SIRIKATA_MIGRATION_MONITOR_HPP_

#include <sirikata/core/util/Platform.hpp>
#include <sirikata/space/LocationService.hpp>
#include <sirikata/space/CoordinateSegmentation.hpp>

#include <boost/multi_index_container.hpp>
#include <boost/multi_index/member.hpp>
#include <boost/multi_index/ordered_index.hpp>

namespace Sirikata {

/** MigrationMonitor keeps track of objects that are currently on
 *  this server and determines when they have left the server, or
 *  more generally, when they should begin to migrate to another
 *  server.
 */
class MigrationMonitor : public LocationServiceListener, public CoordinateSegmentation::Listener {
public:
    typedef std::tr1::function<void(const UUID&)> MigrationCallback;

    /** Create a new MigrationMonitor.  The MigrationCallback is called any time a migration is detected.  Note that
     *  it may be called from a thread other than the main thread, so it should be thread safe.
     *  \param ctx SpaceContext for this simulation
     *  \param locservice location service for this server
     *  \param cseg coordinate segmentation used for this server
     *  \param cb callback to be invoked when a migration is detected
     */
    MigrationMonitor(SpaceContext* ctx, LocationService* locservice, CoordinateSegmentation* cseg, MigrationCallback cb);
    ~MigrationMonitor();

    // Indicates whether the given position is on this server, useful to check if object should be
    // permitted to join this server.
    bool onThisServer(const Vector3f& pos) const;

private:

    /** LocationServiceListener Interface. */
    virtual void localObjectAdded(const UUID& uuid, bool agg, const TimedMotionVector3f& loc, const TimedMotionQuaternion& orient, const BoundingSphere3f& bounds, const String& mesh, const String& physics);
    virtual void localObjectRemoved(const UUID& uuid, bool agg);
    virtual void localLocationUpdated(const UUID& uuid, bool agg, const TimedMotionVector3f& newval);

    // Handlers for location events we care about.  These are handled in our internal strand
    void handleLocalObjectAdded(const UUID& uuid, const TimedMotionVector3f& loc, const BoundingSphere3f& bounds);
    void handleLocalObjectRemoved(const UUID& uuid);
    void handleLocalLocationUpdated(const UUID& uuid, const TimedMotionVector3f& newval);

    /** CoordinateSegmentation::Listener Interface. */
    virtual void updatedSegmentation(CoordinateSegmentation* cseg, const std::vector<SegmentationInfo>& new_segmentation);
    void handleUpdatedSegmentation(CoordinateSegmentation* cseg, const std::vector<SegmentationInfo>& new_segmentation);

    // Given our current information, sets up the next timeout, cancelling any outstanding timeouts.
    // This is conservative -- it will only replace the timer if the earliest event time changed
    void waitForNextEvent();

    // Service the migration monitor, return a set of objects for which migrations should be started
    void service();

    bool inRegion(const Vector3f& pos) const;

    Time computeNextEventTime(const UUID& obj, const TimedMotionVector3f& newloc);

    SpaceContext* mContext;
    LocationService* mLocService;
    CoordinateSegmentation* mCSeg;
    BoundingBoxList mBoundingRegions;

    struct ObjectInfo {
        ObjectInfo(UUID id, Time next)
         : objid(id),
           nextEvent(next)
        {}

        UUID objid;
        Time nextEvent;
    };

    // Tags used by ObjectInfoSet
    struct objid {};
    struct nextevent {};

    typedef boost::multi_index_container<
        ObjectInfo,
        boost::multi_index::indexed_by<
            boost::multi_index::ordered_unique< boost::multi_index::tag<objid>, BOOST_MULTI_INDEX_MEMBER(ObjectInfo,UUID,objid) >,
            boost::multi_index::ordered_non_unique< boost::multi_index::tag<nextevent>, BOOST_MULTI_INDEX_MEMBER(ObjectInfo,Time,nextEvent) >
        >
    > ObjectInfoSet;
    typedef ObjectInfoSet::index<objid>::type ObjectInfoByID;
    typedef ObjectInfoSet::index<nextevent>::type ObjectInfoByNextEvent;

    static void changeNextEventTime(ObjectInfo& objinfo, const Time& newt);

    ObjectInfoSet mObjectInfo;

    Network::IOStrand* mStrand;
    Network::IOTimerPtr mTimer;

    Time mMinEventTime;

    MigrationCallback mCB;
};

} // namespace Sirikata

#endif //_SIRIKATA_MIGRATION_MONITOR_HPP_

ext: hpp

max_stars_repo_name: pathorn/sirikata

max_issues_repo_name: pathorn/sirikata

max_forks_repo_name: pathorn/sirikata


text:
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE atomic_rw_test

#include "async/atomic_rw.hpp"

#include <boost/test/unit_test.hpp>
#include <future>
#include <iostream>
#include <numeric>
#include <set>

#include "async/atomic.hpp"
#include "async/vector.hpp"

using namespace nil;
using namespace nil::async;

BOOST_AUTO_TEST_CASE(ReadTest) {
  atomic_rw<std::set<int>> async_set{1, 4, 5, 6};
  BOOST_CHECK(async_set.copy() == (std::set<int>{1, 4, 5, 6}));
  async_set.assign(4, 6, 7, 9);
  BOOST_CHECK(async_set.copy() == (std::set<int>{4, 6, 7, 9}));

  auto read_func_1 = [&]() {
    for (size_t ii{0}; ii < 100; ++ii) {
      auto read_proxy = async_set.read();
      BOOST_CHECK_EQUAL(read_proxy->size(), 4);
      BOOST_CHECK_EQUAL(read_proxy.value().count(4), 1u);
      BOOST_CHECK_EQUAL((*read_proxy).count(2), 0u);
      BOOST_CHECK(!read_proxy->empty());
      BOOST_CHECK_EQUAL(4 + 6 + 7 + 9, std::accumulate(read_proxy->cbegin(),
                                                       read_proxy->cend(), 0));
    }
  };

  auto read_func_2 = [&]() {
    for (size_t ii{0}; ii < 100; ++ii) {
      BOOST_CHECK_EQUAL(async_set->size(), 4);
      BOOST_CHECK_EQUAL(async_set->count(4), 1u);
      BOOST_CHECK_EQUAL((*async_set)->count(2), 0u);
      BOOST_CHECK(!async_set.copy().empty());
      BOOST_CHECK_EQUAL(4 + 6 + 7 + 9, std::accumulate(async_set->cbegin(),
                                                       async_set->cend(), 0));
    }
  };

  auto f1 = std::async(std::launch::async, read_func_1);
  auto f2 = std::async(std::launch::async, read_func_1);
  auto f3 = std::async(std::launch::async, read_func_2);
  auto f4 = std::async(std::launch::async, read_func_1);
  auto f5 = std::async(std::launch::async, read_func_2);

  f1.get();
  f2.get();
  f3.get();
  f4.get();
  f5.get();
}

BOOST_AUTO_TEST_CASE(WriteTest) {
  atomic_rw<std::set<int>> async_set{1, 4, 5, 6};
  const auto& const_async_set = async_set;
  auto read_func = [&const_async_set]() {
    for (size_t ii{0}; ii < 100; ++ii) {
      {
        auto read_proxy = const_async_set.read();
        BOOST_CHECK_EQUAL(read_proxy->size(), 4);
        BOOST_CHECK_EQUAL(read_proxy->count(4), 1u);
        BOOST_CHECK_EQUAL(read_proxy->count(12), 0u);
        BOOST_CHECK_EQUAL(read_proxy->count(13), 0u);
        BOOST_CHECK_EQUAL(read_proxy->count(14), 0u);
        BOOST_CHECK_EQUAL(read_proxy->count(15), 0u);
        BOOST_CHECK(!read_proxy->empty());
        BOOST_CHECK_EQUAL(
            1 + 4 + 5 + 6,
            std::accumulate(read_proxy->cbegin(), read_proxy->cend(), 0));
      }
      for (size_t ii{0}; ii < 100; ++ii) {
        BOOST_CHECK_EQUAL(4, 4);
      }
    }
  };

  auto write_func = [&async_set]() {
    for (size_t ii{0}; ii < 100; ++ii) {
      {
        auto write_proxy = async_set.write();
        write_proxy->insert(12);
        write_proxy->insert(13);
        write_proxy->insert(14);
        write_proxy->insert(15);
        write_proxy->erase(12);
        write_proxy->erase(13);
        write_proxy->erase(14);
        write_proxy->erase(15);
        auto cp = *write_proxy;
        *write_proxy = std::set<int>({1, 2, 3, 4, 5});
        *write_proxy = cp;
      }
      for (size_t ii{0}; ii < 100; ++ii) {
        BOOST_CHECK_EQUAL(4, async_set->size());
      }
    }
  };

  auto f1 = std::async(std::launch::async, read_func);
  auto f2 = std::async(std::launch::async, read_func);
  auto f3 = std::async(std::launch::async, write_func);

  f1.get();
  f2.get();
  f3.get();
}

max_stars_repo_name: SwappyG/nilcpp

max_issues_repo_name: SwappyG/nilcpp

max_forks_repo_name: SwappyG/nilcpp


text:
#ifndef FORGE_FORGE_HPP_INCLUDED
#define FORGE_FORGE_HPP_INCLUDED

#include <boost/filesystem/path.hpp>
#include <string>
#include <vector>

struct lua_State;

namespace sweet
{

namespace error
{

class ErrorPolicy;

}

namespace forge
{

class Context;
class ForgeEventSink;
class Reader;
class Executor;
class Scheduler;
class System;
class TargetPrototype;
class ToolsetPrototype;
class Toolset;
class Target;
class Graph;
class Lua;

/**
// Forge library main class.
*/
class Forge
{
    error::ErrorPolicy& error_policy_;
    ForgeEventSink* event_sink_; ///< The EventSink for this Forge or null if this Forge has no EventSink.
    Lua* lua_; ///< The Lua bindings to the Forge library.
    System* system_; ///< The System that provides access to the operating system.
    Reader* reader_; ///< The reader that filters executable output and dependencies.
    Graph* graph_; ///< The dependency graph of targets used to determine which targets are outdated.
    Scheduler* scheduler_; ///< The scheduler that schedules environments to process jobs in the dependency graph.
    Executor* executor_; ///< The executor that schedules threads to process commands.
    boost::filesystem::path root_directory_; ///< The full path to the root directory.
    boost::filesystem::path initial_directory_; ///< The full path to the initial directory.
    boost::filesystem::path home_directory_; ///< The full path to the user's home directory.
    boost::filesystem::path executable_directory_; ///< The full path to the build executable directory.
    bool stack_trace_enabled_; ///< Print stack traces on error when true.

    public:
        Forge( const std::string& initial_directory, error::ErrorPolicy& error_policy, ForgeEventSink* event_sink );
        ~Forge();

        error::ErrorPolicy& error_policy() const;
        System* system() const;
        Reader* reader() const;
        Graph* graph() const;
        Scheduler* scheduler() const;
        Executor* executor() const;
        Context* context() const;
        lua_State* lua_state() const;

        const boost::filesystem::path& root() const;
        boost::filesystem::path root( const boost::filesystem::path& path ) const;
        const boost::filesystem::path& initial() const;
        boost::filesystem::path initial( const boost::filesystem::path& path ) const;
        const boost::filesystem::path& home() const;
        boost::filesystem::path home( const boost::filesystem::path& path ) const;
        const boost::filesystem::path& executable() const;
        boost::filesystem::path executable( const boost::filesystem::path& path ) const;
        boost::filesystem::path absolute( const boost::filesystem::path& path ) const;
        boost::filesystem::path relative( const boost::filesystem::path& path ) const;

        void set_stack_trace_enabled( bool stack_trace_enabled );
        bool stack_trace_enabled() const;
        void set_maximum_parallel_jobs( int maximum_parallel_jobs );
        int maximum_parallel_jobs() const;
        void set_forge_hooks_library( const std::string& forge_hooks_library );
        const std::string& forge_hooks_library() const;

        void set_root_directory( const std::string& root_directory );
        void assign_global_variables( const std::vector<std::string>& assignments_and_commands );
        void set_package_path( const std::string& path );
        void execute( const std::string& filename, const std::string& command );
        void file( const std::string& filename );
        void script( const std::string& script );

        void create_target_lua_binding( Target* target );
        void update_target_lua_binding( Target* target );
        void destroy_target_lua_binding( Target* target );
        void create_toolset_lua_binding( Toolset* toolset );
        void destroy_toolset_lua_binding( Toolset* toolset );
        void create_target_prototype_lua_binding( TargetPrototype* target_prototype );
        void destroy_target_prototype_lua_binding( TargetPrototype* target_prototype );
        void create_toolset_prototype_lua_binding( ToolsetPrototype* toolset_prototype );
        void destroy_toolset_prototype_lua_binding( ToolsetPrototype* toolset_prototype );

        void outputf( const char* format, ... );
        void errorf( const char* format, ... );
        void output( const char* message );
        void error( const char* message );
};

}

}

#endif

max_stars_repo_name: willmbaker/forge

max_issues_repo_name: willmbaker/forge

max_forks_repo_name: willmbaker/forge


text:
//
// Created by qfeng on 17-9-29.
//

#include "gbtree_model/gbtree_model.h"
#include "gbtree_model/leaf_node.h"
#include <fstream>
#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>

using namespace std;

namespace quickscorer {

    GBTreeModel::GBTreeModel() {
        _logger = spdlog::get(QSLog::_logger_name);
    }

    vector<float> GBTreeModel::predict(const vector<Eigen::SparseVector<float>> &instances, bool output_margin) {
        vector<float> results;
        for(int i = 0; i < instances.size(); ++i) {
            auto score = predict(instances[i], output_margin);
            results.push_back(score);
        }
        return results;
    }

    float GBTreeModel::predict(const Eigen::SparseVector<float> &features, bool output_margin) {
        float margin = 0;
        try {
            for (int i = 0; i < _trees.size(); ++i) {
                margin += _tree_weights[i] * _trees[i]->predict(features);
            }
        } catch (exception &ex) {
            _logger->error("Fail to predict features of size {}, detail: {}", features.size(), ex.what());
        }
        if(output_margin) return margin;
        else return 1.0 / (1.0 + exp(-margin));
    }

    unique_ptr<GBTreeModel> GBTreeModel::from_xgb_txt(const string &model_path, int num_trees) {
        auto logger = spdlog::get(QSLog::_logger_name);
        logger->info("Load gbtree model from {}", model_path);
        try {
            int tree_count = 0;
            ifstream model_file;
            model_file.open(model_path);
            if (model_file.is_open()) {
                string line;
                auto model = unique_ptr<GBTreeModel>(new GBTreeModel());
                uint64_t feature_size = 0;
                google::dense_hash_set<uint64_t> all_tree_features;
                all_tree_features.set_empty_key(std::numeric_limits<uint64_t>::max());
                unique_ptr<InnerNode> tree = nullptr;
                google::dense_hash_map<int, InnerNode *> recent_depth_nodes;
                recent_depth_nodes.set_empty_key(std::numeric_limits<int>::max());
                unique_ptr<google::dense_hash_set<uint64_t>> tree_features = nullptr;
                while (!model_file.eof()) {
                    getline(model_file, line);
                    if (boost::algorithm::starts_with(line, "booster") ||
                        boost::algorithm::trim_copy(line).length() == 0) {
                        // start parsing a new tree or finish parsing all the trees
                        if (tree != nullptr) {
                            model->_trees.push_back(std::move(tree));
                            model->_tree_weights.push_back(1);
                            recent_depth_nodes.clear();
                            all_tree_features.insert(tree_features->begin(), tree_features->end());
                            model->_tree_features.push_back(std::move(tree_features));
                        }
                        // check the tree numbers
                        if (num_trees > 0) {
                            if (tree_count++ >= num_trees) break;
                        }
                        // create a new tree instance
                        if (boost::algorithm::starts_with(line, "booster")) {
                            // create a new tree
                            tree = unique_ptr<InnerNode>(new InnerNode(0));
                            tree_features = unique_ptr<google::dense_hash_set<uint64_t>>(
                                    new google::dense_hash_set<uint64_t>());
                            tree_features->set_empty_key(std::numeric_limits<uint64_t>::max());
                        }
                    } else {
                        // parse a line of tree node
                        auto f_idx = parse_line(line, recent_depth_nodes, *tree);
                        if (f_idx > 0) {
                            if (feature_size < f_idx) feature_size = f_idx;
                            tree_features->insert(f_idx);
                        }
                    }
                }
                model->_feature_size = feature_size + 1;
                if (model_file.is_open()) model_file.close();
                // log statistical information
                logger->info("GBTree stat: feature size {}", model->_feature_size);
                logger->info("GBTree stat: distinct features {}", all_tree_features.size());
#ifdef _DEBUG
                vector<pair<uint64_t, int>> feature_counts;
                for (auto it = all_tree_features.begin(); it != all_tree_features.end(); ++it) {
                    int count = 0;
                    for (int i = 0; i < model->_tree_features.size(); i++) {
                        auto found = model->_tree_features[i]->find(*it);
                        if (found != model->_tree_features[i]->end()) ++count;
                    }
                    feature_counts.emplace_back(*it, count);
                }
                std::sort(feature_counts.begin(), feature_counts.end(),
                          [](pair<uint64_t, int> &lhs, pair<uint64_t, int> &rhs) {
                              return lhs.second > rhs.second;
                          });
                ostringstream ss;
                for (int i = 0; i < feature_counts.size(); ++i) {
                    ss << feature_counts[i].first << ":" << feature_counts[i].second << " ";
                }
                logger->info("GBTree stat: feature histogram {}", ss.str());
#endif
                // return loaded model
                return model;
            } else
                logger->error("Fail to open xgboost model file {}.", model_path);
        } catch (exception &ex) {
            logger->error("Fail to load xgboost model from {}, detail: {}.", model_path, ex.what());
        }
        return nullptr;
    }

    uint64_t
    GBTreeModel::parse_line(const string &line, google::dense_hash_map<int, InnerNode *> &recent_depth_nodes,
                            InnerNode &root) {
        // parse depth based on number of tabs
        int i = 0;
        while (line[i] == '\t') ++i;
        int depth = i;
        // parse feature
        while (line[i] != ':') ++i;
        if (line[i + 1] == '[') {
            // inner node and parse feature
            int f_idx_st = i + 3;
            while (line[i] != '<') ++i;
            int f_idx_end = i;
            auto f_idx = boost::lexical_cast<uint64_t>(line.substr(f_idx_st, f_idx_end - f_idx_st));
            // parse condition value
            int f_val_st = i + 1;
            while (line[i] != ']') ++i;
            int f_val_end = i;
            auto f_val = boost::lexical_cast<float>(line.substr(f_val_st, f_val_end - f_val_st));
            // parse left child
            while (line[i] != '=') ++i;
            int left_child_st = i + 1;
            while (line[i] != ',') ++i;
            int left_child_end = i;
            auto left_child = line.substr(left_child_st, left_child_end - left_child_st);
            // skip right child
            while (line[i] != '=') ++i;
            // parse default directory
            ++i;
            while (line[i] != '=') ++i;
            ++i;
            auto missing = line.substr(i);
            // append node to its parent
            if (depth > 0) {
                // initialize non-root node
                auto node = unique_ptr<InnerNode>(new InnerNode(depth));
                node->_split_feature = f_idx;
                node->_split_value = f_val;
                node->_default_to_left = (missing == left_child);
                // append node to its parent
                auto parent = recent_depth_nodes[depth - 1];
                if (parent->_left_child == nullptr) {
                    parent->_left_child = std::move(node);
                    recent_depth_nodes[depth] = dynamic_cast<InnerNode *>(parent->_left_child.get());
                } else {
                    parent->_right_child = std::move(node);
                    recent_depth_nodes[depth] = dynamic_cast<InnerNode *>(parent->_right_child.get());
                }
            } else {
                // initialize root node
                root._split_feature = f_idx;
                root._split_value = f_val;
                root._default_to_left = (missing == left_child);
                recent_depth_nodes[0] = &root;
            }

            return f_idx;
        } else {
            // leaf node and parse value
            while (line[i] != '=') ++i;
            ++i;
            auto leaf_val = boost::lexical_cast<float>(line.substr(i));
            auto &parent = recent_depth_nodes[depth - 1];
            auto leaf_node = unique_ptr<LeafNode>(new LeafNode(depth, leaf_val));
            if (parent->_left_child == nullptr) parent->_left_child = std::move(leaf_node);
            else parent->_right_child = std::move(leaf_node);
            return 0;
        }
    }
}


text:
//
// Copyright (c) 2020 Damian Jarek (damian.jarek93@gmail.com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// Official repository: https://github.com/djarek/canary
//

// Test if header is self-contained
#include <canary/raw.hpp>

#include <boost/core/lightweight_test.hpp>
#include <canary/interface_index.hpp>

namespace
{

namespace net = canary::net;

void
test_sync_send()
{
    net::io_context ctx{1};
    canary::raw::socket sock1{
      ctx, canary::raw::endpoint{canary::get_interface_index("vcan0")}};
    canary::raw::socket sock2{
      ctx, canary::raw::endpoint{canary::get_interface_index("vcan0")}};
    ::can_frame out_frame{};
    out_frame.can_id = 0xFF;
    std::uint8_t const data[] = {0xDE, 0xAD, 0xBE, 0xEF};
    out_frame.can_dlc = sizeof(data);
    std::memcpy(out_frame.data, data, sizeof(data));
    sock1.send(net::buffer(&out_frame, sizeof(out_frame)));
    ::can_frame in_frame{};
    sock2.receive(net::buffer(&in_frame, sizeof(in_frame)));

    BOOST_TEST_EQ(in_frame.can_id, out_frame.can_id);
    BOOST_TEST_EQ(in_frame.can_dlc, out_frame.can_dlc);
    BOOST_TEST_ALL_EQ(&in_frame.data[0],
                      &in_frame.data[sizeof(data)],
                      &out_frame.data[0],
                      &out_frame.data[sizeof(data)]);
}

void
test_sync_sendto()
{
    net::io_context ctx{1};
    // Use vcan1 so that we can tell apart a default constructed endpoint and
    // one filled by receive_from()
    canary::raw::socket sock1{
      ctx, canary::raw::endpoint{canary::get_interface_index("vcan1")}};
    canary::raw::socket sock2{
      ctx, canary::raw::endpoint{canary::get_interface_index("vcan1")}};

    canary::raw::endpoint const ep1{canary::get_interface_index("vcan1")};
    canary::raw::endpoint ep2;
    ::can_frame out_frame{};
    out_frame.can_id = 0xFF;
    std::uint8_t const data[] = {0xDE, 0xAD, 0xBE, 0xEF};
    out_frame.can_dlc = sizeof(data);
    std::memcpy(out_frame.data, data, sizeof(data));
    sock1.send_to(net::buffer(&out_frame, sizeof(out_frame)), ep1);
    ::can_frame in_frame{};
    sock2.receive_from(net::buffer(&in_frame, sizeof(in_frame)), ep2);

    BOOST_TEST_EQ(in_frame.can_id, out_frame.can_id);
    BOOST_TEST_EQ(in_frame.can_dlc, out_frame.can_dlc);
    BOOST_TEST_ALL_EQ(&in_frame.data[0],
                      &in_frame.data[sizeof(data)],
                      &out_frame.data[0],
                      &out_frame.data[sizeof(data)]);
    BOOST_TEST_EQ(ep1.interface_index(), ep2.interface_index());
}

} // namespace

int
main()
{
    test_sync_send();
    test_sync_sendto();
    return boost::report_errors();
}

max_stars_repo_name: phvheumen/canary

max_issues_repo_name: phvheumen/canary

max_forks_repo_name: phvheumen/canary


text:
//==================================================================================================
/*!
  @file

  Introspection header gateway

  @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_DETAIL_DISPATCH_META_GENERATION_HPP_INCLUDED
#define BOOST_SIMD_DETAIL_DISPATCH_META_GENERATION_HPP_INCLUDED

#include <boost/simd/detail/dispatch/meta/generation/upgrade.hpp>
#include <boost/simd/detail/dispatch/meta/generation/downgrade.hpp>
#include <boost/simd/detail/dispatch/meta/generation/as_signed.hpp>
#include <boost/simd/detail/dispatch/meta/generation/apply_sign.hpp>
#include <boost/simd/detail/dispatch/meta/generation/as_integer.hpp>
#include <boost/simd/detail/dispatch/meta/generation/as_floating.hpp>
#include <boost/simd/detail/dispatch/meta/generation/as_unsigned.hpp>
#include <boost/simd/detail/dispatch/meta/generation/make_integer.hpp>
#include <boost/simd/detail/dispatch/meta/generation/make_floating.hpp>
#include <boost/simd/detail/dispatch/meta/generation/transfer_qualifiers.hpp>

#endif

max_stars_repo_name: SylvainCorlay/pythran

max_issues_repo_name: SylvainCorlay/pythran

max_forks_repo_name: SylvainCorlay/pythran


text:
#pragma once

#include <Eigen/Cholesky>
#include <Eigen/Core>
#include <Eigen/Sparse>
#include <limits>

namespace fnnls {

using ArrayXb = Eigen::Array<bool, Eigen::Dynamic, 1>;
template <typename T>
using MatrixX_ = Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>;
template <typename T>
using VectorX_ = Eigen::Matrix<T, Eigen::Dynamic, 1>;
template <typename T>
using ArrayX_ = Eigen::Array<T, Eigen::Dynamic, 1>;

inline const Eigen::ArrayXi to_indices(const Eigen::Ref<const ArrayXb> &b_array) {
    Eigen::ArrayXi indices = Eigen::ArrayXi::LinSpaced(b_array.size(), 0, b_array.size() - 1);
    const auto shifted_iterator
        = std::stable_partition(indices.data(), indices.data() + indices.size(),
                                [&b_array](Eigen::Index i) { return b_array(i); });
    const size_t data_size = shifted_iterator - indices.data();
    indices.conservativeResize(data_size);
    return indices;
}

inline const ArrayXb operator!(const Eigen::Ref<const ArrayXb> &array_b) {
    return ArrayXb::NullaryExpr(array_b.size(),
                                [&array_b](Eigen::Index i) { return !array_b(i); });
}

template <typename T>
inline Eigen::ArrayXi::Index argmax_of_masked_array(const Eigen::Ref<const VectorX_<T>> &w,
                                                    const Eigen::Ref<const ArrayXb> &P) {
    // The function calculates the argmax of w masked by inverted boolean array P,
    // i.e. argmax(W * ~P).
    Eigen::ArrayXi::Index argmax;
    (ArrayX_<T>::NullaryExpr(P.size(), [&w, &P](Eigen::Index i) {
        if (!P(i)) {
            return w(i);
        }
        constexpr T dzero = T{};
        return dzero;
    })).maxCoeff(&argmax);
    return argmax;
}

template <typename T>
inline VectorX_<T> least_squares_solver(const Eigen::Ref<const MatrixX_<T>> &ZTZ,
                                        const Eigen::Ref<const VectorX_<T>> &ZTx,
                                        const Eigen::Ref<const Eigen::ArrayXi> &indices) {
    return ZTZ(indices, indices)
        .template selfadjointView<Eigen::Upper>()
        .ldlt()
        .solve(ZTx(indices));
}

template <typename T>
inline T get_alpha(const Eigen::Ref<const ArrayX_<T>> &d, const Eigen::Ref<const ArrayX_<T>> &s,
                   const Eigen::Ref<const Eigen::ArrayXi> &indices) {
    // Please note that there is an erroneous extra minus sign in the article
    // on line C2.
    // See instead for example the pseudocode at:
    // https://en.wikipedia.org/wiki/Non-negative_least_squares
    return (d(indices) / (d(indices) - s(indices))).minCoeff();
}

template <typename T>
inline const MatrixX_<T> construct_ZTZ(const Eigen::Ref<const Eigen::SparseMatrix<T>> &ZT_sp,
                                       const int n) {
    MatrixX_<T> ZTZ = MatrixX_<T>::Zero(n, n);
    ZTZ.template triangularView<Eigen::Upper>() = MatrixX_<T>(ZT_sp * ZT_sp.transpose());
    ZTZ.template triangularView<Eigen::Lower>() = ZTZ.transpose();
    return ZTZ;
}

template <typename T>
inline VectorX_<T> fnnls_solver(const Eigen::Map<MatrixX_<T>> &ZT,
                                const Eigen::Map<VectorX_<T>> &x, int max_iterations = 0,
                                T tolerance = -1.0, const T *const precompute_ptr = nullptr) {
    // This implementation is optimised for speed when ZT is intermediately
    // sparse. Please note that Python uses C-style Row-Major storage and Eigen
    // uses Fortran style Col-Major storage. The incoming Z matrix will appear
    // transposed in Eigen. Hence the name ZT to mimic that a Row-Major matrix
    // from Python was sent in.

    const auto n = ZT.rows();

    if (ZT.cols() != x.rows()) {
        throw std::runtime_error(
            "Mismatched sizes of data matrix ZT and target vector x: ZT size = ("
            + std::to_string(n) + ", " + std::to_string(ZT.cols()) + "), x size = "
            + std::to_string(x.rows()) + " (number of rows of ZT should match the size of x)");
    }

    constexpr auto dzero = T{};
    constexpr auto epsilon = std::numeric_limits<T>::epsilon();
    constexpr auto denorm_min = std::numeric_limits<T>::denorm_min();

    max_iterations = max_iterations ? max_iterations : 3 * n;
    tolerance = tolerance > dzero ? tolerance : epsilon * n;

    const Eigen::SparseMatrix<T> ZT_sp = ZT.sparseView();

    const MatrixX_<T> ZTZ = precompute_ptr
                                ? Eigen::Map<MatrixX_<T>>(const_cast<T *>(precompute_ptr), n, n)
                                : construct_ZTZ<T>(ZT_sp, n);

    const VectorX_<T> ZTx = ZT_sp * x;

    constexpr int max_repetitions{5};
    int no_update{};

    ArrayXb P = ArrayXb::Constant(n, false);
    VectorX_<T> d = VectorX_<T>::Zero(n);
    VectorX_<T> s = VectorX_<T>::Zero(n);
    VectorX_<T> w = ZTx;

    for (int iter{};; ++iter) {
        if (P.all() || (w(to_indices(!P)).maxCoeff() < tolerance)) {
            break;
        } else if (iter == max_iterations) {
            throw std::runtime_error(
                "Solution not converged after maximum number of allowed iterations!");
        }
        const ArrayXb P_previous = P;
        P(argmax_of_masked_array<T>(w, P)) = true;
        s(to_indices(P)) = least_squares_solver<T>(ZTZ, ZTx, to_indices(P));

        for (;;) {
            if (!(P.any()) || (s(to_indices(P)).minCoeff() >= dzero)) {
                break;
            }
            // Coefficients that are in the passive set P, but have become
            // non-positive needs adjustment. alpha has to be larger than 0 and
            // smaller than 1. Precision issues where alpha becomes 0 or 1 for a
            // coefficient in the passive set has to be turned off.
            const T alpha = get_alpha<T>(d, s, to_indices(P && (s.array() < dzero)));
            d.noalias() += alpha * (s - d);
            P(to_indices(d.array() <= denorm_min)) = false;
            s(to_indices(P)) = least_squares_solver<T>(ZTZ, ZTx, to_indices(P));
            s(to_indices(!P)).setZero();
        }

        if ((P_previous == P).all()) {
            ++no_update;
        } else {
            no_update = 0;
        }

        if (no_update >= max_repetitions) {
            break;
        }

        d = s;
        w.noalias() = -(ZTZ * d.sparseView());
        w.noalias() += ZTx;
    }

    // Residual is given by
    // const T residual = (x - ZT.transpose() * d).norm();
    return d;
}
} // namespace fnnls

max_stars_repo_name: mikaeltw/fnnlsEigen

max_issues_repo_name: mikaeltw/fnnlsEigen

max_forks_repo_name: mikaeltw/fnnlsEigen


text:
#include "MyModel.h"
#include "DNest4/code/DNest4.h"
#include <stdexcept>
#include <cmath>
#include <armadillo>
#include <sstream>

namespace Obscurity
{

// CONSTRUCTOR AND MEMBER FUNCTIONS
MyModel::MyModel()
:blobs(4, 100, false, MyConditionalPrior(), DNest4::PriorType::log_uniform)
,obscurer_map(ni, nj)
,convolved(ni, nj)
,star(ni, nj)
,fft_of_star(ni, nj)
{

}

void MyModel::from_prior(DNest4::RNG& rng)
{
    blobs.from_prior(rng);

    DNest4::Cauchy c1(0.0, 1.0);
    x0 = -std::abs(c1.generate(rng));

    DNest4::Cauchy c2(0.0, 0.1*data.get_t_range());
    timescale = std::abs(c2.generate(rng));

    // Limb darkening prior
    // p(x) \propto 0.7752 + 1.4379*x^2.3369
    auto p = [](double x) { return 0.7752 + 1.4379*pow(x, 2.3369); };
    double p_max = p(1.0);
    while(true)
    {
        limb_darkening = rng.rand();
        if(rng.rand() <= p(limb_darkening)/p_max)
            break;
    }

    DNest4::Cauchy c3(0.0, 5.0);
    magnitude = c3.generate(rng);

    noise_boost = rng.rand();
    nu = exp(log(1.0) + log(1E3)*rng.rand());

    calculate_star();
    calculate_obscurer_map();
}

double MyModel::calculate_total_flux(double time) const
{
    double speed = 1.0/timescale;
    double offset = x0 + speed*time;

    int j = (int)floor((offset - (x_min + 0.5*dx))/dx);
    return convolved(ni/2, j%nj);
}

double MyModel::perturb(DNest4::RNG& rng)
{
    double logH = 0.0;

    if(rng.rand() <= 0.7)
    {
        logH += blobs.perturb(rng);
        if(blobs.components_changed())
            calculate_obscurer_map();
    }
    else
    {
        int which = rng.rand_int(6);
        if(which == 0)
        {
            DNest4::Cauchy c(0.0, 1.0);
            logH += c.perturb(x0, rng);
            x0 = -std::abs(x0);
        }
        else if(which == 1)
        {
            DNest4::Cauchy c(0.0, 0.1*data.get_t_range());
            logH += c.perturb(timescale, rng);
            timescale = std::abs(timescale);
        }
        else if(which == 2)
        {
            // Limb darkening prior density
            auto p = [](double x) { return 0.7752 + 1.4379*pow(x, 2.3369); };
            logH -= log(p(limb_darkening));
            limb_darkening += rng.randh();
            DNest4::wrap(limb_darkening, 0.0, 1.0);
            logH += log(p(limb_darkening));

            // Recalculate star
            calculate_star();
        }
        else if(which == 3)
        {
            DNest4::Cauchy c3(0.0, 5.0);
            logH += c3.perturb(magnitude, rng);
        }
        else if(which == 4)
        {
            noise_boost += rng.randh();
            DNest4::wrap(noise_boost, 0.0, 1.0);
        }
        else
        {
            nu = log(nu);
            nu += log(1E3)*rng.randh();
            DNest4::wrap(nu, log(1.0), log(1E3));
            nu = exp(nu);
        }
    }
    return logH;
}

double MyModel::log_likelihood() const
{
    double logL = 0.0;

    const auto& t = data.get_t();
    const auto& y = data.get_y();
    const auto& sig = data.get_sig();

    // Transform from latent U(0, 1) to actual noise-boost factor
    double K = (noise_boost < 0.5)?
               (1.0):
               (exp(log(1E3)*2*(noise_boost - 0.5)));

    // Compute intensive constant factors outside the loop
    double C = std::lgamma(0.5*(nu + 1.0)) - std::lgamma(0.5*nu)
                - 0.5*log(nu*M_PI);

    double model_prediction, scale;
    for(size_t i=0; i<t.size(); ++i)
    {
        model_prediction = magnitude - 2.5*log10(calculate_total_flux(t[i]));
        scale = K*sig[i];
        logL += C - log(scale) - 0.5*(nu+1)*
                        (1.0 + pow(y[i] - model_prediction, 2)/scale/scale/nu);
    }

    return logL;
}

void MyModel::calculate_obscurer_map()
{
    // Obscurer image
    for(size_t j=0; j<nj; ++j)
        for(size_t i=0; i<ni; ++i)
            obscurer_map(i, j) = 0.0;

    const auto& blobs_params = blobs.get_components();
    int i_min, i_max, j_min, j_max;
    double width;

    // Center of mass of blobs
    auto com = com_blobs();

    for(const auto& blob_params: blobs_params)
    {
        // Use position relative to center of mass
        std::vector<double> centered = blob_params;
        centered[0] -= std::get<0>(com);
        centered[1] -= std::get<1>(com);

        width = centered[3]*LL;

        // Determine square patch of image to loop over
        i_min = (int)floor(((y_max - 0.5*dy) - (centered[1] + width))/dy);
        i_max = (int)floor(((y_max - 0.5*dy) - (centered[1] - width))/dy);
        j_min = (int)floor(((centered[0] - width) - (x_min + 0.5*dx))/dx);
        j_max = (int)floor(((centered[0] + width) - (x_min + 0.5*dx))/dx);

        if(i_min < 0)
            i_min = 0;
        if(i_max < 0)
            i_max = 0;
        if(j_min < 0)
            j_min = 0;
        if(j_max < 0)
            j_max = 0;

        if(i_min >= (int)ni)
            i_min = ni - 1;
        if(i_max >= (int)ni)
            i_max = ni - 1;
        if(j_min >= (int)nj)
            j_min = nj - 1;
        if(j_max >= (int)nj)
            j_max = nj - 1;

        for(int j=j_min; j<=j_max; ++j)
            for(int i=i_min; i<=i_max; ++i)
                obscurer_map(i, j) += evaluate_blob(centered, x[j], y[i]);
    }
    for(size_t j=0; j<nj; ++j)
        for(size_t i=0; i<ni; ++i)
            obscurer_map(i, j) = exp(-obscurer_map(i, j));

    // FFT of obscurer_map
    arma::cx_mat A = arma::fft2(obscurer_map);

    // (FFT of obscurer map)*(FFT of star map)
    for(size_t j=0; j<nj; ++j)
        for(size_t i=0; i<ni; ++i)
            A(i, j) *= fft_of_star(i, j);

    // obscurer map convolved with star map
    A = arma::ifft2(A);
    for(size_t i=0; i<ni; ++i)
        for(size_t j=0; j<nj; ++j)
            convolved(i, j) = A(i, j).real();
}

void MyModel::calculate_star()
{
    double rsq;

    // Argh column-major order
    // Star image
    double tot = 0.0;
    for(size_t j=0; j<nj; ++j)
    {
        for(size_t i=0; i<ni; ++i)
        {
            rsq = x[j]*x[j] + y[i]*y[i];
            if(rsq < 1.0)
            {
                star(i, j) = 1.0 -
                    limb_darkening*(1.0 - sqrt(1.0 - rsq));
            }
            else
                star(i, j) = 0.0;
            tot += star(i, j);
        }
    }
    for(size_t j=0; j<nj; ++j)
        for(size_t i=0; i<ni; ++i)
            star(i, j) /= tot;

    arma::mat star2 = star;
    int m, n;
    for(int i=0; i<(int)ni; i++)
    {
        m = DNest4::mod(i - (int)ni/2, (int)ni);
        for(int j=0; j<(int)nj; j++)
        {
            n = DNest4::mod(j - (int)nj/2, (int)nj);
            star2(m, n) = star(i, j);
        }
    }

    fft_of_star = arma::fft2(star2);
}

void MyModel::print(std::ostream& out) const
{
    // Transform from latent U(0, 1) to actual noise-boost factor
    double K = (noise_boost < 0.5)?
               (1.0):
               (exp(log(1E3)*2*(noise_boost - 0.5)));

    out<<x0<<' '<<timescale<<' '<<limb_darkening<<' ';
    out<<K<<' '<<nu<<' ';
    blobs.print(out);

    const auto& t = data.get_t();
    for(size_t i=0; i<t.size(); ++i)
        out<<(magnitude - 2.5*log10(calculate_total_flux(t[i])))<<' ';

    for(size_t i=0; i<ni; ++i)
        for(size_t j=0; j<nj; ++j)
            out<<star(i, j)<<' ';

    for(size_t i=0; i<ni; ++i)
        for(size_t j=0; j<nj; ++j)
            out<<obscurer_map(i, j)<<' ';
}

std::string MyModel::description() const
{
    std::stringstream s;
    s<<"x0, timescale, limb_darkening, K, nu, ";

    s<<"dim_blobs, max_num_blobs, sigma, mu_mass, mu_width, ";
    s<<"num_blobs, ";
    for(int i=0; i<100; ++i)
        s<<"xc["<<i<<"], ";
    for(int i=0; i<100; ++i)
        s<<"yc["<<i<<"], ";
    for(int i=0; i<100; ++i)
        s<<"mass["<<i<<"], ";
    for(int i=0; i<100; ++i)
        s<<"width["<<i<<"], ";

    const auto& t = data.get_t();
    for(size_t i=0; i<t.size(); ++i)
        s<<"model_prediction["<<i<<"], ";

    for(size_t i=0; i<ni; ++i)
        for(size_t j=0; j<nj; ++j)
            s<<"star("<<i<<", "<<j<<"), ";

    for(size_t i=0; i<ni; ++i)
        for(size_t j=0; j<nj; ++j)
            s<<"obscurer_map("<<i<<", "<<j<<"), ";

    return s.str();
}

/* STATIC STUFF */

Data                  MyModel::data;
std::vector<double>   MyModel::x(MyModel::nj);
std::vector<double>   MyModel::y(MyModel::ni);

void MyModel::initialise()
{
    for(size_t i=0; i<ni; ++i)
        y[i] = y_max - (i + 0.5)*dy;

    for(size_t j=0; j<nj; ++j)
        x[j] = x_min + (j + 0.5)*dx;
}

void MyModel::load_data(const char* filename)
{
    data.load(filename);
}

std::tuple<double, double> MyModel::com_blobs() const
{
    double com_x = 0.0;
    double com_y = 0.0;
    double mtot = 0.0;
    const auto& blobs_params = blobs.get_components();

    double xc, yc, mass;
    for(size_t i=0; i<blobs_params.size(); ++i)
    {
        xc = blobs_params[i][0];
        yc = blobs_params[i][1];
        mass = blobs_params[i][2];

        com_x += mass*xc;
        com_y += mass*yc;
        mtot += mass;
    }

    if(blobs_params.size() != 0)
    {
        com_x /= mtot;
        com_y /= mtot;
    }

    return std::tuple<double, double>(com_x, com_y);
}

double MyModel::evaluate_blob(const std::vector<double>& blob_params,
                                                        double x, double y)
{
    static constexpr double C = 2/M_PI;

    double rsq = pow(x - blob_params[0], 2) + pow(y - blob_params[1], 2);
    double widthsq = blob_params[3]*blob_params[3]*LL*LL;

    if(rsq >= widthsq)
        return 0.0;

    return C*blob_params[2]*(1.0 - rsq/widthsq)/widthsq;
}

} // namespace Obscurity

max_stars_repo_name: eggplantbren/Obscurity

max_issues_repo_name: eggplantbren/Obscurity

max_forks_repo_name: eggplantbren/Obscurity


text:
#ifdef WIN32
#pragma execution_character_set("utf-8")
#endif
#include "pclviewer.h"
#include <cstdlib>
#include <iostream>
#include <algorithm>
#include <boost/bind.hpp>
#include"sampleMarkParam/pointcloudparamterconfig.h"

PCLViewer::PCLViewer(QWidget *parent) : QVTKWidget(parent)
{
    initData();
    initConnect();
}

PCLViewer::~PCLViewer()
{

}

void PCLViewer::setIsSelect(bool isSelect)
{
    this->isSelect = isSelect;
}

int PCLViewer::setNewPointCloud(const QString &pcdFilePath)
{
    int errorCode = 0;
    if(PointCloudParamterConfig::getFileType() == PointCloudFileType::PCD_FILE)
    {
        errorCode = pcReader.pcdRead(pcdFilePath.toStdString(), srcCloud, origin, orientation);
        drawRandomColorPointCloud();
    }
    else if(PointCloudParamterConfig::getFileType() == PointCloudFileType::BIN_FILE)
    {
        if(PointCloudParamterConfig::getFieldsNumber() == 3)
        {
            pcl::PointCloud<pcl::PointXYZI>::Ptr cloud(new pcl::PointCloud<pcl::PointXYZI>);
            errorCode = pcReader.xyzBinRead(pcdFilePath.toStdString(), cloud);
            drawRGBPointCloud(cloud);
        }
        else if(PointCloudParamterConfig::getFieldsNumber() == 4)
        {
            pcl::PointCloud<pcl::PointXYZI>::Ptr cloud(new pcl::PointCloud<pcl::PointXYZI>);
            errorCode = pcReader.xyziBinRead(pcdFilePath.toStdString(), cloud);
            drawRGBPointCloud(cloud);
        }
        else if(PointCloudParamterConfig::getFieldsNumber() == 6)
        {
            pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud(new pcl::PointCloud<pcl::PointXYZRGB>);
            errorCode = pcReader.rbgBinRead(pcdFilePath.toStdString(), cloud);
            drawRGBPointCloud(cloud);
        }
    }
    else if(PointCloudParamterConfig::getFileType() == PointCloudFileType::PLY_FILE)
    {
        errorCode = pcReader.plyRead(pcdFilePath.toStdString(), srcCloud);
        drawRandomColorPointCloud();
    }
    return errorCode;
}

void PCLViewer::setOjects(const QList<MyObject> &obejcts, QString sampleClass)
{
    QList<MyObject> rect3DObejcts;
    rect3DObejcts.clear();
    for(int loop = 0; loop < obejcts.count(); loop++)
    {
        const MyObject object = obejcts[loop];
        if(object.getShapeType() == ShapeType::RECT3D_SHAPE)
        {
            rect3DObejcts.append(object);
        }
    }
    this->sampleClass = sampleClass;
    drawShape(rect3DObejcts);
}

void PCLViewer::clearPoints()
{
    viewer->removeAllShapes();
    viewer->removePointCloud("srcCloud");
    if(clickedPoints->size() > 0)
    {
        clickedPoints->clear();
        viewer->updatePointCloud(clickedPoints, "clickedPoints");
        this->update();
    }
}

void PCLViewer::getPoints(pcl::PointCloud<pcl::PointXYZI>::Ptr &result)
{
    result->clear();
    for(const pcl::PointXYZRGB &point: clickedPoints->points)
    {
        pcl::PointXYZI tempPoint;
        tempPoint.x = point.x;
        tempPoint.y = point.y;
        tempPoint.z = point.z;
        tempPoint.intensity = 0;
        result->push_back(tempPoint);
    }
}

void PCLViewer::enterEvent(QEvent *e)
{
    if(isSelect)
    {
        setCursor(myDrawCursor);
    }
    QVTKWidget::enterEvent(e);
}

void PCLViewer::leaveEvent(QEvent *e)
{
    QVTKWidget::leaveEvent(e);
}

void PCLViewer::mouseDoubleClickEvent(QMouseEvent *e)
{
    QVTKWidget::mouseDoubleClickEvent(e);
}

void PCLViewer::clickedPointCallback(const pcl::visualization::PointPickingEvent& event)
{
    if(isSelect)
    {
        bool isIn = false;
        pcl::PointXYZRGB currentPoint;
        if (event.getPointIndex() == -1)
            return;
        event.getPoint(currentPoint.x, currentPoint.y, currentPoint.z);
        currentPoint.r = 0;
        currentPoint.g = 0;
        currentPoint.b = 0;
        for(size_t loop = 0; loop < this->clickedPoints->size(); loop++)
        {
            if(this->clickedPoints->points[loop].x != currentPoint.x
                    && this->clickedPoints->points[loop].y != currentPoint.y
                    && this->clickedPoints->points[loop].z != currentPoint.z)
            {
                isIn = true;
                break;
            }
        }
        if(isIn || this->clickedPoints->size() <= 0)
            this->clickedPoints->push_back(currentPoint);

        pcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZRGB> red(clickedPoints, 255, 0, 0);

        this->viewer->removePointCloud("clickedPoints");
        this->viewer->addPointCloud(this->clickedPoints, red, "clickedPoints");
        this->viewer->setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 5, "clickedPoints");

        this->update();

        std::cout << "point:" << currentPoint.x << " " << currentPoint.y << " " << currentPoint.z << std::endl;
    }
}

void PCLViewer::drawRandomColorPointCloud()
{
    viewer->removePointCloud("srcCloud");
    colorHandler.reset (new pcl::visualization::PointCloudColorHandlerRandom<pcl::PCLPointCloud2>(srcCloud));
    geometryHandler.reset(new pcl::visualization::PointCloudGeometryHandlerXYZ<pcl::PCLPointCloud2>(srcCloud));
    //geometryHandler.reset(new pcl::visualization::PointCloudGeometryHandlerSurfaceNormal<pcl::PCLPointCloud2>(srcCloud));
    viewer->addPointCloud(srcCloud, geometryHandler, colorHandler, origin, orientation, "srcCloud", 0);

    viewer->removeAllShapes();
    viewer->addCube(0, 1.0, 0, 1.0, 0, 1.0, 1, 0, 0, "cube1", 0);
    viewer->setShapeRenderingProperties(pcl::visualization::PCL_VISUALIZER_REPRESENTATION, \
                                        pcl::visualization::PCL_VISUALIZER_REPRESENTATION_WIREFRAME, "cube1");
    viewer->setShapeRenderingProperties(pcl::visualization::PCL_VISUALIZER_COLOR, 255, 255, 0, "cube1");
    viewer->addCube(0, 3.0, 0, 3.0, 0, 3.0, 1, 0, 0, "cube2", 0);
    viewer->setShapeRenderingProperties(pcl::visualization::PCL_VISUALIZER_REPRESENTATION, \
                                        pcl::visualization::PCL_VISUALIZER_REPRESENTATION_WIREFRAME, "cube2");
    viewer->setShapeRenderingProperties(pcl::visualization::PCL_VISUALIZER_COLOR, 255, 255, 0, "cube2");

    this->update();
}

void PCLViewer::drawRGBPointCloud(pcl::PointCloud<pcl::PointXYZI>::Ptr &cloud)
{
    float scale = 10;
    viewer->removePointCloud("srcCloud");
    rgbCloud->clear();
    // Fill the cloud with some points
    for (size_t i = 0; i < cloud->points.size (); ++i)
    {
      pcl::PointXYZRGB point;
      point.x = cloud->points[i].x;
      point.y = cloud->points[i].y;
      point.z = cloud->points[i].z;
      point.r = static_cast<unsigned char>(cloud->points[i].intensity * scale);
      point.g = static_cast<unsigned char>(cloud->points[i].intensity * scale);
      point.b = static_cast<unsigned char>(cloud->points[i].intensity * scale);
      rgbCloud->push_back(point);
    }
    viewer->addPointCloud(rgbCloud, "srcCloud");

    viewer->removeAllShapes();
    viewer->addCube(0, 1.0, 0, 1.0, 0, 1.0, 1, 0, 0, "cube1", 0);
    viewer->setShapeRenderingProperties(pcl::visualization::PCL_VISUALIZER_REPRESENTATION, \
                                        pcl::visualization::PCL_VISUALIZER_REPRESENTATION_WIREFRAME, "cube1");
    viewer->setShapeRenderingProperties(pcl::visualization::PCL_VISUALIZER_COLOR, 255, 255, 0, "cube1");
    viewer->addCube(0, 3.0, 0, 3.0, 0, 3.0, 1, 0, 0, "cube2", 0);
    viewer->setShapeRenderingProperties(pcl::visualization::PCL_VISUALIZER_REPRESENTATION, \
                                        pcl::visualization::PCL_VISUALIZER_REPRESENTATION_WIREFRAME, "cube2");
    viewer->setShapeRenderingProperties(pcl::visualization::PCL_VISUALIZER_COLOR, 255, 255, 0, "cube2");

    this->update();
}

void PCLViewer::drawRGBPointCloud(pcl::PointCloud<pcl::PointXYZRGB>::Ptr &cloud)
{
    viewer->removePointCloud("srcCloud");
    rgbCloud->clear();
    // Fill the cloud with some points
    for (size_t i = 0; i < cloud->points.size (); ++i)
    {
      rgbCloud->push_back(cloud->points[i]);
    }
    viewer->addPointCloud(rgbCloud, "srcCloud");
    this->update();
}

void PCLViewer::drawShape(const QList<MyObject> &obejcts)
{
    viewer->removeAllShapes();
    drawCircle();
    for(int loop = 0; loop < obejcts.count(); loop++)
    {
        if(sampleClass == "All")
        {
            drawObject(obejcts[loop], loop);
        }
        else
        {
            if(obejcts[loop].getObjectClass().contains(sampleClass))
            {
                drawObject(obejcts[loop], loop);
            }
        }
    }
    this->update();
}

void PCLViewer::drawCircle()
{
    pcl::ModelCoefficients circleCoeff1;
    circleCoeff1.values.resize(3);
    circleCoeff1.values[0] = 0;
    circleCoeff1.values[1] = 0;
    circleCoeff1.values[2] = 50.0f;
    viewer->addCircle(circleCoeff1, "circle1", 0);
    viewer->setShapeRenderingProperties(pcl::visualization::PCL_VISUALIZER_REPRESENTATION, \
                                        pcl::visualization::PCL_VISUALIZER_REPRESENTATION_WIREFRAME, "circle1");
    viewer->setShapeRenderingProperties(pcl::visualization::PCL_VISUALIZER_COLOR, 255, 0, 0, "circle1");

    pcl::ModelCoefficients circleCoeff2;
    circleCoeff2.values.resize(3);
    circleCoeff2.values[0] = 0;
    circleCoeff2.values[1] = 0;
    circleCoeff2.values[2] = 100.0f;
    viewer->addCircle(circleCoeff2, "circle2", 0);
    viewer->setShapeRenderingProperties(pcl::visualization::PCL_VISUALIZER_REPRESENTATION, \
                                        pcl::visualization::PCL_VISUALIZER_REPRESENTATION_WIREFRAME, "circle2");
    viewer->setShapeRenderingProperties(pcl::visualization::PCL_VISUALIZER_COLOR, 255, 255, 0, "circle2");
}

void PCLViewer::drawObject(const MyObject &object, int id)
{
    pcl::PointXYZ point;
    const MyRect3D rect3d = object.getBox3D();
    QString boxId = QString("box_%1").arg(id);
    Rotation yaw = transform.getRotation(0, 0, rect3d.theta);
    double length = static_cast<double>(rect3d.size[0]);
    double width = static_cast<double>(rect3d.size[1]);
    double height = static_cast<double>(rect3d.size[2]);
    point.x = rect3d.center[0];
    point.y = rect3d.center[1];
    point.z = rect3d.center[2] + static_cast<float>(height / 2.0);
    viewer->addText3D<pcl::PointXYZ>(object.getObjectClass().toStdString(), point, 1.0, \
                                     255, 255, 0, QString("text_%1").arg(id).toStdString());
    viewer->addCube(rect3d.center, yaw, length, width, height, boxId.toStdString());
    viewer->setShapeRenderingProperties(pcl::visualization::PCL_VISUALIZER_REPRESENTATION, \
                                        pcl::visualization::PCL_VISUALIZER_REPRESENTATION_WIREFRAME, boxId.toStdString());
    viewer->setShapeRenderingProperties(pcl::visualization::PCL_VISUALIZER_COLOR, 255, 0, 0, boxId.toStdString());
}

void PCLViewer::initData()
{
    viewer.reset (new pcl::visualization::PCLVisualizer("cloud", false));
    initCloud();

    colorHandler.reset (new pcl::visualization::PointCloudColorHandlerRandom<pcl::PCLPointCloud2>(srcCloud));
    geometryHandler.reset (new pcl::visualization::PointCloudGeometryHandlerXYZ<pcl::PCLPointCloud2>(srcCloud));
    viewer->addPointCloud (srcCloud, geometryHandler, colorHandler, origin, orientation, "srcCloud", 0);
    viewer->setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 2, "srcCloud", 0);
    viewer->setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_IMMEDIATE_RENDERING, 1.0, "srcCloud");

    this->SetRenderWindow(viewer->getRenderWindow());
    viewer->setupInteractor(this->GetInteractor (), this->GetRenderWindow ());

    viewer->setBackgroundColor(0, 0, 0);
    viewer->setCameraPosition(0, 0, 0, 0, 0, 0, 0, 0, -1);
    viewer->addCoordinateSystem(1.0);
    viewer->initCameraParameters();
    viewer->cameraParamsSet ();
    viewer->cameraFileLoaded ();
    viewer->resetCameraViewpoint("srcCloud");
    viewer->resetCamera();

    viewer->registerPointPickingCallback(boost::bind(&PCLViewer::clickedPointCallback, this, _1));

    // Set whether or not we should be using the vtkVertexBufferObjectMapper
    viewer->setUseVbos(true);

    this->update();

    sampleClass = "All";

    isSelect = false;
    myDrawCursor = QCursor(QPixmap(tr(":/images/images/cross.png")));
}

void PCLViewer::initConnect()
{

}

void PCLViewer::initCloud()
{
    srcCloud.reset(new pcl::PCLPointCloud2);
    rgbCloud.reset(new pcl::PointCloud<pcl::PointXYZRGB>);
    clickedPoints.reset(new pcl::PointCloud<pcl::PointXYZRGB>);
}


text:
/*=============================================================================
    Copyright (c) 2009 Daniel James
    Copyright (c) 2002 2004 2006 Joel de Guzman
    Copyright (c) 2004 Eric Niebler
    http://spirit.sourceforge.net/

    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)
=============================================================================*/

#if !defined(BOOST_SPIRIT_QUICKBOOK_QUICKBOOK_HPP)
#define BOOST_SPIRIT_QUICKBOOK_QUICKBOOK_HPP

#include "fwd.hpp"
#include "values.hpp"
#include <boost/filesystem/path.hpp>
#include <string>
#include <time.h>
#include <vector>

namespace quickbook {
namespace fs = boost::filesystem;

extern tm *current_time;    // the current time
extern tm *current_gm_time; // the current UTC time
extern bool debug_mode;
extern bool self_linked_headers;
extern std::vector<fs::path> include_path;
extern std::vector<std::string> preset_defines;
extern fs::path image_location;

void parse_file(quickbook::state &state, value include_doc_id = value(),
                bool nested_file = false);
// Some initialisation methods
//
// Declared here to avoid including other headers
namespace detail {
void initialise_markups();
}
} // namespace quickbook

#endif

max_stars_repo_name: henrywarhurst/matrix

max_issues_repo_name: henrywarhurst/matrix

max_forks_repo_name: henrywarhurst/matrix


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

#include <boost/hana/functional.hpp>

#include <boost/hana/detail/assert.hpp>
#include <boost/hana/detail/constexpr.hpp>
using namespace boost::hana;

struct _extra { virtual ~_extra() { } };
_extra extra{};

#define BOOST_HANA_TEST_BINARY_OP(op, x, y)                                 \
    BOOST_HANA_CONSTEXPR_ASSERT((_ op _)(x, y) == (x op y));                \
    BOOST_HANA_RUNTIME_ASSERT((_ op _)(x, y, extra) == (x op y));           \
    BOOST_HANA_RUNTIME_ASSERT((_ op _)(x, y, extra, extra) == (x op y));    \
                                                                            \
    BOOST_HANA_CONSTEXPR_ASSERT((_ op y)(x) == (x op y));                   \
    BOOST_HANA_RUNTIME_ASSERT((_ op y)(x, extra) == (x op y));              \
    BOOST_HANA_RUNTIME_ASSERT((_ op y)(x, extra, extra) == (x op y));       \
                                                                            \
    BOOST_HANA_CONSTEXPR_ASSERT((x op _)(y) == (x op y));                   \
    BOOST_HANA_RUNTIME_ASSERT((x op _)(y, extra) == (x op y));              \
    BOOST_HANA_RUNTIME_ASSERT((x op _)(y, extra, extra) == (x op y));       \
/**/

#define BOOST_HANA_TEST_UNARY_OP(op, x)                                     \
    BOOST_HANA_CONSTEXPR_ASSERT((op _)(x) == (op x));                       \
    BOOST_HANA_RUNTIME_ASSERT((op _)(x, extra) == (op x));                  \
    BOOST_HANA_RUNTIME_ASSERT((op _)(x, extra, extra) == (op x));           \
/**/

int main() {
    // Arithmetic
    BOOST_HANA_TEST_UNARY_OP(+, 1)
    BOOST_HANA_TEST_UNARY_OP(-, 1)
    BOOST_HANA_TEST_BINARY_OP(+, 6, 3)
    BOOST_HANA_TEST_BINARY_OP(-, 6, 3)
    BOOST_HANA_TEST_BINARY_OP(*, 6, 3)
    BOOST_HANA_TEST_BINARY_OP(/, 6, 3)
    BOOST_HANA_TEST_BINARY_OP(%, 6, 3)

    // Bitwise
    BOOST_HANA_TEST_UNARY_OP(~, 5)
    BOOST_HANA_TEST_BINARY_OP(&, 6, 3)
    BOOST_HANA_TEST_BINARY_OP(|, 6, 3)
    BOOST_HANA_TEST_BINARY_OP(^, 6, 3)
    BOOST_HANA_TEST_BINARY_OP(<<, 6, 3)
    BOOST_HANA_TEST_BINARY_OP(>>, 6, 3)

    // Comparison
    BOOST_HANA_TEST_BINARY_OP(==, 6, 3)
    BOOST_HANA_TEST_BINARY_OP(!=, 6, 3)
    BOOST_HANA_TEST_BINARY_OP(<, 6, 3)
    BOOST_HANA_TEST_BINARY_OP(<=, 6, 3)
    BOOST_HANA_TEST_BINARY_OP(>, 6, 3)
    BOOST_HANA_TEST_BINARY_OP(>=, 6, 3)

    // Logical
    BOOST_HANA_TEST_BINARY_OP(||, true, false)
    BOOST_HANA_TEST_BINARY_OP(&&, true, true)
    BOOST_HANA_TEST_UNARY_OP(!, true)

    // Member access
    constexpr int i = 4;
    constexpr int array[] = {0, 1, 2};
    BOOST_HANA_TEST_UNARY_OP(*, &i)

    BOOST_HANA_CONSTEXPR_ASSERT(_[0](array) == array[0]);
    BOOST_HANA_RUNTIME_ASSERT(_[0](array, extra) == array[0]);
    BOOST_HANA_RUNTIME_ASSERT(_[0](array, extra, extra) == array[0]);
    BOOST_HANA_CONSTEXPR_ASSERT(_[1](array) == array[1]);
    BOOST_HANA_CONSTEXPR_ASSERT(_[1](array) == array[1]);
    BOOST_HANA_CONSTEXPR_ASSERT(_[2](array) == array[2]);

    // Other
    BOOST_HANA_CONSTEXPR_LAMBDA auto f = [](auto x) { return x + 1; };
    BOOST_HANA_CONSTEXPR_ASSERT(_(1)(f) == f(1));
    BOOST_HANA_RUNTIME_ASSERT(_(1)(f, extra) == f(1));
    BOOST_HANA_RUNTIME_ASSERT(_(1)(f, extra, extra) == f(1));
    BOOST_HANA_CONSTEXPR_ASSERT(_(2)(f) == f(2));
    BOOST_HANA_CONSTEXPR_ASSERT(_(3)(f) == f(3));
}

max_stars_repo_name: rbock/hana

max_issues_repo_name: rbock/hana

max_forks_repo_name: rbock/hana


text:
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE Hello
#include <boost/test/unit_test.hpp>

BOOST_AUTO_TEST_CASE( test1 )
{
	BOOST_TEST( 2 == 1 );
}

BOOST_AUTO_TEST_CASE( test2 )
{
	int i = 0;

	BOOST_TEST( i == 2 );
	BOOST_TEST( i == 0 );
}

max_stars_repo_name: zzragida/CppExamples

max_issues_repo_name: zzragida/CppExamples

max_forks_repo_name: zzragida/CppExamples


text:
// Copyright (c) 2006, 2007 Julio M. Merino Vidal
// Copyright (c) 2008 Ilya Sokolov, Boris Schaeling
// Copyright (c) 2009 Boris Schaeling
// Copyright (c) 2010 Felipe Tanus, Boris Schaeling
// Copyright (c) 2011, 2012 Jeff Flinn, Boris Schaeling
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#define BOOST_TEST_MAIN
#define BOOST_TEST_IGNORE_SIGCHLD
#include <boost/test/included/unit_test.hpp>

#include <boost/process/error.hpp>
#include <boost/process/async.hpp>
#include <boost/process/child.hpp>

#include <boost/system/error_code.hpp>
#include <boost/asio.hpp>
#if defined(BOOST_WINDOWS_API)
#   include <Windows.h>
typedef boost::asio::windows::stream_handle pipe_end;
#elif defined(BOOST_POSIX_API)
#   include <sys/wait.h>
#   include <signal.h>
typedef boost::asio::posix::stream_descriptor pipe_end;
#endif

namespace bp = boost::process;

BOOST_AUTO_TEST_CASE(sync_wait)
{
    using boost::unit_test::framework::master_test_suite;

    std::error_code ec;
    bp::child c(
        master_test_suite().argv[1],
        "test", "--exit-code", "123",
        ec
    );
    BOOST_REQUIRE(!ec);
    c.wait();
    int exit_code = c.exit_code();

    BOOST_CHECK_EQUAL(123, exit_code);

    c.wait();
}

#if defined(BOOST_WINDOWS_API)
struct wait_handler
{
    HANDLE handle_;

    wait_handler(HANDLE handle) : handle_(handle) {}

    void operator()(const boost::system::error_code &ec)
    {
        BOOST_REQUIRE(!ec);
        DWORD exit_code;
        BOOST_REQUIRE(GetExitCodeProcess(handle_, &exit_code));
        BOOST_CHECK_EQUAL(123, exit_code);
    }
};
#elif defined(BOOST_POSIX_API)
struct wait_handler
{
    void operator()(const boost::system::error_code &ec, int signal)
    {
        BOOST_REQUIRE(!ec);
        BOOST_REQUIRE_EQUAL(SIGCHLD, signal);
        int status;
        wait(&status);
        BOOST_CHECK_EQUAL(123, WEXITSTATUS(status));
    }
};
#endif

BOOST_AUTO_TEST_CASE(async_wait)
{
    using boost::unit_test::framework::master_test_suite;
    using namespace boost::asio;

    boost::asio::io_service io_service;

#if defined(BOOST_POSIX_API)
    signal_set set(io_service, SIGCHLD);
    set.async_wait(wait_handler());
#endif

    std::error_code ec;
    bp::child c(
        master_test_suite().argv[1],
        "test", "--exit-code", "123",
        ec
    );
    BOOST_REQUIRE(!ec);

#if defined(BOOST_WINDOWS_API)
    windows::object_handle handle(io_service, c.native_handle());
    handle.async_wait(wait_handler(handle.native()));
#endif
    std::cout << "async_wait 1" << std::endl;
    io_service.run();
    std::cout << "async_wait 2" << std::endl;
}

max_stars_repo_name: lijgame/boost

max_issues_repo_name: lijgame/boost

max_forks_repo_name: lijgame/boost


text:
//  (C) Copyright Nick Thompson 2020.
//  Use, modification and distribution are 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)

#include <random>
#include <iostream>
#include <iomanip>
#include <benchmark/benchmark.h>
#include <boost/math/tools/cohen_acceleration.hpp>
#include <boost/multiprecision/float128.hpp>
#include <boost/multiprecision/mpfr.hpp>
#include <boost/multiprecision/cpp_bin_float.hpp>
#include <boost/core/demangle.hpp>

using boost::multiprecision::number;
using boost::multiprecision::mpfr_float_backend;
using boost::multiprecision::float128;
using boost::multiprecision::cpp_bin_float_50;
using boost::multiprecision::cpp_bin_float_100;
using boost::math::tools::cohen_acceleration;
using boost::math::constants::pi;

template<typename Real>
class G {
public:
    G(){
        k_ = 0;
    }

    Real operator()() {
        k_ += 1;
        return 1/(k_*k_);
    }

private:
    Real k_;
};

template<class Real>
void CohenAcceleration(benchmark::State& state)
{
    using std::abs;
    Real x = pi<Real>()*pi<Real>()/12;
    for (auto _ : state)
    {
        auto g = G<Real>();
        x = cohen_acceleration(g);
        benchmark::DoNotOptimize(x);
    }
    if (abs(x - pi<Real>()*pi<Real>()/12) > 16*std::numeric_limits<Real>::epsilon())
    {
        std::cerr << std::setprecision(std::numeric_limits<Real>::max_digits10);
        std::cerr << "Cohen acceleration computed " << x << " on type " << boost::core::demangle(typeid(Real).name()) << "\n";
        std::cerr << "But expected value is       " << pi<Real>()*pi<Real>()/12 << "\n";
    }
}

BENCHMARK_TEMPLATE(CohenAcceleration, float);
BENCHMARK_TEMPLATE(CohenAcceleration, double);
BENCHMARK_TEMPLATE(CohenAcceleration, long double);
BENCHMARK_TEMPLATE(CohenAcceleration, float128);
BENCHMARK_TEMPLATE(CohenAcceleration, cpp_bin_float_50);
BENCHMARK_TEMPLATE(CohenAcceleration, cpp_bin_float_100);
BENCHMARK_TEMPLATE(CohenAcceleration, number<mpfr_float_backend<100>>);
BENCHMARK_TEMPLATE(CohenAcceleration, number<mpfr_float_backend<200>>);
BENCHMARK_TEMPLATE(CohenAcceleration, number<mpfr_float_backend<300>>);
BENCHMARK_TEMPLATE(CohenAcceleration, number<mpfr_float_backend<400>>);
BENCHMARK_TEMPLATE(CohenAcceleration, number<mpfr_float_backend<1000>>);

template<class Real>
void NaiveSum(benchmark::State& state)
{
    using std::abs;
    Real x = pi<Real>()*pi<Real>()/12;
    for (auto _ : state)
    {
        auto g = G<Real>();
        Real term = g();
        x = term;
        bool even = false;
        while (term > std::numeric_limits<Real>::epsilon()/2) {
            term = g();
            if (even) {
                x += term;
                even = false;
            } else {
                x -= term;
                even = true;
            }
        }
        benchmark::DoNotOptimize(x);
    }
    // The accuracy tests don't pass because the sum is ill-conditioned:
    /*if (abs(x - pi<Real>()*pi<Real>()/12) > 16*std::numeric_limits<Real>::epsilon())
    {
        std::cerr << std::setprecision(std::numeric_limits<Real>::max_digits10);
        std::cerr << "Cohen acceleration computed " << x << " on type " << boost::core::demangle(typeid(Real).name()) << "\n";
        std::cerr << "But expected value is       " << pi<Real>()*pi<Real>()/12 << "\n";
    }*/
}

BENCHMARK_TEMPLATE(NaiveSum, float);
BENCHMARK_TEMPLATE(NaiveSum, double);
BENCHMARK_TEMPLATE(NaiveSum, long double);
BENCHMARK_TEMPLATE(NaiveSum, float128);
BENCHMARK_TEMPLATE(NaiveSum, cpp_bin_float_50);
BENCHMARK_TEMPLATE(NaiveSum, cpp_bin_float_100);
BENCHMARK_TEMPLATE(NaiveSum, number<mpfr_float_backend<100>>);
BENCHMARK_TEMPLATE(NaiveSum, number<mpfr_float_backend<200>>);
BENCHMARK_TEMPLATE(NaiveSum, number<mpfr_float_backend<300>>);
BENCHMARK_TEMPLATE(NaiveSum, number<mpfr_float_backend<400>>);
BENCHMARK_TEMPLATE(NaiveSum, number<mpfr_float_backend<1000>>);

BENCHMARK_MAIN();

max_stars_repo_name: oleg-alexandrov/math

max_issues_repo_name: oleg-alexandrov/math