text:
#include "dynet/nodes.h"
#include "dynet/dynet.h"
#include "dynet/training.h"
#include "dynet/timing.h"
#include "dynet/rnn.h"
#include "dynet/gru.h"
#include "dynet/lstm.h"
#include "dynet/fast-lstm.h"
#include "dynet/expr.h"

#include <iostream>
#include <fstream>
#include <sstream>
#include <type_traits>
#include <sys/types.h>
#include <sys/stat.h>

#include <boost/archive/text_iarchive.hpp>
#include <boost/archive/text_oarchive.hpp>
#include <boost/program_options.hpp>

#include "s2s/dynet/dict.h"
#include "s2s/corpus/options.hpp"
#include "s2s/corpus/corpora.hpp"
#include "s2s/corpus/dicts.hpp"
#include "s2s/corpus/batch.hpp"
#include "s2s/nn/encdec.hpp"

#ifndef INCLUDE_GUARD_ENCODER_DECODER_BASE_HPP
#define INCLUDE_GUARD_ENCODER_DECODER_BASE_HPP

namespace s2s {

class encoder_decoder_base : public encoder_decoder {

public:

    std::vector<dynet::Expression> h_bi;
    dynet::Expression i_feed;

    explicit encoder_decoder_base(dynet::ParameterCollection& model, const s2s_options& opts, dicts& d) : encoder_decoder(model,opts,d) {

        flag_drop_out = true;
        unsigned int dec_feeding_size = 0;

        assert(opts.dec_feature_vocab_size.size() == opts.dec_feature_vec_size.size());
        unsigned int cell_ratio = 2; // In GRU, cell_ratio = 1;

        p_dec_init_w.resize(opts.num_layers * cell_ratio);
        for(unsigned int i = 0; i < opts.num_layers * cell_ratio; i++){
            p_dec_init_w[i] = model.add_parameters({opts.rnn_size, opts.rnn_size});
        }
        p_dec_init_bias.resize(opts.num_layers * cell_ratio);
        for(unsigned int i = 0; i < opts.num_layers * cell_ratio; i++){
            p_dec_init_bias[i] = model.add_parameters({opts.rnn_size});
        }
        if(opts.additional_output_layer == true){
            dec_feeding_size = opts.rnn_size;
        }else{
            dec_feeding_size = opts.rnn_size * 3;
        }
        if(opts.additional_output_layer == true){
            p_add_W = model.add_parameters({dec_feeding_size, opts.rnn_size * 3});
            p_add_bias = model.add_parameters({dec_feeding_size});
            p_out_R = model.add_parameters({d.dict_set_trg.d_word.size(), opts.rnn_size});
            p_out_bias = model.add_parameters({d.dict_set_trg.d_word.size()});
        }else{
            p_out_R = model.add_parameters({d.dict_set_trg.d_word.size(), dec_feeding_size});
            p_out_bias = model.add_parameters({d.dict_set_trg.d_word.size()});
        }

        dec_builder = dynet::VanillaLSTMBuilder(
            opts.num_layers,
            (rev_enc_builder.input_dim + dec_feeding_size + 3),
            opts.rnn_size,
            model
        );

    }

    encoder_decoder_base(const encoder_decoder_base&) = delete;
    encoder_decoder_base& operator=(const encoder_decoder_base&) = delete;
    ~encoder_decoder_base() = default;

    void encoder(const batch &batch_local, dynet::ComputationGraph& cg) {
        // initialize
        init(batch_local, cg);
        // embedding
        embedding(batch_local, cg);

        std::vector<dynet::Expression> h_fwd(slen);
        std::vector<dynet::Expression> h_bwd(slen);
        h_bi.resize(slen);

        // forward encoder
        fwd_enc_builder.new_graph(cg);
        fwd_enc_builder.start_new_sequence();
        if(flag_drop_out == true && opts.dropout_rate_lstm_word > 0.f){
            fwd_enc_builder.set_dropout_masks(batch_size);
        }
        for (unsigned int t_i = 0; t_i < slen; ++t_i) {
            fwd_enc_builder.add_input(h_lookup[t_i]);
            h_fwd[t_i] = fwd_enc_builder.back();
        }
        // backward encoder
        rev_enc_builder.new_graph(cg);
        rev_enc_builder.start_new_sequence();
        if(flag_drop_out == true && opts.dropout_rate_lstm_word > 0.f){
            rev_enc_builder.set_dropout_masks(batch_size);
        }
        for (unsigned int ind = 0; ind < slen; ++ind) {
            unsigned int t_i = (slen - 1) - ind;
            rev_enc_builder.add_input(h_lookup[t_i]);
            h_bwd[t_i] = rev_enc_builder.back();
        }
        // bidirectional encoding
        for (unsigned int t_i = 0; t_i < slen; ++t_i) {
            h_bi[t_i] = concatenate(std::vector<dynet::Expression>({h_fwd[t_i], h_bwd[t_i]}));
        }
        // Initialize decoder
        std::vector<dynet::Expression> vec_enc_final_state;
        vec_enc_final_state = rev_enc_builder.final_s();
        dec_builder.new_graph(cg);
        if(opts.additional_connect_layer){
            std::vector<dynet::Expression> vec_dec_init_state;
            for (unsigned int i = 0; i < vec_enc_final_state.size(); i++){
                dynet::Expression i_dec_init_w = parameter(cg, p_dec_init_w[i]);
                dynet::Expression i_dec_init_bias = parameter(cg, p_dec_init_bias[i]);
                vec_dec_init_state.push_back(tanh(i_dec_init_w * vec_enc_final_state[i] + i_dec_init_bias));
            }
            dec_builder.start_new_sequence(vec_dec_init_state);
        }else{
            dec_builder.start_new_sequence(vec_enc_final_state);
        }
        if(flag_drop_out == true && opts.dropout_rate_lstm_word > 0.f){
            dec_builder.set_dropout_masks(batch_size);
        }
        init_feed(batch_local, cg);
    }

    void init_feed(const batch &batch_local, dynet::ComputationGraph& cg){
        i_feed = dynet::zeroes(cg, dynet::Dim({p_out_R.dim().d[1]}, batch_local.batch_size()));
    }

    dynet::Expression decoder_output(dynet::ComputationGraph& cg,  const std::vector<unsigned int> prev, const unsigned int t){
        return decoder_output(cg, prev, t, dec_builder.state());
    }

    dynet::Expression decoder_output(dynet::ComputationGraph& cg,  const std::vector<unsigned int> prev, const unsigned int t, const dynet::RNNPointer pointer_prev){
        // t should be always larger than 0.
        assert(t > 0);
        // convert previous label to the bit features.
        std::vector<dynet::real> bit_features;
        const unsigned int start_id = d.dict_set_trg.start_id_word;
        const unsigned int kep_id = d.dict_set_trg.keep_id_word;
        const unsigned int del_id = d.dict_set_trg.delete_id_word;
        for(unsigned int batch_id = 0; batch_id < prev.size(); batch_id++){
            // start
            if(prev[batch_id] == start_id){
                bit_features.push_back(opts.bit_size_flt);
            }else{
                bit_features.push_back(0.0f);
            }
            // keep
            if(prev[batch_id] == kep_id){
                bit_features.push_back(opts.bit_size_flt);
            }else{
                bit_features.push_back(0.0f);
            }
            // delete
            if(prev[batch_id] == del_id){
                bit_features.push_back(opts.bit_size_flt);
            }else{
                bit_features.push_back(0.0f);
            }
        }
        dynet::Expression i_x_t = dynet::input(cg, dynet::Dim({3}, batch_size), bit_features);
        dynet::Expression i_dec_input = concatenate(std::vector<dynet::Expression>({i_x_t, i_feed}));
        i_dec_input = concatenate(std::vector<dynet::Expression>({i_dec_input, h_lookup[t]}));
        dec_builder.add_input(pointer_prev, i_dec_input);
        dynet::Expression i_h_dec = dec_builder.h.back().back();
        if(opts.additional_output_layer){
            dynet::Expression i_add_W = parameter(cg, p_add_W);
            dynet::Expression i_add_bias = parameter(cg, p_add_bias);
            i_feed = tanh(i_add_W * concatenate(std::vector<dynet::Expression>({i_h_dec, h_bi[t]})) + i_add_bias);
        }else{
            i_feed = concatenate(std::vector<dynet::Expression>({i_h_dec, h_bi[t]}));
        }
        dynet::Expression i_out_R = parameter(cg, p_out_R);
        dynet::Expression i_out_bias = parameter(cg, p_out_bias);
        dynet::Expression i_out_pred_t = i_out_R * i_feed + i_out_bias;
        return i_out_pred_t;
    }

    void disable_dropout(){
        fwd_char_enc_builder.disable_dropout();
        rev_char_enc_builder.disable_dropout();
        fwd_enc_builder.disable_dropout();
        rev_enc_builder.disable_dropout();
        dec_builder.disable_dropout();
        flag_drop_out = false;
    }

    void enable_dropout(){
        fwd_char_enc_builder.set_dropout(opts.dropout_rate_lstm_char, 0.f);
        rev_char_enc_builder.set_dropout(opts.dropout_rate_lstm_char, 0.f);
        fwd_enc_builder.set_dropout(opts.dropout_rate_lstm_word, 0.f);
        rev_enc_builder.set_dropout(opts.dropout_rate_lstm_word, 0.f);
        dec_builder.set_dropout(opts.dropout_rate_lstm_word, 0.f);
        flag_drop_out = true;
    }

private:
    friend class boost::serialization::access;
    template<class Archive>
    void serialize(Archive & ar, const unsigned int version) {
        ar & p_word_enc;
        ar & p_char_enc;
        ar & p_feat_enc;
        ar & p_dec_init_bias;
        ar & p_dec_init_w;
        ar & p_layer_w;
        ar & p_add_W;
        ar & p_add_bias;
        ar & p_out_R;
        ar & p_out_bias;
        ar & dec_builder;
        ar & rev_char_enc_builder;
        ar & fwd_char_enc_builder;
        ar & rev_enc_builder;
        ar & fwd_enc_builder;
    }

};

}

#endif

max_stars_repo_name: kamigaito/SLAHAN

max_issues_repo_name: kamigaito/SLAHAN

max_forks_repo_name: kamigaito/SLAHAN


text:
#ifndef BOOST_OUTBUF_STRING_HPP
#define BOOST_OUTBUF_STRING_HPP

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

#include <string>
#if defined(__cpp_exceptions)
#include <exception>
#endif

#include <boost/outbuf.hpp>

namespace boost {
namespace detail {

template <typename T, bool NoExcept, typename CharT>
class string_writer_mixin;

template <typename T, typename CharT>
class string_writer_mixin<T, false, CharT>
{
public:

    string_writer_mixin() = default;

    void do_recycle()
    {
        auto * p = static_cast<T*>(this)->pos();
        static_cast<T*>(this)->set_pos(_buf);

        if (p >= buf_begin() && static_cast<T*>(this)->good())
        {
            if (p > buf_end())
            {
                p = buf_end();
            }
            static_cast<T*>(this)->set_good(false);
            static_cast<T*>(this)->_append(buf_begin(), p);
            static_cast<T*>(this)->set_good(true);
        }
    }
    void do_finish()
    {
        auto * p = static_cast<T*>(this)->pos();
        if (p >= buf_begin() && static_cast<T*>(this)->good())
        {
            if (p > buf_end())
            {
                p = buf_end();
            }
            static_cast<T*>(this)->set_good(false);
            static_cast<T*>(this)->_append(buf_begin(), p);
        }
    }

    CharT* buf_begin()
    {
        return _buf;
    }
    CharT* buf_end()
    {
        return _buf + _buf_size;
    }

private:

    static constexpr std::size_t _buf_size
        = boost::min_size_after_recycle<CharT>();
    CharT _buf[_buf_size];
};

#if defined(__cpp_exceptions)

template <typename T, typename CharT>
class string_writer_mixin<T, true, CharT>
{
public:

    string_writer_mixin() = default;

    void do_recycle() noexcept
    {
        auto * p = static_cast<T*>(this)->pos();
        static_cast<T*>(this)->set_pos(buf_begin());

        if (static_cast<T*>(this)->good() && buf_begin() <= p)
        {
            if (p > buf_end())
            {
                p = buf_end();
            }
            try
            {
                static_cast<T*>(this)->_append(buf_begin(), p);
            }
            catch(...)
            {
                _eptr = std::current_exception();
                static_cast<T*>(this)->set_good(false);
            }
        }
    }

    void do_finish()
    {
        if (_eptr != nullptr)
        {
            std::rethrow_exception(_eptr);
        }
        BOOST_ASSERT(static_cast<T*>(this)->good());
        auto * p = static_cast<T*>(this)->pos();
        if (buf_begin() <= p)
        {
            if (p > buf_end())
            {
                p = buf_end();
            }
            static_cast<T*>(this)->set_good(false);
            auto p = static_cast<T*>(this)->pos();
            if (p >= buf_begin())
            {
                if (p > buf_end())
                {
                    p = buf_end();
                }
                static_cast<T*>(this)->_append(buf_begin(), p);
            }
        }
    }

    CharT* buf_begin()
    {
        return _buf;
    }
    CharT* buf_end()
    {
        return _buf + _buf_size;
    }

private:

    std::exception_ptr _eptr = nullptr;
    static constexpr std::size_t _buf_size
        = boost::min_size_after_recycle<CharT>();
    CharT _buf[_buf_size];
};

#else // defined(__cpp_exceptions)

template <typename T, typename CharT>
class string_writer_mixin<T, true, CharT>
    : public string_writer_mixin<T, false, CharT>
{
};

#endif // defined(__cpp_exceptions)

template < bool NoExcept
         , typename CharT
         , typename Traits
         , typename Allocator >
class basic_string_appender_impl
    : public boost::detail::basic_outbuf_noexcept_switch<NoExcept, CharT>
    , protected boost::detail::string_writer_mixin
        < basic_string_appender_impl<NoExcept, CharT, Traits, Allocator>
        , NoExcept
        , CharT >
{
public:

    using string_type = std::basic_string<CharT, Traits>;

    basic_string_appender_impl(string_type& str_)
        : boost::detail::basic_outbuf_noexcept_switch<NoExcept, CharT>
            ( boost::outbuf_garbage_buf<CharT>()
            , boost::outbuf_garbage_buf_end<CharT>() )
        , _str(str_)
    {
        this->set_pos(this->buf_begin());
        this->set_end(this->buf_end());
    }
    basic_string_appender_impl() = delete;
    basic_string_appender_impl(const basic_string_appender_impl&) = delete;
    basic_string_appender_impl(basic_string_appender_impl&&) = delete;
    ~basic_string_appender_impl() = default;

    void finish()
    {
        this->do_finish();
    }

    void do_reserve(std::size_t s)
    {
        _str.reserve(_str.size() + s);
    }

private:

    template <typename, bool, typename>
    friend class detail::string_writer_mixin;

    void _append(const CharT* begin, const CharT* end)
    {
        _str.append(begin, end);
    }

    string_type& _str;
};

template < bool NoExcept
         , typename CharT
         , typename Traits
         , typename Allocator >
class basic_string_maker_impl
    : public boost::detail::basic_outbuf_noexcept_switch<NoExcept, CharT>
    , protected boost::detail::string_writer_mixin
        < basic_string_maker_impl<NoExcept, CharT, Traits, Allocator>
        , NoExcept
        , CharT >
{
public:

    using string_type = std::basic_string<CharT, Traits>;

    basic_string_maker_impl()
        : boost::detail::basic_outbuf_noexcept_switch<NoExcept, CharT>
            ( boost::outbuf_garbage_buf<CharT>()
            , boost::outbuf_garbage_buf_end<CharT>() )
    {
        this->set_pos(this->buf_begin());
        this->set_end(this->buf_end());
    }

    basic_string_maker_impl(const basic_string_maker_impl&) = delete;
    basic_string_maker_impl(basic_string_maker_impl&&) = delete;
    ~basic_string_maker_impl() = default;

    string_type finish()
    {
        this->do_finish();
        return std::move(_str);
    }

    void do_reserve(std::size_t s)
    {
        _str.reserve(s);
    }

private:

    template <typename, bool, typename>
    friend class detail::string_writer_mixin;

    void _append(const CharT* begin, const CharT* end)
    {
        _str.append(begin, end);
    }

    string_type _str;
};

} // namespace detail

template < typename CharT
         , typename Traits = std::char_traits<CharT>
         , typename Allocator = std::allocator<CharT>  >
class basic_string_appender_noexcept final
    : public boost::detail::basic_string_appender_impl
        < true, CharT, Traits, Allocator >
{
public:

    using boost::detail::basic_string_appender_impl
        < true, CharT, Traits, Allocator >
        ::basic_string_appender_impl;

    void recycle() noexcept(true) override
    {
        this->do_recycle();
    }

    void reserve(std::size_t s)
    {
        this->do_reserve(s);
    }
};

template < typename CharT
         , typename Traits = std::char_traits<CharT>
         , typename Allocator = std::allocator<CharT> >
class basic_string_appender final
    : public boost::detail::basic_string_appender_impl
        < false, CharT, Traits, Allocator >
{
public:

    using boost::detail::basic_string_appender_impl
        < false, CharT, Traits, Allocator >
        ::basic_string_appender_impl;

    void recycle() override
    {
        this->do_recycle();
    }

    void reserve(std::size_t s)
    {
        this->do_reserve(s);
    }
};

template < typename CharT
         , typename Traits = std::char_traits<CharT>
         , typename Allocator = std::allocator<CharT> >
class basic_string_maker_noexcept final
    : public boost::detail::basic_string_maker_impl
        < true, CharT, Traits, Allocator >
{
public:

    using boost::detail::basic_string_maker_impl
        < true, CharT, Traits, Allocator >
        ::basic_string_maker_impl;

    void recycle() noexcept(true) override
    {
        this->do_recycle();
    }

    void reserve(std::size_t s)
    {
        this->do_reserve(s);
    }
};

template < typename CharT
         , typename Traits = std::char_traits<CharT>
         , typename Allocator = std::allocator<CharT> >
class basic_string_maker final
    : public boost::detail::basic_string_maker_impl
        < false, CharT, Traits, Allocator >
{
public:

    using boost::detail::basic_string_maker_impl
        < false, CharT, Traits, Allocator >
        ::basic_string_maker_impl;

    void recycle() override
    {
        this->do_recycle();
    }

    void reserve(std::size_t s)
    {
        this->do_reserve(s);
    }
};

using string_appender = basic_string_appender<char>;
using u16string_appender = basic_string_appender<char16_t>;
using u32string_appender = basic_string_appender<char32_t>;
using wstring_appender = basic_string_appender<wchar_t>;

using string_maker = basic_string_maker<char>;
using u16string_maker = basic_string_maker<char16_t>;
using u32string_maker = basic_string_maker<char32_t>;
using wstring_maker = basic_string_maker<wchar_t>;

using string_appender_noexcept = basic_string_appender_noexcept<char>;
using u16string_appender_noexcept = basic_string_appender_noexcept<char16_t>;
using u32string_appender_noexcept = basic_string_appender_noexcept<char32_t>;
using wstring_appender_noexcept = basic_string_appender_noexcept<wchar_t>;

using string_maker_noexcept = basic_string_maker_noexcept<char>;
using u16string_maker_noexcept = basic_string_maker_noexcept<char16_t>;
using u32string_maker_noexcept = basic_string_maker_noexcept<char32_t>;
using wstring_maker_noexcept = basic_string_maker_noexcept<wchar_t>;

#if defined(__cpp_char8_t)

using u8string_appender = basic_string_appender<char8_t>;
using u8string_maker = basic_string_maker<char8_t>;
using u8string_appender_noexcept = basic_string_appender_noexcept<char8_t>;
using u8string_maker_noexcept = basic_string_maker_noexcept<char8_t>;

#endif

} // namespace boost

#endif  // BOOST_OUTBUF_STRING_HPP

ext: hpp


text:
// Copyright (c) 2014, Samuel A. Roth. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can
// be found in the COPYING file.

#ifndef DATA_HPP_F6Z1XF
#define DATA_HPP_F6Z1XF

#include <memory>
#include <string>
#include <vector>
#include <ostream>
#include <iostream>
#include <unordered_map>
#include <boost/format.hpp>
#include "stream.hpp"
#include "streamindent.hpp"
#include "util.hpp"
namespace autobind {

// std::string gensym(const std::string &prefix="G");

class Module;
class ConversionInfo;

/// Represents the bindings for a C++ declaration.
class Export
{
	std::string _name;
public:
	Export(std::string name)
	: _name(std::move(name)) { }
	virtual ~Export() { }

	const std::string &name() const { return _name; }

	virtual void setModule(Module &) { }

	/// Forward-declare the bindings.
	virtual void codegenDeclaration(std::ostream &) const = 0;
	/// Define the bindings.
	virtual void codegenDefinition(std::ostream &) const = 0;
	/// Emit an entry suitable for inclusion in the PyMethodDef[] table, if applicable.
	virtual void codegenMethodTable(std::ostream &) const = 0;
	/// Emit any code that needs to be run on module init.
	virtual void codegenInit(std::ostream &) const { }

	/// Incorporate the other export into this one. If this is not possible, throw std::runtime_error.
	/// (Do this by calling the superclass implementation.)
	/// This may be used to implement overloading.
	virtual void merge(const Export &other)
	{
		throw std::runtime_error("Cannot merge export " + name() + " with " + other.name());
	}

	virtual bool validate(const ConversionInfo &) const
	{
		return true;
	}
};

} // namespace autobind

#endif // DATA_HPP_F6Z1XF

max_stars_repo_name: sam-roth/autobind

max_issues_repo_name: sam-roth/autobind

max_forks_repo_name: sam-roth/autobind


text:
//
// Copyright Jason Rice 2017
// 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)
//

#include <nbdl/ui_helper/params_concat.hpp>
#include <nbdl/ui_spec.hpp>

#include <boost/hana/equal.hpp>
#include <boost/hana/integral_constant.hpp>
#include <boost/hana/map.hpp>
#include <boost/hana/pair.hpp>
#include <catch.hpp>
#include <string>

namespace hana = boost::hana;

TEST_CASE("Concatenate ui_spec params into an std::string.", "[ui_helper][params_concat]")
{
  constexpr hana::string<'f', 'o', 'o'> foo_s;
  constexpr hana::string<'b', 'a', 'r'> bar_s;
  constexpr hana::string<'b', 'a', 'z'> baz_s;

  auto store = hana::make_map(hana::make_pair(hana::int_c<0>, std::string(" Hello, world! ")));

  constexpr auto params = mpdef::make_list(
    foo_s
  , bar_s
  , baz_s
  , nbdl::ui_spec::get(hana::int_c<0>)
  , foo_s
  );

  std::string result = nbdl::ui_helper::params_concat(params, store).to_string();
  CHECK(result == std::string("foobarbaz Hello, world! foo"));
}

ext: cpp

max_stars_repo_name: ricejasonf/nbdl

max_issues_repo_name: ricejasonf/nbdl

max_forks_repo_name: ricejasonf/nbdl


text:
#include <iostream>
#include <fstream>
#include <string>

#include <boost/tokenizer.hpp>
#include <boost/algorithm/string/predicate.hpp>

#include <map>

#include <openmht/plot/gnuplot-iostream.h>
#include <openmht/plot/Plot.h>

#include <boost/make_shared.hpp>

#include <stdio.h>
#include <termios.h>
#include <unistd.h>
#include <fcntl.h>

using std::cout;
using std::endl;

namespace openmht
{
     Plot::Plot()
     {
          gp_ = boost::make_shared<Gnuplot>();
     }

     //void Plot::plot_frames(std::list<swarm_proto::Frame> &frames, int divide, bool enable_3d)
     //{
     //     int count = 0;
     //     std::map<int,std::list<swarm_proto::Vector3d> > tracks;
     //     for (std::list<swarm_proto::Frame>::iterator it = frames.begin();
     //          it != frames.end(); it++, count++) {
     //
     //          if (count % divide == 0) {
     //               for (int i = 0; i < it->contact_size(); i++) {
     //                    swarm_proto::Vector3d pos;
     //                    pos.set_x(it->contact(i).state().position().x());
     //                    pos.set_y(it->contact(i).state().position().y());
     //                    pos.set_z(it->contact(i).state().position().z());
     //
     //                    tracks[it->contact(i).id().id()].push_back(pos);
     //               }
     //          }
     //     }
     //
     //     // Convert map into list
     //     std::list< std::list<swarm_proto::Vector3d> > lists;
     //     std::list<std::string> labels;
     //     std::list<std::string> styles;
     //
     //     for(std::map<int,std::list<swarm_proto::Vector3d> >::iterator it = tracks.begin();
     //         it != tracks.end(); it++) {
     //          lists.push_back(it->second);
     //          labels.push_back(swarm::int2str(it->first));
     //          styles.push_back("linespoints");
     //     }
     //
     //     std::string title = "Swarm Tracks";
     //     std::list<std::string> objects;
     //
     //     std::string options = "";
     //     //options += "set size ratio -1\n";
     //     //options += "set view equal xy\n";
     //     //options += "set size 1,1\n";
     //
     //     options += "set xlabel \"X\"\n";
     //     options += "set ylabel \"Y\"\n";
     //     options += "set ticslevel 0\n";
     //     options += "set key outside\n";
     //     options += "set grid xtics ytics\n";
     //
     //     this->plot(lists, title, labels, styles, options, objects, enable_3d);
     //}
     //
     void Plot::plot(std::list< std::map<int, std::list<Eigen::Vector2d> > > &lists,
                     const std::string &title,
                     std::list<std::string> &labels,
                     std::list<std::string> &styles,
                     std::string options,
                     std::list<std::string> &objects,
                     bool enable_3d)
     {
          (*gp_) << "reset\n";
          (*gp_) << "set title '" << title << "'\n";

          if (options != "") {
               (*gp_) << options;
          }

          // Draw objects
          for(std::list<std::string>::iterator it = objects.begin();
              it != objects.end(); it++) {
               (*gp_) << *it << endl;
          }

          if (enable_3d) {
               (*gp_) << "splot";
          } else {
               (*gp_) << "plot";
          }

          std::list<std::string>::iterator it_styles = styles.begin();
          std::list<std::string>::iterator it_labels = labels.begin();
          for (std::list< std::map<int, std::list<Eigen::Vector2d> > >::iterator it = lists.begin(); it != lists.end(); it++) {
               for (std::map<int, std::list<Eigen::Vector2d> >::iterator it_map = it->begin(); it_map != it->end(); it_map++) {

                    std::list<double> xLocs;
                    std::list<double> yLocs;
                    std::list<double> zLocs;

                    std::list<Eigen::Vector2d>::iterator it2;
                    for (it2 = it_map->second.begin() ; it2 != it_map->second.end() ; it2++) {
                         xLocs.push_back((*it2)(0,0));
                         yLocs.push_back((*it2)(1,0));
                         zLocs.push_back(0);
                    }

                    if (enable_3d) {
                         (*gp_) << (*gp_).file1d(std::make_tuple(xLocs,yLocs,zLocs));
                    } else {
                         (*gp_) << (*gp_).file1d(std::make_pair(xLocs,yLocs));
                    }
                    (*gp_) << "with " << *it_styles  << " title '" << it_map->first << "-" << *it_labels << "'";

                    if (++it_map != it->end()) {
                         (*gp_) << ",";
                    }
                    --it_map;
               }
               if (++it != lists.end()) {
                    (*gp_) << ",";
               }
               --it;

               it_styles++;
               it_labels++;
          }
          it_styles = styles.begin();
          it_labels = labels.begin();

          (*gp_) << endl;
     }

     void Plot::wait()
     {
          cout << "Hit any key to continue." << endl;
          while(kbhit() == 0);
     }

     int Plot::kbhit()
     {
          struct termios oldt, newt;
          int ch;
          int oldf;

          tcgetattr(STDIN_FILENO, &oldt);
          newt = oldt;
          newt.c_lflag &= ~(ICANON | ECHO);
          tcsetattr(STDIN_FILENO, TCSANOW, &newt);
          oldf = fcntl(STDIN_FILENO, F_GETFL, 0);
          fcntl(STDIN_FILENO, F_SETFL, oldf | O_NONBLOCK);

          ch = getchar();

          tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
          fcntl(STDIN_FILENO, F_SETFL, oldf);

          if(ch != EOF)
          {
               ungetc(ch, stdin);
               return 1;
          }

          return 0;
     }

     void Plot::gnuplot_test()
     {
          //Gnuplot gp;
          Gnuplot gp("gnuplot -persist");
          // Create a script which can be manually fed into gnuplot later:
          //    Gnuplot gp(">script.gp");
          // Create script and also feed to gnuplot:
          //    Gnuplot gp("tee plot.gp | gnuplot -persist");
          // Or choose any of those options at runtime by setting the GNUPLOT_IOSTREAM_CMD
          // environment variable.

          // Gnuplot lists (i.e. arrows) require four columns: (x,y,dx,dy)
          std::list<boost::tuple<double, double, double, double> > pts_A;

          // You can also use a separate container for each column, like so:
          std::list<double> pts_B_x;
          std::list<double> pts_B_y;
          std::list<double> pts_B_dx;
          std::list<double> pts_B_dy;

          // You could also use:
          //   std::list<std::list<double> >
          //   boost::tuple of four std::list's
          //   std::list of std::tuple (if you have C++11)
          //   arma::mat (with the Armadillo library)
          //   blitz::Array<blitz::TinyList<double, 4>, 1> (with the Blitz++ library)
          // ... or anything of that sort

          for(double alpha=0; alpha<1; alpha+=1.0/24.0) {
               double theta = alpha*2.0*3.14159;
               pts_A.push_back(boost::make_tuple(
                                    cos(theta),
                                    sin(theta),
                                    -cos(theta)*0.1,
                                    -sin(theta)*0.1
                                    ));

               pts_B_x .push_back( cos(theta)*0.8);
               pts_B_y .push_back( sin(theta)*0.8);
               pts_B_dx.push_back( sin(theta)*0.1);
               pts_B_dy.push_back(-cos(theta)*0.1);
          }

          // Don't forget to put "\n" at the end of each line!
          gp << "set xrange [-2:2]\nset yrange [-2:2]\n";
          // '-' means read from stdin.  The send1d() function sends data to gnuplot's stdin.
          gp << "plot '-' with vectors title 'pts_A', '-' with vectors title 'pts_B'\n";
          gp.send1d(pts_A);
          gp.send1d(boost::make_tuple(pts_B_x, pts_B_y, pts_B_dx, pts_B_dy));
     }
}

max_stars_repo_name: SyllogismRXS/openmht

max_issues_repo_name: SyllogismRXS/openmht

max_forks_repo_name: SyllogismRXS/openmht


text:
/* Copyright Institute of Sound and Vibration Research - All rights reserved */

#include "biquad_coefficient.hpp"

#include <libvisr/detail/compose_message_string.hpp>

#include <boost/property_tree/json_parser.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>

#include <istream>
#include <iostream>
#include <sstream>
#include <string>

namespace visr
{
namespace rbbl
{

template< typename CoeffType >
/*static*/ BiquadCoefficient<CoeffType>
BiquadCoefficient<CoeffType>::fromJson( boost::property_tree::ptree const & tree )
{
  BiquadCoefficient<CoeffType> res;
  res.loadJson( tree );
  return res;
}

template< typename CoeffType >
/*static*/ BiquadCoefficient<CoeffType>
BiquadCoefficient<CoeffType>::fromJson( std::basic_istream<char> & stream )
{
  BiquadCoefficient<CoeffType> res;
  res.loadJson( stream );
  return res;
}

template< typename CoeffType >
/*static*/ BiquadCoefficient<CoeffType>
BiquadCoefficient<CoeffType>::fromXml( boost::property_tree::ptree const & tree )
{
  BiquadCoefficient<CoeffType> res;
  res.loadXml( tree );
  return res;
}

template< typename CoeffType >
/*static*/ BiquadCoefficient<CoeffType>
BiquadCoefficient<CoeffType>::fromXml( std::basic_istream<char> & stream )
{
  BiquadCoefficient<CoeffType> res;
  res.loadXml( stream );
  return res;
}

template< typename CoeffType >
void BiquadCoefficient<CoeffType>::loadJson( boost::property_tree::ptree const & tree )
{
  // boost::property_tree::ptree const biquadTree = tree.get_child( "biquad" );

  CoeffType const a0 = tree.get<CoeffType>( "a0", static_cast<CoeffType>(1.0f) );
  at( 0 ) = tree.get<CoeffType>( "b0" ) / a0;
  at( 1 ) = tree.get<CoeffType>( "b1" ) / a0;
  at( 2 ) = tree.get<CoeffType>( "b2" ) / a0;
  at( 3 ) = tree.get<CoeffType>( "a1" ) / a0;
  at( 4 ) = tree.get<CoeffType>( "a2" ) / a0;
}

template< typename CoeffType >
void BiquadCoefficient<CoeffType>::loadJson( std::basic_istream<char> & stream )
{
  boost::property_tree::ptree tree;
  try
  {
    read_json( stream, tree );
  }
  catch( std::exception const & ex )
  {
    throw std::invalid_argument( detail::composeMessageString( "Error while parsing a json BiquadCoefficient node: " , ex.what( )) );
  }
  loadJson( tree );
}

template< typename CoeffType >
void BiquadCoefficient<CoeffType>::loadXml( boost::property_tree::ptree const & tree )
{
  // Hack: Depending from where this method is called, we don't know
  boost::property_tree::ptree const biquadTree = tree.count( "biquad" ) == 0
    ? tree : tree.get_child( "biquad" );

  boost::optional<CoeffType> const a0Optional = biquadTree.get_optional<CoeffType>( "<xmlattr>.a0" );
  CoeffType const a0 = a0Optional ? *a0Optional : static_cast<CoeffType>(1.0f);
  CoeffType const a1 = biquadTree.get<CoeffType>( "<xmlattr>.a1" );
  CoeffType const a2 = biquadTree.get<CoeffType>( "<xmlattr>.a2" );
  CoeffType const b0 = biquadTree.get<CoeffType>( "<xmlattr>.b0" );
  CoeffType const b1 = biquadTree.get<CoeffType>( "<xmlattr>.b1" );
  CoeffType const b2 = biquadTree.get<CoeffType>( "<xmlattr>.b2" );

  at( 0 ) = b0 / a0;
  at( 1 ) = b1 / a0;
  at( 2 ) = b2 / a0;
  at( 3 ) = a1 / a0;
  at( 4 ) = a2 / a0;
}

template< typename CoeffType >
void BiquadCoefficient<CoeffType>::loadXml( std::basic_istream<char> & stream )
{
  boost::property_tree::ptree tree;
  try
  {
    read_xml( stream, tree );
  }
  catch( std::exception const & ex )
  {
    throw std::invalid_argument( std::string( "Error while parsing a XML BiquadCoefficient node: " ) + ex.what( ) );
  }
  loadXml( tree );
}

template< typename CoeffType >
void BiquadCoefficient<CoeffType>::writeJson( boost::property_tree::ptree & tree ) const
{
  tree.put( "b0", b0() );
  tree.put( "b1", b1( ) );
  tree.put( "b2", b2( ) );
  tree.put( "a1", a1( ) );
  tree.put( "a2", a2( ) );
}

template< typename CoeffType >
void BiquadCoefficient<CoeffType>::writeJson( std::basic_ostream<char> & stream ) const
{
  boost::property_tree::ptree tree;
  writeJson( tree );
  try
  {
    write_json( stream, tree);
  } catch (std::exception const & ex)
  {
    throw( detail::composeMessageString( "Error while writing BiquadCoefficient message to JSON: ", ex.what() ) );
  }
}

template< typename CoeffType >
void BiquadCoefficient<CoeffType>::writeJson( std::string & str ) const
{
  std::stringstream stream;
  writeJson( stream );
  str = stream.str();
}

template< typename CoeffType >
void BiquadCoefficient<CoeffType>::writeXml( boost::property_tree::ptree & tree ) const
{
  // TODO: implement me!
  assert( false );
}

template< typename CoeffType >
void BiquadCoefficient<CoeffType>::writeXml( std::basic_ostream<char> & stream ) const
{
  boost::property_tree::ptree tree;
  writeJson( tree );

}

template< typename CoeffType >
void BiquadCoefficient<CoeffType>::writeXml( std::string & str ) const
{
}

///////////////////////////////////////////////////////////////////////////////

template< typename CoeffType >
/*static*/ BiquadCoefficientList<CoeffType>
BiquadCoefficientList<CoeffType>::fromJson( boost::property_tree::ptree const & tree )
{
  BiquadCoefficientList<CoeffType> ret;
  ret.loadJson( tree );
  return ret;
}

template< typename CoeffType >
/*static*/ BiquadCoefficientList<CoeffType>
BiquadCoefficientList<CoeffType>::fromJson( std::basic_istream<char> & stream )
{
  BiquadCoefficientList<CoeffType> ret;
  ret.loadJson( stream );
  return ret;
}

template< typename CoeffType >
/*static*/ BiquadCoefficientList<CoeffType>
BiquadCoefficientList<CoeffType>::fromJson( std::string const & str )
{
  BiquadCoefficientList<CoeffType> ret;
  ret.loadJson( str );
  return ret;

}

template< typename CoeffType >
/*static*/ BiquadCoefficientList<CoeffType>
BiquadCoefficientList<CoeffType>::fromXml( boost::property_tree::ptree const & tree )
{
  BiquadCoefficientList<CoeffType> ret;
  ret.loadXml( tree );
  return ret;
}

template< typename CoeffType >
/*static*/ BiquadCoefficientList<CoeffType>
BiquadCoefficientList<CoeffType>::fromXml( std::basic_istream<char> & stream )
{
  BiquadCoefficientList<CoeffType> ret;
  ret.loadXml( stream );
  return ret;
}

template< typename CoeffType >
/*static*/ BiquadCoefficientList<CoeffType>
BiquadCoefficientList<CoeffType>::fromXml( std::string const & str )
{
  BiquadCoefficientList<CoeffType> ret;
  ret.loadXml( str );
  return ret;
}

template< typename CoeffType >
void BiquadCoefficientList<CoeffType>::loadJson( boost::property_tree::ptree const & tree )
{
  auto const biquadNodes = tree.equal_range( "" );
  std::size_t const numBiquads = std::distance( biquadNodes.first, biquadNodes.second );
  resize( numBiquads );
  std::size_t biqIndex = 0;
  for( boost::property_tree::ptree::const_assoc_iterator treeIt( biquadNodes.first ); treeIt != biquadNodes.second; ++treeIt, ++biqIndex )
  {
    boost::property_tree::ptree const childTree = treeIt->second;
    at( biqIndex ).loadJson( childTree );
  }
}

template< typename CoeffType >
void BiquadCoefficientList<CoeffType>::loadJson( std::basic_istream<char> & stream )
{
  boost::property_tree::ptree tree;
  try
  {
    read_json( stream, tree );
  }
  catch( std::exception const & ex )
  {
    throw std::invalid_argument( std::string( "Error while parsing a JSON BiquadCoefficientList representation: " ) + ex.what( ) );
  }
  loadJson( tree );
}

template< typename CoeffType >
void BiquadCoefficientList<CoeffType>::loadJson( std::string const & str )
{
  std::stringstream stream( str );
  loadJson( stream );
}

template< typename CoeffType >
void BiquadCoefficientList<CoeffType>::loadXml( boost::property_tree::ptree const & tree )
{
  // Hack: Depending from where this method is called, we don't know
  boost::property_tree::ptree const specNode = tree.count( "filterSpec" ) == 0
    ? tree : tree.get_child( "filterSpec" );

  auto const biquadNodes = specNode.equal_range( "biquad" );
  std::size_t const numBiquads = std::distance( biquadNodes.first, biquadNodes.second );
  resize( numBiquads );
  std::size_t biqIndex = 0;
  for( boost::property_tree::ptree::const_assoc_iterator treeIt( biquadNodes.first ); treeIt != biquadNodes.second; ++treeIt, ++biqIndex )
  {
    boost::property_tree::ptree const childTree = treeIt->second;
    at( biqIndex ).loadXml( childTree );
  }
}

template< typename CoeffType >
void BiquadCoefficientList<CoeffType>::loadXml( std::basic_istream<char> & stream )
{
  boost::property_tree::ptree tree;
  try
  {
    read_xml( stream, tree );
  }
  catch( std::exception const & ex )
  {
    throw std::invalid_argument( std::string( "Error while parsing a XML BiquadCoefficient node: " ) + ex.what( ) );
  }
  loadXml( tree );
}

template< typename CoeffType >
void BiquadCoefficientList<CoeffType>::loadXml( std::string const & str )
{
  std::stringstream stream( str );
  loadXml( stream );
}

template< typename CoeffType >
void BiquadCoefficientList<CoeffType>::writeJson( boost::property_tree::ptree & tree ) const
{
  for( std::size_t idx( 0 ); idx < size(); ++idx )
  {
    boost::property_tree::ptree child;
    at( idx ).writeJson( child );
    tree.push_back( std::make_pair( "", child ) );
  }
}

template< typename CoeffType >
void BiquadCoefficientList<CoeffType>::writeJson( std::basic_ostream<char> & stream ) const
{
  boost::property_tree::ptree tree;
  writeJson( tree );
  try
  {
    write_json( stream, tree );
  }
  catch( std::exception const & ex )
  {
    throw std::invalid_argument( std::string( "Error while writing a BiquadCoefficientList to JSON: " ) + ex.what( ) );
  }
}

template< typename CoeffType >
void BiquadCoefficientList<CoeffType>::writeJson( std::string & str ) const
{
  std::stringstream stream;
  writeJson( stream );
  str = stream.str();
}

template< typename CoeffType >
void BiquadCoefficientList<CoeffType>::writeXml( boost::property_tree::ptree & tree ) const
{
  // TODO: implement me!
  assert( false );
}

template< typename CoeffType >
void BiquadCoefficientList<CoeffType>::writeXml( std::basic_ostream<char> & stream ) const
{
  boost::property_tree::ptree tree;
  writeXml( tree );
  try
  {
    write_xml( stream, tree );
  }
  catch( std::exception const & ex )
  {
    throw std::invalid_argument( std::string( "Error while writing BiquadCoefficientList to XML: " ) + ex.what( ) );
  }
}

template< typename CoeffType >
void BiquadCoefficientList<CoeffType>::writeXml( std::string & str ) const
{
  std::stringstream stream;
  writeXml( stream );
  str = stream.str();
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////

template<typename CoeffType>
BiquadCoefficientMatrix<CoeffType>::BiquadCoefficientMatrix( std::size_t numberOfFilters, std::size_t numberOfBiquads )
{
  resize( numberOfFilters, numberOfBiquads );
}

template<typename CoeffType>
BiquadCoefficientMatrix<CoeffType>::~BiquadCoefficientMatrix()
{
}

template<typename CoeffType>
void BiquadCoefficientMatrix<CoeffType>::resize( std::size_t numberOfFilters, std::size_t numberOfBiquads )
{
  mRows.clear(); // Needed to trigger the re-initialisation of all rows even if the size decreases or stayed constant.
  // Define the initial entry for all filter rows (numberOfBiquads 'default' biquad specs)
  BiquadCoefficientList<CoeffType> templ( numberOfBiquads );
  mRows.resize( numberOfFilters, templ );
}

template<typename CoeffType>
void BiquadCoefficientMatrix<CoeffType>::setFilter( std::size_t filterIdx, BiquadCoefficientList<CoeffType> const & newFilter )
{
  if( filterIdx >= numberOfFilters() )
  {
    throw std::out_of_range( "BiquadCoefficientMatrix::setFilter(): Filter index exceeds maximum admissible value." );
  }
  if( newFilter.size() > numberOfSections() )
  {
    throw std::invalid_argument( "BiquadCoefficientMatrix::setFilter(): The number index exceeds maximum admissible value." );
  }
  BiquadCoefficientList<CoeffType> & row = mRows[filterIdx];
  std::copy( &newFilter[0], &newFilter[0] + newFilter.size(), &row[0] );
  std::fill_n( &row[0] + newFilter.size(),
    numberOfSections()
    - newFilter.size(), BiquadCoefficient<CoeffType>() );
}

template< typename CoeffType >
/*static*/ BiquadCoefficientMatrix<CoeffType>
BiquadCoefficientMatrix<CoeffType>::fromJson( boost::property_tree::ptree const & tree )
{
  BiquadCoefficientMatrix<CoeffType> ret{0,0};
  ret.loadJson( tree );
  return ret;
}

template< typename CoeffType >
/*static*/ BiquadCoefficientMatrix<CoeffType>
BiquadCoefficientMatrix<CoeffType>::fromJson( std::basic_istream<char> & stream )
{
  BiquadCoefficientMatrix<CoeffType> ret{0,0};
  ret.loadJson( stream );
  return ret;
}

template< typename CoeffType >
/*static*/ BiquadCoefficientMatrix<CoeffType>
BiquadCoefficientMatrix<CoeffType>::fromJson( std::string const & str )
{
  BiquadCoefficientMatrix<CoeffType> ret{0,0};
  ret.loadJson( str );
  return ret;

}

template< typename CoeffType >
/*static*/ BiquadCoefficientMatrix<CoeffType>
BiquadCoefficientMatrix<CoeffType>::fromXml( boost::property_tree::ptree const & tree )
{
  BiquadCoefficientMatrix<CoeffType> ret{0,0};
  ret.loadXml( tree );
  return ret;
}

template< typename CoeffType >
/*static*/ BiquadCoefficientMatrix<CoeffType>
BiquadCoefficientMatrix<CoeffType>::fromXml( std::basic_istream<char> & stream )
{
  BiquadCoefficientMatrix<CoeffType> ret{0,0};
  ret.loadXml( stream );
  return ret;
}

template< typename CoeffType >
/*static*/ BiquadCoefficientMatrix<CoeffType>
BiquadCoefficientMatrix<CoeffType>::fromXml( std::string const & str )
{
  BiquadCoefficientMatrix<CoeffType> ret{0,0};
  ret.loadXml( str );
  return ret;
}

template< typename CoeffType >
void BiquadCoefficientMatrix<CoeffType>::loadJson( boost::property_tree::ptree const & tree )
{
  auto const channelNodes = tree.equal_range( "" );
  std::size_t const numChannels = std::distance( channelNodes.first, channelNodes.second );
  if( numChannels == 0 )
  {
    resize( 0, 0 ); // return empty matrix
  }
  std::size_t static const unInitMarker = std::numeric_limits<std::size_t>::max();
  std::size_t numBiquads = unInitMarker;
  std::size_t rowIdx{ 0 };
  for( boost::property_tree::ptree::const_assoc_iterator channelIt( channelNodes.first ); channelIt != channelNodes.second; ++channelIt, ++rowIdx )
  {
    boost::property_tree::ptree const channelTree = channelIt->second;
    BiquadCoefficientList<CoeffType> const rowFilters = BiquadCoefficientList<CoeffType>::fromJson( channelTree );
    if( rowIdx == 0 )
    {
      numBiquads = rowFilters.size();
      resize( numChannels, numBiquads );
    }
    assert( numBiquads != unInitMarker ); // Check that initialisation is performed during the first run.
    if( rowFilters.size() != numBiquads )
    {
      std::invalid_argument( "BiquadCoefficientMatrix::loadJSON(): Encountered matrix rows with differing sizes." );
    }
    setFilter( rowIdx, rowFilters );
  }
}

template< typename CoeffType >
void BiquadCoefficientMatrix<CoeffType>::loadJson( std::basic_istream<char> & stream )
{
  boost::property_tree::ptree tree;
  try
  {
    read_json( stream, tree );
  }
  catch( std::exception const & ex )
  {
    throw std::invalid_argument( std::string( "Error while parsing a JSON BiquadCoefficientMatrix representation: " ) + ex.what() );
  }
  loadJson( tree );
}

template< typename CoeffType >
void BiquadCoefficientMatrix<CoeffType>::loadJson( std::string const & str )
{
  std::stringstream stream( str );
  loadJson( stream );
}

template< typename CoeffType >
void BiquadCoefficientMatrix<CoeffType>::loadXml( boost::property_tree::ptree const & tree )
{
#if 0
  // Hack: Depending from where this method is called, we don't know
  boost::property_tree::ptree const specNode = tree.count( "filterSpec" ) == 0
    ? tree : tree.get_child( "filterSpec" );

  auto const biquadNodes = specNode.equal_range( "biquad" );
  std::size_t const numBiquads = std::distance( biquadNodes.first, biquadNodes.second );
  resize( numBiquads );
  std::size_t biqIndex = 0;
  for( boost::property_tree::ptree::const_assoc_iterator treeIt( biquadNodes.first ); treeIt != biquadNodes.second; ++treeIt, ++biqIndex )
  {
    boost::property_tree::ptree const childTree = treeIt->second;
    at( biqIndex ).loadXml( childTree );
  }
#endif
}

template< typename CoeffType >
void BiquadCoefficientMatrix<CoeffType>::loadXml( std::basic_istream<char> & stream )
{
  boost::property_tree::ptree tree;
  try
  {
    read_xml( stream, tree );
  }
  catch( std::exception const & ex )
  {
    throw std::invalid_argument( std::string( "Error while parsing a XML BiquadCoefficient node: " ) + ex.what() );
  }
  loadXml( tree );
}

template< typename CoeffType >
void BiquadCoefficientMatrix<CoeffType>::loadXml( std::string const & str )
{
  std::stringstream stream( str );
  loadXml( stream );
}

template< typename CoeffType >
void BiquadCoefficientMatrix<CoeffType>::writeJson( boost::property_tree::ptree & tree ) const
{
#if 0
  for( std::size_t idx( 0 ); idx < size(); ++idx )
  {
    boost::property_tree::ptree child;
    at( idx ).writeJson( child );
    tree.push_back( std::make_pair( "", child ) );
  }
#endif
}

template< typename CoeffType >
void BiquadCoefficientMatrix<CoeffType>::writeJson( std::basic_ostream<char> & stream ) const
{
  boost::property_tree::ptree tree;
  writeJson( tree );
  try
  {
    write_json( stream, tree );
  }
  catch( std::exception const & ex )
  {
    throw std::invalid_argument( std::string( "Error while writing a BiquadCoefficientMatrix to JSON: " ) + ex.what() );
  }
}

template< typename CoeffType >
void BiquadCoefficientMatrix<CoeffType>::writeJson( std::string & str ) const
{
  std::stringstream stream;
  writeJson( stream );
  str = stream.str();
}

template< typename CoeffType >
void BiquadCoefficientMatrix<CoeffType>::writeXml( boost::property_tree::ptree & tree ) const
{
  // TODO: implement me!
  assert( false );
}

template< typename CoeffType >
void BiquadCoefficientMatrix<CoeffType>::writeXml( std::basic_ostream<char> & stream ) const
{
  boost::property_tree::ptree tree;
  writeXml( tree );
  try
  {
    write_xml( stream, tree );
  }
  catch( std::exception const & ex )
  {
    throw std::invalid_argument( std::string( "Error while writing BiquadCoefficientMatrix to XML: " ) + ex.what() );
  }
}

template< typename CoeffType >
void BiquadCoefficientMatrix<CoeffType>::writeXml( std::string & str ) const
{
  std::stringstream stream;
  writeXml( stream );
  str = stream.str();
}

// Explicit instantiations
template class BiquadCoefficient<float>;
template class BiquadCoefficientList<float>;
template class BiquadCoefficientMatrix<float>;

template class BiquadCoefficient<double>;
template class BiquadCoefficientList<double>;
template class BiquadCoefficientMatrix<double>;

} // namespace rbbl
} // namespace visr


text:
#include "Graph.h"

#ifdef _WIN32
#pragma warning(disable:4503)
#pragma warning(push)
#pragma warning(disable:4996 4251 4275 4800)
#endif
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/filesystem.hpp>   // includes all needed Boost.Filesystem declarations
#include <boost/regex.hpp>
#include <boost/algorithm/string_regex.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/thread/recursive_mutex.hpp>
#include <boost/thread/lock_guard.hpp>

#ifdef _WIN32
#pragma warning(pop)
#endif

#include "ProcessManager.h"
#include "blocks/ParamValidator.h"
#include "SubBlock.h"

using namespace std;
using namespace charliesoft;
using namespace boost::filesystem;
using boost::recursive_mutex;
using boost::property_tree::ptree;
using boost::lexical_cast;
using boost::lock_guard;

namespace charliesoft
{
  bool GraphOfProcess::_pauseProcess = false;

  GraphOfProcess::GraphOfProcess()
  {
    _pauseProcess = false;
    _parent = NULL;
    _subBlock = NULL;
  };

  GraphOfProcess::~GraphOfProcess()
  {
    stop();
    waitUntilEnd(5000);//15s
    for (size_t i = 0; i < _vertices.size(); i++)
    {
      Block* b = _vertices[i];
      delete b;
    }
    _vertices.clear();
  }

  void GraphOfProcess::addNewProcess(Block* block){
    _vertices.push_back(block);
    block->setGraph(this);
    //if graph is running, start it:
    if (!_runningThread.empty())
    {
      block->markAsUnprocessed();
      _runningThread[block] = boost::thread(boost::ref(*block));
    }
  };

  void GraphOfProcess::deleteProcess(Block* process){
    extractProcess(process);//remove the process from the graph
    delete process;//free memory
  };

  void GraphOfProcess::extractProcess(Block* process){
    //remove every links:
    for (auto& outParam : process->_myOutputs)
      outParam.second = Not_A_Value();
    for (auto& inParam : process->_myInputs)
      inParam.second = Not_A_Value();

    for (auto it = _vertices.begin();
      it != _vertices.end(); it++)
    {
      if (*it == process)
      {
        _vertices.erase(it);

        for (auto& waitThread : _waitingForRendering)
        {
          if (waitThread.first != process)
            waitThread.second.erase(process);
        }

        auto& waitThreadDelete = _waitingForRendering.find(process);
        if (waitThreadDelete != _waitingForRendering.end())
        {
          waitThreadDelete->second.clear();
          _waitingForRendering.erase(waitThreadDelete);
        }

        auto& it = _runningThread.find(process);
        if (it != _runningThread.end())
        {
          it->second.interrupt();
          it->second.join();//wait for the end...
          _runningThread.erase(it);
        }

        return;
      }
    }
  };

  void GraphOfProcess::removeLink(const BlockLink& l)
  {
    *(l._to->getParam(l._toParam, true)) = Not_A_Value();
  }

  void GraphOfProcess::createLink(Block* src, std::string paramName, Block* dest, std::string paramNameDest)
  {
    src->linkParam(paramName, dest, paramNameDest);
  }

  std::vector<Block*>& GraphOfProcess::getVertices()
  {
    return _vertices;
  }

  void GraphOfProcess::updateAncestors(Block* process)
  {
    //wait for every direct linked ancestors:
    //Is there old parameters? -> if yes, we wait for update, else we process the block right now:
    for (auto it = process->_myInputs.begin(); it != process->_myInputs.end(); it++)
    {
      ParamValue* linkedBlock = it->second.get<ParamValue*>();
      if (linkedBlock!=NULL)
      {
        //we have an ancestor! We ask for an update:
        linkedBlock->update();
      }
    }
  }

  void GraphOfProcess::shouldWaitAncestors(Block* process)
  {
    boost::unique_lock<boost::mutex> lock(_mtx);
    //should we wait for a process? (depending on the block type)
    if (process->getTypeExec() == Block::asynchrone)
      return;//no need to wait
    //wait for every direct linked ancestors:
    //Is there old parameters? -> if yes, we wait for update, else we process the block right now:
    for (auto it = process->_myInputs.begin(); it != process->_myInputs.end(); it++)
    {
      if (it->second.isLinked())
      {
        ParamValue* other = it->second.get<ParamValue*>();
        while (!it->second.isNew())
        {//we have to wait for any update!
          //std::cout << "---  " << _STR(process->getName()) << " -> Wait " << _STR(it->second.getName()) << endl;
          process->setState(Block::waitingChild);
          other->getBlock()->waitProducers(lock);//wait for parameter update!
          //std::cout << "---  " << _STR(process->getName()) << " <- unblock " << _STR(it->second.getName()) << endl;
        }
      }
    }//ok, every ancestor have produced a value!
    if (NULL != _subBlock)
    {
      for (auto link : _subBlock->externBlocksInput)
      {
        try
        {
          if (link._to == process)
          {
            ParamValue* distVal = link._to->getParam(link._toParam, true);
            if (distVal->isDefaultValue() || !distVal->isNew())
            {
              //std::cout << "---  subBlock_" << _STR(link._to->getName()) << " -> Wait " << _STR(link._fromParam) << endl;
              process->setState(Block::waitingChild);
              _subBlock->waitUpdateParams(lock);//wait for parameter update!
              //std::cout << "---  subBlock_" << _STR(link._to->getName()) << " <- unblock " << _STR(link._fromParam) << endl;
            }
          }
        }
        catch (...)
        {
          //nothing to do...
        }
      }
    }
  }

  void GraphOfProcess::clearWaitingList(Block* process)
  {
    boost::unique_lock<boost::mutex> lock(_mtx);
    _waitingForRendering[process].clear();
    cout << "___clearWaitingList___" << endl;
  }

  void GraphOfProcess::shouldWaitConsumers(Block* process)
  {
    boost::unique_lock<boost::mutex> lock(_mtx);
    //should we wait for a process? (depending on the block type)
    if (process!=NULL && process->getTypeExec() == Block::synchrone)
    {
      //wait for the childs of this process. They have to be fully rendered before we rerun this block!
      for (auto it = process->_myOutputs.begin(); it != process->_myOutputs.end(); it++)
      {
        //wait for threads consumption
        std::set<ParamValue*>& listeners = it->second.getListeners();
        for (auto listener : listeners)
        {
          if (listener->isLinked() && listener->isNew())//this param is still not consumed...
          {
            _waitingForRendering[process].insert(listener->getBlock());
          }
        }
      }
    }
    if (process == NULL && _subBlock != NULL)
    {
      process = _subBlock;
      for (auto& threads : _runningThread)
      {
        if (threads.first->getState() != Block::waitingChild &&
          threads.first->getState() != Block::waitingConsumers &&
          threads.first->getState() != Block::stopped)
          _waitingForRendering[process].insert(threads.first);
      }
    }
    if (process != NULL && !_waitingForRendering[process].empty())
    {
      process->setState(Block::waitingConsumers);
      process->waitConsumers(lock);//wait for parameter update! Will be waked up when _waitingForRendering is empty!
    }

  }

  void GraphOfProcess::blockProduced(Block* process, bool fullyRendered)
  {
    boost::unique_lock<boost::mutex> lock(_mtx);/*
    if (fullyRendered)
      std::cout << " \t\t\t  " << _STR(process->getName()) << " Produced!" << endl;
    else
      std::cout << " \t\t\t  " << _STR(process->getName()) << " partially rendered!" << endl;*/
    //wake up linked output blocks
    process->notifyProduction();

    if (fullyRendered)
    {
      //remove this block for every waiting thread:
      for (auto& waitThread : _waitingForRendering)
      {
        if (waitThread.first != process)
        {
          waitThread.second.erase(process);
          if (waitThread.second.empty())
            waitThread.first->wakeUpFromConsumers();
        }
      }
    }
  }

  void GraphOfProcess::stop(bool delegateParent, bool waitEnd, bool stopAll)
  {
    if (_parent != NULL && delegateParent)
      return _parent->stop(delegateParent, waitEnd);
    if (stopAll)
    {
      for (auto& it = _runningThread.begin(); it != _runningThread.end(); it++)
        it->second.interrupt();
    }

    if (waitEnd)
      waitUntilEnd(15000);//15s
  }

  void GraphOfProcess::waitUntilEnd(size_t max_ms_time)
  {
    auto _time_start = boost::posix_time::microsec_clock::local_time();
    for (auto& it = _runningThread.begin(); it != _runningThread.end(); it++)
    {
      if (it->first->getState() != Block::stopped && it->second.joinable())
      {
        if (max_ms_time == 0)
          it->second.join();
        else
        {
          if (!it->second.timed_join(boost::posix_time::milliseconds(max_ms_time)))
            return;//quit because we can't stop the process

          boost::posix_time::ptime time_end(boost::posix_time::microsec_clock::local_time());
          boost::posix_time::time_duration duration(time_end - _time_start);
          if (duration.total_milliseconds() >= max_ms_time)
            return;
          max_ms_time -= static_cast<size_t>(duration.total_milliseconds());
        }
      }
    }
    _runningThread.clear();
  }

  bool GraphOfProcess::run(bool singleShot, bool delegateParent)
  {
    if (_parent != NULL && delegateParent)
      return _parent->run(singleShot);
    stop(delegateParent);//just in case...
    _pauseProcess = false;
    bool res = true;
    for (auto it = _vertices.begin();
      it != _vertices.end(); it++)
    {
      (*it)->markAsUnprocessed();
      (*it)->setExecuteOnlyOnce(singleShot);
      _runningThread[*it] = boost::thread(boost::ref(**it));
    }

    return res;
  }

  bool GraphOfProcess::switchPause(bool delegateParent)
  {
    if (_parent != NULL && delegateParent)
      return _parent->switchPause();
    _pauseProcess = !_pauseProcess;
    if (!_pauseProcess)
    {
      //wake up threads:
      for (auto it = _vertices.begin();
        it != _vertices.end(); it++)
        (*it)->wakeUpFromPause();
    }
    return _pauseProcess;
  }

  void GraphOfProcess::saveGraph(boost::property_tree::ptree& tree) const
  {
    for (auto it = _vertices.begin();
      it != _vertices.end(); it++)
      tree.add_child("GraphOfProcess.Block", (*it)->getXML());
  }

  bool GraphOfProcess::initChildDatas(Block* block, std::set<Block*>& listOfRenderedBlocks)
  {
    if (listOfRenderedBlocks.find(block) != listOfRenderedBlocks.end())
      return false;//nothing to do...

    if (block->getState() != Block::stopped && block->getState() != Block::paused)
      return true;//block is running, the value will be updated automatically!

    listOfRenderedBlocks.insert(block);
    //take one shot of block to init output:
    try
    {
      block->init();
      block->run(true);
      block->release();

      //now render every childs.
      set<Block*> renderBlocks;
      for (auto it = block->_myOutputs.begin(); it != block->_myOutputs.end(); it++)
      {
        //wake up the threads, if any!
        std::set<ParamValue*>& listeners = it->second.getListeners();
        for (auto listener : listeners)
        {
          if (listener->isLinked())
          {
            Block* consumer = listener->getBlock();
            if (consumer != NULL && consumer->isReadyToRun(true))
              renderBlocks.insert(consumer);
          }
        }

      }
      for (Block* consumer : renderBlocks)
      {
        if (listOfRenderedBlocks.find(consumer) == listOfRenderedBlocks.end())
          initChildDatas(consumer, listOfRenderedBlocks);
      }
    }
    catch (cv::Exception& e)
    {
      block->addErrorMsg(e.what());
      std::cout << "exception caught: " << e.what() << std::endl;
      return false;
    }
    return true;
  }

  void GraphOfProcess::fromGraph(boost::property_tree::ptree& tree,
    std::map<unsigned int, ParamValue*>& addressesMap)
  {
    boost::optional<ptree&> vertices = tree.get_child_optional("GraphOfProcess");

    vector < std::pair<ParamValue*, unsigned int> > toUpdate;
    vector<ConditionOfRendering*> condToUpdate;

    if (vertices)
    {
      for (ptree::iterator it = vertices->begin(); it != vertices->end(); it++)
      {
        if (it->first.compare("Block") == 0)
        {
          ptree *block = &it->second;
          string name = block->get("name", "Error");
          Block* tmp = ProcessManager::getInstance()->createAlgoInstance(name);
          if (tmp != NULL)
          {
            addNewProcess(tmp);
            tmp->initFromXML(block, toUpdate, addressesMap, condToUpdate);
          }
        }
      }
      //now make links:
      for (auto valToUpdate : toUpdate)
      {
        Block* fromBlock = valToUpdate.first != NULL ? valToUpdate.first->getBlock() : NULL;
        ParamValue* secondVal = addressesMap[valToUpdate.second];
        Block* toBlock = secondVal != NULL ? secondVal->getBlock() : NULL;
        if (fromBlock != NULL && toBlock != NULL)
        {
          try
          {
            createLink(toBlock, secondVal->getName(), fromBlock, valToUpdate.first->getName());
          }
          catch (ErrorValidator& e)
          {//algo doesn't accept this value!
            //QMessageBox::warning(this, _QT("ERROR_GENERIC_TITLE"), e.errorMsg.c_str());
            std::cout << e.errorMsg << std::endl;
          }
        }
      }
      //and set correct values of conditions:
      for (auto cond : condToUpdate)
      {
        if (cond->getCategory_left() == 1)//output of block:
        {
          unsigned int addr = static_cast<unsigned int>(cond->getOpt__valueleft().get<double>() + 0.5);
          cond->setValue(true, addressesMap[addr]);
        }
        if (cond->getCategory_right() == 1)//output of block:
        {
          unsigned int addr = static_cast<unsigned int>(cond->getOpt__valueright().get<double>() + 0.5);
          cond->setValue(false, addressesMap[addr]);
        }
      }

      //first look for edges who are ready to run:
      set<Block*> renderedBlocks;
      for (auto it = _vertices.begin();
        it != _vertices.end(); it++)
      {
        if ((*it)->isReadyToRun(true))
          initChildDatas(*it, renderedBlocks);//and init him and output childs
      }
    }
  }

}

max_stars_repo_name: Petititi/imGraph

max_issues_repo_name: Petititi/imGraph

max_forks_repo_name: Petititi/imGraph


text:
// Copyright 2020 The Hds Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "node_client.h"
#include <mutex>
#include "pow/external_pow.h"
#include "utility/logger.h"
#include <boost/filesystem.hpp>

namespace
{
    constexpr int kVerificationThreadsMaxAvailable = -1;

    boost::filesystem::path pathFromStdString(const std::string& path)
    {
#ifdef WIN32
        boost::filesystem::path boostPath{ hds::Utf8toUtf16(path.c_str()) };
#else
        boost::filesystem::path boostPath{ path };
#endif
        return boostPath;
    }

    void removeNodeDataIfNeeded(const std::string& nodePathStr)
    {
        try
        {
            auto nodePath = pathFromStdString(nodePathStr);
            auto appDataPath = nodePath.parent_path();

            if (!boost::filesystem::exists(appDataPath))
            {
                return;
            }
            try
            {
                hds::NodeDB nodeDB;
                nodeDB.Open(nodePathStr.c_str());
                return;
            }
            catch (const hds::NodeDBUpgradeException&)
            {
            }

            boost::filesystem::remove(nodePath);

            std::vector<boost::filesystem::path> macroBlockFiles;
            for (boost::filesystem::directory_iterator endDirIt, it{ appDataPath }; it != endDirIt; ++it)
            {
                if (it->path().filename().wstring().find(L"tempmb") == 0)
                {
                    macroBlockFiles.push_back(it->path());
                }
            }

            for (auto& path : macroBlockFiles)
            {
                boost::filesystem::remove(path);
            }
        }
        catch (std::exception & e)
        {
            LOG_ERROR() << e.what();
        }
    }
}

namespace hds
{
NodeClient::NodeClient(INodeClientObserver* observer)
    : m_observer(observer)
    , m_shouldStartNode(false)
    , m_shouldTerminateModel(false)
    , m_isRunning(false)
{
}

NodeClient::~NodeClient()
{
    try
    {
        m_shouldTerminateModel = true;
        m_waiting.notify_all();
        {
            auto r = m_reactor.lock();
            if (r)
            {
                r->stop();
                if (m_thread)
                {
                    // TODO: check this
                    m_thread->join();
                }
            }
        }
    }
    catch (const std::exception& e)
    {
        LOG_UNHANDLED_EXCEPTION() << "what = " << e.what();
    }
    catch (...) {
        LOG_UNHANDLED_EXCEPTION();
    }
}

void NodeClient::setKdf(hds::Key::IKdf::Ptr kdf)
{
    m_pKdf = kdf;
}

void NodeClient::setOwnerKey(hds::Key::IPKdf::Ptr key)
{
    m_ownerKey = key;
}

void NodeClient::startNode()
{
    m_shouldStartNode = true;
    m_waiting.notify_all();
}

void NodeClient::stopNode()
{
    m_shouldStartNode = false;
    auto reactor = m_reactor.lock();
    if (reactor)
    {
        reactor->stop();
    }
}

void NodeClient::start()
{
    m_thread = std::make_shared<std::thread>([this]()
    {
        try
        {
            removeNodeDataIfNeeded(m_observer->getLocalNodeStorage());

            auto reactor = io::Reactor::create();
            m_reactor = reactor;// store weak ref
            io::Reactor::Scope scope(*reactor);

            std::mutex localMutex;

            while (!m_shouldTerminateModel)
            {
                if (!m_shouldStartNode)
                {
                    std::unique_lock<std::mutex> lock(localMutex);

                    while (!m_shouldStartNode && !m_shouldTerminateModel)
                    {
                        m_waiting.wait(lock);
                    }
                }

                if (!m_shouldTerminateModel)
                {
                    bool bErr = true;
                    try
                    {
                        m_shouldStartNode = false;
                        runLocalNode();
                        bErr = false;
                    }
                    catch (const io::Exception& ex)
                    {
                        LOG_ERROR() << ex.what();
                        m_observer->onFailedToStartNode(ex.errorCode);
                        bErr = false;
                    }
                    catch (const std::runtime_error& ex)
                    {
                        LOG_ERROR() << ex.what();
                    }
                    catch (const CorruptionException& ex)
                    {
                        LOG_ERROR() << "Corruption: " << ex.m_sErr;
                    }

                    if (bErr)
                        m_observer->onSyncError(Node::IObserver::Error::Unknown);
                }
            }
        }
        catch (const std::exception& e)
        {
            LOG_UNHANDLED_EXCEPTION() << "what = " << e.what();
        }
        catch (...) {
            LOG_UNHANDLED_EXCEPTION();
        }

        m_observer->onNodeThreadFinished();
    });
}

bool NodeClient::isNodeRunning() const
{
    return m_isRunning;
}

void NodeClient::runLocalNode()
{
    class ScopedNotifier final {
    public:
        explicit ScopedNotifier(INodeClientObserver& observer)
            : _observer(observer)
            , _nodeCreated(false)
        {}

        void notifyNodeCreated()
        {
            assert(!_nodeCreated);
            _nodeCreated = true;
            _observer.onNodeCreated();
        }

        ~ScopedNotifier()
        {
            if (_nodeCreated)
            {
                _observer.onNodeDestroyed();
            }
        }
    private:
        INodeClientObserver& _observer;
        bool _nodeCreated = false;
    } notifier(*m_observer);

    // Scope, just for clarity. Notifier created above
    // should be destroyed the last
    {
        Node node;
        node.m_Cfg.m_Listen.port(m_observer->getLocalNodePort());
        node.m_Cfg.m_Listen.ip(INADDR_ANY);
        node.m_Cfg.m_sPathLocal = m_observer->getLocalNodeStorage();
        node.m_Cfg.m_MiningThreads = 0;
        node.m_Cfg.m_VerificationThreads = kVerificationThreadsMaxAvailable;

        if (m_pKdf)
        {
            node.m_Keys.SetSingleKey(m_pKdf);
        }
        else if(m_ownerKey)
        {
            node.m_Keys.m_pOwner = m_ownerKey;
        }

		node.m_Cfg.m_Horizon.SetStdFastSync();

        auto peers = m_observer->getLocalNodePeers();

        for (const auto& peer : peers)
        {
            io::Address peer_addr;
            if (peer_addr.resolve(peer.c_str()))
            {
                node.m_Cfg.m_Connect.emplace_back(peer_addr);
            }
            else
             {
                LOG_ERROR() << "Unable to resolve node address: " << peer;
            }
        }

        LOG_INFO() << "starting a node on " << node.m_Cfg.m_Listen.port() << " port...";

        class MyObserver final: public Node::IObserver
        {
        public:
            MyObserver(Node& node, NodeClient& model)
                : m_node(node)
                , m_model(model)
            {
                assert(m_model.m_observer);
            }

            ~MyObserver()
            {
                assert(m_model.m_observer);
                if (m_reportedStarted) m_model.m_observer->onStoppedNode();
            }

            void OnSyncProgress() override
            {
                Node::SyncStatus s = m_node.m_SyncStatus;

				if (MaxHeight == m_Done0)
					m_Done0 = s.m_Done;
				s.ToRelative(m_Done0);

                if (!m_reportedStarted && (s.m_Done == s.m_Total))
                {
                    m_reportedStarted = true;
                    m_model.m_observer->onStartedNode();
                }

                // make sure no overflow during conversion from SyncStatus to int,int.
                const auto threshold = static_cast<unsigned int>(std::numeric_limits<int>::max());
                while (s.m_Total > threshold)
                {
                    s.m_Total >>= 1;
                    s.m_Done >>= 1;
                }

                m_model.m_observer->onSyncProgressUpdated(static_cast<int>(s.m_Done), static_cast<int>(s.m_Total));
            }

            void OnSyncError(Node::IObserver::Error error) override
            {
                m_model.m_observer->onSyncError(error);
            }

            void InitializeUtxosProgress(uint64_t done, uint64_t total) override
            {
                m_model.m_observer->onInitProgressUpdated(done, total);
            }

        private:
            Node& m_node;
            NodeClient& m_model;
			Height m_Done0 = MaxHeight;
            bool m_reportedStarted = false;
        } obs(node, *this);

        node.m_Cfg.m_Observer = &obs;
        node.Initialize();
        notifier.notifyNodeCreated();

        if (node.get_AcessiblePeerCount() == 0)
        {
            throw std::runtime_error("Resolved peer list is empty");
        }

        m_isRunning = true;
        io::Reactor::get_Current().run();
        m_isRunning = false;
    }
}
}

max_stars_repo_name: hadescoincom/hds-core

max_issues_repo_name: hadescoincom/hds-core

max_forks_repo_name: hadescoincom/hds-core


text:
#include <iostream>
#include <string>
#include <boost/asio.hpp>
#include <boost/array.hpp>
#include "connection.h"

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

connection::connection( char* network, char * port) : resolver(io), query(network, port), iterator(resolver.resolve(query)), socket(io)
{

}

void connection::connect()
{

	boost::asio::connect(socket, iterator);

}

void connection::disconnect()
{

}

std::size_t connection::send(std::string &msg)
{
	msg.append("\r\n");

	return boost::asio::write(socket, boost::asio::buffer(msg));

}

std::size_t connection::send(std::string &&msg)
{
	msg.append("\r\n");

	return boost::asio::write(socket, boost::asio::buffer(msg));

}
std::size_t connection::receive(std::array<char, 512> &buf, boost::system::error_code &error)
{

	return socket.read_some(boost::asio::buffer(buf, 512), error);

}

max_stars_repo_name: ajaniMember/IrcBot

max_issues_repo_name: ajaniMember/IrcBot

max_forks_repo_name: ajaniMember/IrcBot


text:
//          Copyright Oliver Kowalke 2013.
// Distributed under the Boost Software License, Version 1.0.
//    (See accompanying file LICENSE_1_0.txt or copy at
//          http://www.boost.org/LICENSE_1_0.txt)

#ifndef BOOST_FIBERS_POLICY_H
#define BOOST_FIBERS_POLICY_H

#include <type_traits>

#include <boost/config.hpp>

#include <boost/fiber/detail/config.hpp>

#ifdef BOOST_HAS_ABI_HEADERS
#  include BOOST_ABI_PREFIX
#endif

namespace boost {
namespace fibers {

enum class launch {
    dispatch,
    post
};

namespace detail {

template< typename Fn >
struct is_launch_policy : public std::false_type {
};

template<>
struct is_launch_policy< boost::fibers::launch > : public std::true_type {
};

}

}}

#ifdef BOOST_HAS_ABI_HEADERS
#  include BOOST_ABI_SUFFIX
#endif

#endif // BOOST_FIBERS_POLICY_H


text:
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE "udho Unit Test (udho::client)"

#include <boost/test/unit_test.hpp>
#include <udho/server.h>
#include <udho/contexts.h>
#include <udho/client.h>
#include <iostream>

typedef udho::servers::quiet::stateless server_type;
typedef udho::contexts::stateless context_type;

BOOST_AUTO_TEST_SUITE(client)

BOOST_AUTO_TEST_CASE(https){
    boost::asio::io_service io;
    context_type::request_type req;
    server_type::attachment_type attachment(io);
    context_type ctx(attachment.aux(), req, attachment);

    ctx.client().get("http://google.com")
        .done([ctx](boost::beast::http::status status, const std::string& body) mutable {
            BOOST_CHECK(status == boost::beast::http::status::moved_permanently);
        }).error([ctx](const boost::beast::error_code& ec) mutable {
            BOOST_CHECK_MESSAGE(false, "test request to http://google.com failed");
        })
        .option(udho::client_options::follow_redirect, false)
        .option(udho::client_options::verify_certificate, true);

    ctx.client().get("http://google.com")
        .done([ctx](boost::beast::http::status status, const std::string& body) mutable {
            BOOST_CHECK(status == boost::beast::http::status::ok);
        }).error([ctx](const boost::beast::error_code& ec) mutable {
            BOOST_CHECK_MESSAGE(false, "test request to http://google.com failed");
        })
        .option(udho::client_options::follow_redirect, true)
        .option(udho::client_options::verify_certificate, true);

    ctx.client().get("http://tls-v1-2.badssl.com")
        .done([ctx](boost::beast::http::status status, const std::string& body) mutable {
            BOOST_CHECK(status == boost::beast::http::status::ok);
        }).error([ctx](const boost::beast::error_code& ec) mutable {
            BOOST_CHECK_MESSAGE(false, "test request to http://google.com failed");
        })
        .option(udho::client_options::follow_redirect, true)
        .option(udho::client_options::verify_certificate, true);

    ctx.client().get("http://expired.badssl.com")
        .done([ctx](boost::beast::http::status status, const std::string& body) mutable {
            BOOST_CHECK_MESSAGE(false, "SSL verification succeeded with http://expired.badssl.com which is unexpected");
        }).error([ctx](const boost::beast::error_code& ec) mutable {
            BOOST_CHECK_MESSAGE(ec.value() == 337047686, "expecting SSL varification failure, but got somethign else");
        })
        .option(udho::client_options::follow_redirect, true)
        .option(udho::client_options::verify_certificate, true);

    ctx.client().get("http://expired.badssl.com")
        .done([ctx](boost::beast::http::status status, const std::string& body) mutable {
            BOOST_CHECK(status == boost::beast::http::status::ok);
        }).error([ctx](const boost::beast::error_code& ec) mutable {
            BOOST_CHECK_MESSAGE(false, "unexpected error whiling ignoring ssl verification");
        })
        .option(udho::client_options::follow_redirect, true)
        .option(udho::client_options::verify_certificate, false);

    udho::url url1 = udho::url::build("https://postman-echo.com/get", {
        {"foo", "bar"},
        {"key", "value"}
    });

    BOOST_CHECK_MESSAGE(url1.stringify() == "https://postman-echo.com:443/get?foo=bar&key=value", "unexpected " << url1.stringify());

    udho::url url2 = udho::url::build("https://postman-echo.com/get?id=42", {
        {"foo", "bar"},
        {"key", "value"}
    });

    BOOST_CHECK_MESSAGE(url2.stringify() == "https://postman-echo.com:443/get?id=42&foo=bar&key=value", "unexpected " << url2.stringify());

    io.run();
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: neel/udho

max_issues_repo_name: neel/udho

max_forks_repo_name: neel/udho