text:
#include <boost/foreach.hpp>
#include <sstream>
#include "Hypothesis.h"
#include "Manager.h"
#include "ActiveChart.h"
#include "TargetPhraseImpl.h"
#include "Sentence.h"
#include "../System.h"
#include "../Scores.h"
#include "../InputPathBase.h"
#include "../FF/StatefulFeatureFunction.h"

using namespace std;

namespace Moses2
{
namespace SCFG
{
Hypothesis *Hypothesis::Create(MemPool &pool, Manager &mgr)
{
  //  ++g_numHypos;
  Hypothesis *ret;
  //ret = new (pool.Allocate<Hypothesis>()) Hypothesis(pool, mgr.system);

  Recycler<HypothesisBase*> &recycler = mgr.GetHypoRecycle();
  ret = static_cast<Hypothesis*>(recycler.Get());
  if (ret) {
    // got new hypo from recycler. Do nothing
  } else {
    ret = new (pool.Allocate<Hypothesis>()) Hypothesis(pool, mgr.system);
    //cerr << "Hypothesis=" << sizeof(Hypothesis) << " " << ret << endl;
    recycler.Keep(ret);
  }
  return ret;
}

Hypothesis::Hypothesis(MemPool &pool,
                       const System &system)
  :HypothesisBase(pool, system)
  ,m_prevHypos(pool)
{

}

void Hypothesis::Init(SCFG::Manager &mgr,
                      const SCFG::InputPath &path,
                      const SCFG::SymbolBind &symbolBind,
                      const SCFG::TargetPhraseImpl &tp,
                      const Vector<size_t> &prevHyposIndices)
{
  m_mgr = &mgr;
  m_targetPhrase = &tp;
  m_path = &path;
  m_symbolBind = &symbolBind;

  m_scores->Reset(mgr.system);
  m_scores->PlusEquals(mgr.system, GetTargetPhrase().GetScores());

  //cerr << "tp=" << tp << endl;
  //cerr << "symbolBind=" << symbolBind << endl;
  //cerr << endl;
  m_prevHypos.resize(symbolBind.numNT);

  size_t currInd = 0;
  for (size_t i = 0; i < symbolBind.coll.size(); ++i) {
    const SymbolBindElement &ele = symbolBind.coll[i];
    //cerr << "ele=" << ele.word->isNonTerminal << " " << ele.hypos << endl;

    if (ele.hypos) {
      const Hypotheses &sortedHypos = *ele.hypos;

      size_t prevHyposInd = prevHyposIndices[currInd];
      assert(prevHyposInd < sortedHypos.size());

      const Hypothesis *prevHypo = static_cast<const SCFG::Hypothesis*>(sortedHypos[prevHyposInd]);
      m_prevHypos[currInd] = prevHypo;

      m_scores->PlusEquals(mgr.system, prevHypo->GetScores());

      ++currInd;
    }
  }
}

SCORE Hypothesis::GetFutureScore() const
{
  return GetScores().GetTotalScore();
}

void Hypothesis::EvaluateWhenApplied()
{
  const std::vector<const StatefulFeatureFunction*> &sfffs =
    GetManager().system.featureFunctions.GetStatefulFeatureFunctions();
  BOOST_FOREACH(const StatefulFeatureFunction *sfff, sfffs) {
    EvaluateWhenApplied(*sfff);
  }
//cerr << *this << endl;

}

void Hypothesis::EvaluateWhenApplied(const StatefulFeatureFunction &sfff)
{
  const SCFG::Manager &mgr = static_cast<const SCFG::Manager&>(GetManager());
  size_t statefulInd = sfff.GetStatefulInd();
  FFState *thisState = m_ffStates[statefulInd];
  sfff.EvaluateWhenApplied(mgr, *this, statefulInd, GetScores(),
                           *thisState);

}

void Hypothesis::OutputToStream(std::ostream &strm) const
{
  const SCFG::TargetPhraseImpl &tp = GetTargetPhrase();
  //cerr << "tp=" << tp.Debug(m_mgr->system) << endl;

  for (size_t targetPos = 0; targetPos < tp.GetSize(); ++targetPos) {
    const SCFG::Word &word = tp[targetPos];
    //cerr << "word " << targetPos << "=" << word << endl;
    if (word.isNonTerminal) {
      //cerr << "is nt" << endl;
      // non-term. fill out with prev hypo
      size_t nonTermInd = tp.GetAlignNonTerm().GetNonTermIndexMap()[targetPos];
      const Hypothesis *prevHypo = m_prevHypos[nonTermInd];
      prevHypo->OutputToStream(strm);
    } else {
      word.OutputToStream(*m_mgr, targetPos, *this, strm);
      strm << " ";
    }

  }
}

std::string Hypothesis::Debug(const System &system) const
{
  stringstream out;
  out << this << flush;

  out << " RANGE:";
  out << m_path->range << " ";
  out << m_symbolBind->Debug(system) << " ";

  // score
  out << " SCORE:" << GetScores().Debug(GetManager().system) << flush;

  out << m_targetPhrase->Debug(GetManager().system);

  out << "PREV:";
  for (size_t i = 0; i < m_prevHypos.size(); ++i) {
    const Hypothesis *prevHypo = m_prevHypos[i];
    out << prevHypo << prevHypo->GetInputPath().range << "(" << prevHypo->GetFutureScore() << ") ";
  }
  out << endl;

  /*
  // recursive
  for (size_t i = 0; i < m_prevHypos.size(); ++i) {
    const Hypothesis *prevHypo = m_prevHypos[i];
    out << prevHypo->Debug(GetManager().system) << " ";
  }
  */

  return out.str();
}

void Hypothesis::OutputTransOpt(std::ostream &out) const
{
  out << GetInputPath().range << " "
      << "score=" << GetScores().GetTotalScore() << " "
      << GetTargetPhrase().Debug(m_mgr->system) << endl;

  BOOST_FOREACH(const Hypothesis *prevHypo, m_prevHypos) {
    prevHypo->OutputTransOpt(out);
  }
}

} // namespaces
}


text:
//
// Created by niko on 23.05.2021.
//

#include <redis_async/common.hpp>
#include <redis_async/error.hpp>

#include <boost/algorithm/string/case_conv.hpp>
#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/split.hpp>
#include <boost/lexical_cast.hpp>

#include <tuple>
#include <vector>

namespace redis_async {

    struct connect_string_parser {

        connect_string_parser() = default;

        connection_options operator()(std::string const &uri) {
            connection_options opts;
            std::string auth;
            std::string path;
            std::tie(auth, path) = split_uri(uri, opts);

            set_auth_opts(auth, opts);
            auto parameter_string = split_path(path, opts);
            parse_parameters(parameter_string, opts);

            return opts;
        }

        static auto split_uri(const std::string &uri, connection_options &opts)
            -> std::tuple<std::string, std::string>;
        static void set_auth_opts(const std::string &auth, connection_options &opts);
        static auto split_path(const std::string &path, connection_options &opts) -> std::string;
        static void parse_parameters(const std::string &parameter_string, connection_options &opts);
        static void set_option(const std::string &key, const std::string &val,
                               connection_options &opts);
        static std::chrono::milliseconds _parse_timeout_option(const std::string &str);
        static bool parse_bool_option(const std::string &str);
    };

    auto connect_string_parser::split_uri(const std::string &uri, connection_options &opts)
        -> std::tuple<std::string, std::string> {
        auto pos = uri.find('=');
        if (pos == std::string::npos)
            throw error::connection_error("invalid connection string");

        opts.alias = uri.substr(0, pos);
        if (opts.alias.empty())
            throw error::connection_error("invalid connection string");

        auto start = pos + 1;

        pos = uri.find("://", start);
        if (pos == std::string::npos)
            throw error::connection_error("invalid connection string");

        opts.schema = uri.substr(start, pos - start);
        if (opts.schema.empty())
            throw error::connection_error("invalid connection string");

        start = pos + 3;
        pos = uri.find('@', start);
        if (pos == std::string::npos) {
            // No auth info.
            return std::make_tuple(std::string{}, uri.substr(start));
        }

        auto auth = uri.substr(start, pos - start);

        return std::make_tuple(auth, uri.substr(pos + 1));
    }

    void connect_string_parser::set_auth_opts(const std::string &auth, connection_options &opts) {
        if (auth.empty()) {
            // No auth info.
            return;
        }
        opts.password = auth;
    }
    auto connect_string_parser::split_path(const std::string &path, connection_options &opts)
        -> std::string {
        auto parameter_pos = path.rfind('?');
        std::string parameter_string;
        if (parameter_pos != std::string::npos) {
            parameter_string = path.substr(parameter_pos + 1);
        }

        auto pos = path.rfind('/');
        if (pos != std::string::npos) {
            // Might specified a db number.
            try {
                auto db = path.substr(pos + 1);
                std::stoi(db);
                opts.database = std::move(db);
                opts.uri = path.substr(0, pos);
            } catch (const std::exception &) {
                // Not a db number, and it might be a path to unix domain socket.
                opts.uri = path.substr(0, parameter_pos);
            }
        } else {
            opts.uri = path.substr(0, parameter_pos);
        }

        if (opts.uri.empty())
            throw error::connection_error("invalid connection string");

        // No db number specified, and use default one, i.e. 0.
        return parameter_string;
    }
    void connect_string_parser::parse_parameters(const std::string &parameter_string,
                                                 connection_options &opts) {
        if (parameter_string.empty())
            return;
        using Strings = std::vector<std::string>;

        Strings parameters;
        boost::split(parameters, parameter_string, boost::is_any_of("&"));

        for (const auto &parameter : parameters) {
            Strings kv_pair;
            boost::split(kv_pair, parameter, boost::is_any_of("="));
            if (kv_pair.size() != 2) {
                throw error::connection_error("invalid option: not a key-value pair: " + parameter);
            }

            const auto &key = kv_pair[0];
            const auto &val = kv_pair[1];
            set_option(key, val, opts);
        }
    }
    void connect_string_parser::set_option(const std::string &key, const std::string &val,
                                           connection_options &opts) {
        if (key == "keep_alive") {
            opts.keep_alive = parse_bool_option(val);
        } else if (key == "connect_timeout") {
            opts.connect_timeout = _parse_timeout_option(val);
        } else if (key == "socket_timeout") {
            opts.socket_timeout = _parse_timeout_option(val);
        } else {
            throw error::connection_error("unknown uri parameter " + key);
        }
    }
    std::chrono::milliseconds connect_string_parser::_parse_timeout_option(const std::string &str) {
        std::size_t timeout = 0;
        std::string unit;
        try {
            std::size_t pos = 0;
            timeout = std::stoul(str, &pos);
            unit = str.substr(pos);
        } catch (const std::exception &e) {
            throw error::connection_error("invalid uri parameter of timeout type: " + str);
        }
        if (unit == "ms") {
            return std::chrono::milliseconds(timeout);
        } else if (unit == "s") {
            return std::chrono::seconds(timeout);
        } else if (unit == "m") {
            return std::chrono::minutes(timeout);
        } else {
            throw error::connection_error("unknown timeout unit: " + unit);
        }
    }
    bool connect_string_parser::parse_bool_option(const std::string &str) {
        auto value = boost::to_lower_copy(str);
        if (value == "true") {
            return true;
        } else if (value == "false") {
            return false;
        }
        throw error::connection_error("invalid uri parameter of bool type: " + str);
    }

    connection_options connection_options::parse(const std::string &uri) {
        return connect_string_parser()(uri);
    }
} // namespace redis_async

redis_async::rdalias operator""_rd(const char *v, size_t) {
    return redis_async::rdalias{std::string{v}};
}
redis_async::connection_options operator""_redis(const char *uri, size_t) {
    return redis_async::connection_options::parse(uri);
}

ext: cpp


text:
#include "logreg.hpp"
#include <cmath>
#include <random>
#include <fstream>
#include <Eigen/Dense>
#include <stdio.h>
#include <iostream>

using namespace std;
using namespace Eigen;

mt19937 rng;

lrsgd::lrsgd()
{
	//set training parameters
	num_iter = 20;
	lambda = (float) 1e-4;
	theta = VectorXf::Random(2, 1);
	cost = 0.0;
	grad = VectorXf::Zero(2, 1);

	//generate training data
	generate_data(X, y);

	//learning rate schedule
	tau0 = 10;
	kappa = 1;  //(0.5, 1]
	eta = VectorXf::Zero(num_iter,1);
	for (int i = 0; i < num_iter; i++)
	{
		eta[i] = (float) pow((tau0 + i), (-kappa));
	}
}

VectorXf lrsgd::sigmoid(VectorXf& a)
{
	return (1 + (-1*a.array()).exp()).inverse();  // 1/(1 + exp(-a))
}

void lrsgd::lr_objective(float& cost, VectorXf& grad, VectorXf& theta)
{
	float n = (float) y.size();
	VectorXi y01 = (y.array() + 1) / 2;  //y \in {0, 1}
	VectorXf h = X * theta;
	VectorXf mu = sigmoid(h);

	mu = mu.cwiseMax((float) 1e-7);       //bound away from zero: max(mu, eps)
	mu = mu.cwiseMin((float)(1 - 1e-7));  //bound away from one:  min(mu, 1-eps)

	ArrayXf t1 = y01.array().cast<float>() * mu.array().log();
	ArrayXf t2 = (1 - y01.array().cast<float>()) * ((1 - mu.array()).log());
	cost = -(t1 + t2).sum() / n;  //NLL
	cost += lambda * theta.norm();  //regularizer
	//cout << "cost: " << cost << endl;

	grad = X.transpose() * (mu - y01.cast<float>()) + 2 * lambda * theta;  //gradient of LR objective
	//cout << "grad norm: " << grad.norm() << endl;
}

void lrsgd::fit()
{
	VectorXf obj_hist = VectorXf::Zero(num_iter, 1);
	VectorXf theta_norm_hist = VectorXf::Zero(num_iter, 1);

	for (int i = 0; i < num_iter; ++i)
	{
		lr_objective(cost, grad, theta);
		theta = theta - eta[i] * grad;

		cout << "grad: " << endl << grad << endl;
		cout << "theta: " << endl << theta << endl;

		obj_hist[i] = cost;
		theta_norm_hist[i] = theta.norm();
		printf("iteration: %d, cost: %.4f, eta: %.4f, theta_norm: %.4f, grad_norm: %.4f\n", i, obj_hist[i], eta[i], theta.norm(), grad.norm());
	}
}

void lrsgd::generate_data(MatrixXf& X, VectorXi& y)
{
	int n = 32, d = 2;
	X = MatrixXf::Zero(n, 2);
	y = VectorXi::Zero(n, 1);

	Vector2f mu1(1, 1), mu2(-1, -1);
	Vector2f pik(0.4, 0.6), cpik(0.4, 1.0); //cumsum(pik)

	cout << "mu1: " << endl << mu1 << endl;
	cout << "mu2: " << endl << mu2 << endl;

	uniform_real_distribution<float> dis01(0, 1);
	Vector2f xn(0, 0);

	for (int i = 0; i < n; i++)
	{
		float z01 = dis01(rng);
		//cout << "z01: " << z01 << endl;

		if (z01 < cpik[0])
		{
			X.row(i) = xn.setRandom() + mu1;
			y(i) = 1;
		}
		else
		{
			X.row(i) = xn.setRandom() + mu2;
			y(i) = -1;
		}
	}

	cout << "y: " << endl << y << endl;
	cout << "X: " << endl << X << endl;

	ofstream fout("./input.txt");
	if (fout.is_open())
	{
		fout << X.size() << endl;
		fout << X << endl;
		fout << y.size() << endl;
		fout << y << endl;
	}
	else
		cout << "Unable to open fout.\n";
}

int main()
{
    cout << "Binary Logistic Regression\n";
	lrsgd LR = lrsgd();
	LR.fit();
	cout << "Learned weights: " << endl << LR.theta << endl;

	cout << "Predicting on training data: " << endl;
	VectorXf mu = LR.X * LR.theta;
	VectorXf h = LR.sigmoid(mu);
	VectorXf y_pred = 2.0 * (h.array() >= 0.5).cast<float>() - 1.0;
	float y_err = (y_pred - LR.y.cast<float>()).sum() / (float) y_pred.size();
        cout << "LR classification error: " << y_err << endl;

	return 0;
}

max_stars_repo_name: vishalbelsare/cpp


text:
// Copyright (c) 2018, SiZ, The Monero Project
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are
// permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
//    conditions and the following disclaimer.
//
// 2. 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.
//
// 3. Neither the name of the copyright holder 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 HOLDER 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.
//
// Parts of this file are originally copyright (c) 2012-2013 The Cryptonote developers

#include <boost/archive/binary_oarchive.hpp>
#include <boost/archive/binary_iarchive.hpp>

#include <boost/utility/value_init.hpp>
#include "include_base_utils.h"
using namespace epee;

#include "wallet2.h"
#include "cryptonote_core/cryptonote_format_utils.h"
#include "rpc/core_rpc_server_commands_defs.h"
#include "misc_language.h"
#include "cryptonote_core/cryptonote_basic_impl.h"
#include "common/boost_serialization_helper.h"
#include "profile_tools.h"
#include "crypto/crypto.h"
#include "serialization/binary_utils.h"
#include "cryptonote_protocol/blobdatatype.h"
#include "crypto/electrum-words.h"

extern "C"
{
#include "crypto/keccak.h"
#include "crypto/crypto-ops.h"
}
using namespace cryptonote;

namespace
{
void do_prepare_file_names(const std::string& file_path, std::string& keys_file, std::string& wallet_file)
{
  keys_file = file_path;
  wallet_file = file_path;
  boost::system::error_code e;
  if(string_tools::get_extension(keys_file) == "keys")
  {//provided keys file name
    wallet_file = string_tools::cut_off_extension(wallet_file);
  }else
  {//provided wallet file name
    keys_file += ".keys";
  }
}

} //namespace

namespace tools
{
// for now, limit to 30 attempts.  TODO: discuss a good number to limit to.
const size_t MAX_SPLIT_ATTEMPTS = 30;

//----------------------------------------------------------------------------------------------------
void wallet2::init(const std::string& daemon_address, uint64_t upper_transaction_size_limit)
{
  m_upper_transaction_size_limit = upper_transaction_size_limit;
  m_daemon_address = daemon_address;
}
//----------------------------------------------------------------------------------------------------
bool wallet2::get_seed(std::string& electrum_words)
{
  crypto::ElectrumWords::bytes_to_words(get_account().get_keys().m_spend_secret_key, electrum_words);

  crypto::secret_key second;
  keccak((uint8_t *)&get_account().get_keys().m_spend_secret_key, sizeof(crypto::secret_key), (uint8_t *)&second, sizeof(crypto::secret_key));

  sc_reduce32((uint8_t *)&second);

  return memcmp(second.data,get_account().get_keys().m_view_secret_key.data, sizeof(crypto::secret_key)) == 0;
}
//----------------------------------------------------------------------------------------------------
void wallet2::process_new_transaction(const cryptonote::transaction& tx, uint64_t height)
{
  process_unconfirmed(tx);
  std::vector<size_t> outs;
  uint64_t tx_money_got_in_outs = 0;

  std::vector<tx_extra_field> tx_extra_fields;
  if(!parse_tx_extra(tx.extra, tx_extra_fields))
  {
    // Extra may only be partially parsed, it's OK if tx_extra_fields contains public key
    LOG_PRINT_L0("Transaction extra has unsupported format: " << get_transaction_hash(tx));
  }

  tx_extra_pub_key pub_key_field;
  if(!find_tx_extra_field_by_type(tx_extra_fields, pub_key_field))
  {
    LOG_PRINT_L0("Public key wasn't found in the transaction extra. Skipping transaction " << get_transaction_hash(tx));
    if(0 != m_callback)
      m_callback->on_skip_transaction(height, tx);
    return;
  }

  crypto::public_key tx_pub_key = pub_key_field.pub_key;
  bool r = lookup_acc_outs(m_account.get_keys(), tx, tx_pub_key, outs, tx_money_got_in_outs);
  THROW_WALLET_EXCEPTION_IF(!r, error::acc_outs_lookup_error, tx, tx_pub_key, m_account.get_keys());

  if(!outs.empty() && tx_money_got_in_outs)
  {
    //good news - got money! take care about it
    //usually we have only one transfer for user in transaction
    cryptonote::COMMAND_RPC_GET_TX_GLOBAL_OUTPUTS_INDEXES::request req = AUTO_VAL_INIT(req);
    cryptonote::COMMAND_RPC_GET_TX_GLOBAL_OUTPUTS_INDEXES::response res = AUTO_VAL_INIT(res);
    req.txid = get_transaction_hash(tx);
    bool r = net_utils::invoke_http_bin_remote_command2(m_daemon_address + "/get_o_indexes.bin", req, res, m_http_client, WALLET_RCP_CONNECTION_TIMEOUT);
    THROW_WALLET_EXCEPTION_IF(!r, error::no_connection_to_daemon, "get_o_indexes.bin");
    THROW_WALLET_EXCEPTION_IF(res.status == CORE_RPC_STATUS_BUSY, error::daemon_busy, "get_o_indexes.bin");
    THROW_WALLET_EXCEPTION_IF(res.status != CORE_RPC_STATUS_OK, error::get_out_indices_error, res.status);
    THROW_WALLET_EXCEPTION_IF(res.o_indexes.size() != tx.vout.size(), error::wallet_internal_error,
      "transactions outputs size=" + std::to_string(tx.vout.size()) +
      " not match with COMMAND_RPC_GET_TX_GLOBAL_OUTPUTS_INDEXES response size=" + std::to_string(res.o_indexes.size()));

    BOOST_FOREACH(size_t o, outs)
    {
      THROW_WALLET_EXCEPTION_IF(tx.vout.size() <= o, error::wallet_internal_error, "wrong out in transaction: internal index=" +
        std::to_string(o) + ", total_outs=" + std::to_string(tx.vout.size()));

      m_transfers.push_back(boost::value_initialized<transfer_details>());
      transfer_details& td = m_transfers.back();
      td.m_block_height = height;
      td.m_internal_output_index = o;
      td.m_global_output_index = res.o_indexes[o];
      td.m_tx = tx;
      td.m_spent = false;
      cryptonote::keypair in_ephemeral;
      cryptonote::generate_key_image_helper(m_account.get_keys(), tx_pub_key, o, in_ephemeral, td.m_key_image);
      THROW_WALLET_EXCEPTION_IF(in_ephemeral.pub != boost::get<cryptonote::txout_to_key>(tx.vout[o].target).key,
        error::wallet_internal_error, "key_image generated ephemeral public key not matched with output_key");

      m_key_images[td.m_key_image] = m_transfers.size()-1;
      LOG_PRINT_L0("Received money: " << print_money(td.amount()) << ", with tx: " << get_transaction_hash(tx));
      if (0 != m_callback)
        m_callback->on_money_received(height, td.m_tx, td.m_internal_output_index);
    }
  }

  uint64_t tx_money_spent_in_ins = 0;
  // check all outputs for spending (compare key images)
  BOOST_FOREACH(auto& in, tx.vin)
  {
    if(in.type() != typeid(cryptonote::txin_to_key))
      continue;
    auto it = m_key_images.find(boost::get<cryptonote::txin_to_key>(in).k_image);
    if(it != m_key_images.end())
    {
      LOG_PRINT_L0("Spent money: " << print_money(boost::get<cryptonote::txin_to_key>(in).amount) << ", with tx: " << get_transaction_hash(tx));
      tx_money_spent_in_ins += boost::get<cryptonote::txin_to_key>(in).amount;
      transfer_details& td = m_transfers[it->second];
      td.m_spent = true;
      if (0 != m_callback)
        m_callback->on_money_spent(height, td.m_tx, td.m_internal_output_index, tx);
    }
  }

  tx_extra_nonce extra_nonce;
  if (find_tx_extra_field_by_type(tx_extra_fields, extra_nonce))
  {
    crypto::hash payment_id;
    if(get_payment_id_from_tx_extra_nonce(extra_nonce.nonce, payment_id))
    {
      uint64_t received = (tx_money_spent_in_ins < tx_money_got_in_outs) ? tx_money_got_in_outs - tx_money_spent_in_ins : 0;
      if (0 < received && null_hash != payment_id)
      {
        payment_details payment;
        payment.m_tx_hash      = cryptonote::get_transaction_hash(tx);
        payment.m_amount       = received;
        payment.m_block_height = height;
        payment.m_unlock_time  = tx.unlock_time;
        m_payments.emplace(payment_id, payment);
        LOG_PRINT_L2("Payment found: " << payment_id << " / " << payment.m_tx_hash << " / " << payment.m_amount);
      }
    }
  }
}
//----------------------------------------------------------------------------------------------------
void wallet2::process_unconfirmed(const cryptonote::transaction& tx)
{
  auto unconf_it = m_unconfirmed_txs.find(get_transaction_hash(tx));
  if(unconf_it != m_unconfirmed_txs.end())
    m_unconfirmed_txs.erase(unconf_it);
}
//----------------------------------------------------------------------------------------------------
void wallet2::process_new_blockchain_entry(const cryptonote::block& b, cryptonote::block_complete_entry& bche, crypto::hash& bl_id, uint64_t height)
{
  //handle transactions from new block

  //optimization: seeking only for blocks that are not older then the wallet creation time plus 1 day. 1 day is for possible user incorrect time setup
  if(b.timestamp + 60*60*24 > m_account.get_createtime())
  {
    TIME_MEASURE_START(miner_tx_handle_time);
    process_new_transaction(b.miner_tx, height);
    TIME_MEASURE_FINISH(miner_tx_handle_time);

    TIME_MEASURE_START(txs_handle_time);
    BOOST_FOREACH(auto& txblob, bche.txs)
    {
      cryptonote::transaction tx;
      bool r = parse_and_validate_tx_from_blob(txblob, tx);
      THROW_WALLET_EXCEPTION_IF(!r, error::tx_parse_error, txblob);
      process_new_transaction(tx, height);
    }
    TIME_MEASURE_FINISH(txs_handle_time);
    LOG_PRINT_L2("Processed block: " << bl_id << ", height " << height << ", " <<  miner_tx_handle_time + txs_handle_time << "(" << miner_tx_handle_time << "/" << txs_handle_time <<")ms");
  }else
  {
    LOG_PRINT_L2( "Skipped block by timestamp, height: " << height << ", block time " << b.timestamp << ", account time " << m_account.get_createtime());
  }
  m_blockchain.push_back(bl_id);
  ++m_local_bc_height;

  if (0 != m_callback)
    m_callback->on_new_block(height, b);
}
//----------------------------------------------------------------------------------------------------
void wallet2::get_short_chain_history(std::list<crypto::hash>& ids)
{
  size_t i = 0;
  size_t current_multiplier = 1;
  size_t sz = m_blockchain.size();
  if(!sz)
    return;
  size_t current_back_offset = 1;
  bool genesis_included = false;
  while(current_back_offset < sz)
  {
    ids.push_back(m_blockchain[sz-current_back_offset]);
    if(sz-current_back_offset == 0)
      genesis_included = true;
    if(i < 10)
    {
      ++current_back_offset;
    }else
    {
      current_back_offset += current_multiplier *= 2;
    }
    ++i;
  }
  if(!genesis_included)
    ids.push_back(m_blockchain[0]);
}
//----------------------------------------------------------------------------------------------------
void wallet2::pull_blocks(uint64_t start_height, size_t& blocks_added)
{
  blocks_added = 0;
  cryptonote::COMMAND_RPC_GET_BLOCKS_FAST::request req = AUTO_VAL_INIT(req);
  cryptonote::COMMAND_RPC_GET_BLOCKS_FAST::response res = AUTO_VAL_INIT(res);
  get_short_chain_history(req.block_ids);
  req.start_height = start_height;
  bool r = net_utils::invoke_http_bin_remote_command2(m_daemon_address + "/getblocks.bin", req, res, m_http_client, WALLET_RCP_CONNECTION_TIMEOUT);
  THROW_WALLET_EXCEPTION_IF(!r, error::no_connection_to_daemon, "getblocks.bin");
  THROW_WALLET_EXCEPTION_IF(res.status == CORE_RPC_STATUS_BUSY, error::daemon_busy, "getblocks.bin");
  THROW_WALLET_EXCEPTION_IF(res.status != CORE_RPC_STATUS_OK, error::get_blocks_error, res.status);

  size_t current_index = res.start_height;
  BOOST_FOREACH(auto& bl_entry, res.blocks)
  {
    cryptonote::block bl;
    r = cryptonote::parse_and_validate_block_from_blob(bl_entry.block, bl);
    THROW_WALLET_EXCEPTION_IF(!r, error::block_parse_error, bl_entry.block);

    crypto::hash bl_id = get_block_hash(bl);
    if(current_index >= m_blockchain.size())
    {
      process_new_blockchain_entry(bl, bl_entry, bl_id, current_index);
      ++blocks_added;
    }
    else if(bl_id != m_blockchain[current_index])
    {
      //split detected here !!!
      THROW_WALLET_EXCEPTION_IF(current_index == res.start_height, error::wallet_internal_error,
        "wrong daemon response: split starts from the first block in response " + string_tools::pod_to_hex(bl_id) +
        " (height " + std::to_string(res.start_height) + "), local block id at this height: " +
        string_tools::pod_to_hex(m_blockchain[current_index]));

      detach_blockchain(current_index);
      process_new_blockchain_entry(bl, bl_entry, bl_id, current_index);
    }
    else
    {
      LOG_PRINT_L2("Block is already in blockchain: " << string_tools::pod_to_hex(bl_id));
    }

    ++current_index;
  }
}
//----------------------------------------------------------------------------------------------------
void wallet2::refresh()
{
  size_t blocks_fetched = 0;
  refresh(0, blocks_fetched);
}
//----------------------------------------------------------------------------------------------------
void wallet2::refresh(uint64_t start_height, size_t & blocks_fetched)
{
  bool received_money = false;
  refresh(start_height, blocks_fetched, received_money);
}
//----------------------------------------------------------------------------------------------------
void wallet2::refresh(uint64_t start_height, size_t & blocks_fetched, bool& received_money)
{
  received_money = false;
  blocks_fetched = 0;
  size_t added_blocks = 0;
  size_t try_count = 0;
  crypto::hash last_tx_hash_id = m_transfers.size() ? get_transaction_hash(m_transfers.back().m_tx) : null_hash;

  while(m_run.load(std::memory_order_relaxed))
  {
    try
    {
      pull_blocks(start_height, added_blocks);
      blocks_fetched += added_blocks;
      if(!added_blocks)
        break;
    }
    catch (const std::exception&)
    {
      blocks_fetched += added_blocks;
      if(try_count < 3)
      {
        LOG_PRINT_L1("Another try pull_blocks (try_count=" << try_count << ")...");
        ++try_count;
      }
      else
      {
        LOG_ERROR("pull_blocks failed, try_count=" << try_count);
        throw;
      }
    }
  }
  if(last_tx_hash_id != (m_transfers.size() ? get_transaction_hash(m_transfers.back().m_tx) : null_hash))
    received_money = true;

  LOG_PRINT_L1("Refresh done, blocks received: " << blocks_fetched << ", balance: " << print_money(balance()) << ", unlocked: " << print_money(unlocked_balance()));
}
//----------------------------------------------------------------------------------------------------
bool wallet2::refresh(size_t & blocks_fetched, bool& received_money, bool& ok)
{
  try
  {
    refresh(0, blocks_fetched, received_money);
    ok = true;
  }
  catch (...)
  {
    ok = false;
  }
  return ok;
}
//----------------------------------------------------------------------------------------------------
void wallet2::detach_blockchain(uint64_t height)
{
  LOG_PRINT_L0("Detaching blockchain on height " << height);
  size_t transfers_detached = 0;

  auto it = std::find_if(m_transfers.begin(), m_transfers.end(), [&](const transfer_details& td){return td.m_block_height >= height;});
  size_t i_start = it - m_transfers.begin();

  for(size_t i = i_start; i!= m_transfers.size();i++)
  {
    auto it_ki = m_key_images.find(m_transfers[i].m_key_image);
    THROW_WALLET_EXCEPTION_IF(it_ki == m_key_images.end(), error::wallet_internal_error, "key image not found");
    m_key_images.erase(it_ki);
    ++transfers_detached;
  }
  m_transfers.erase(it, m_transfers.end());

  size_t blocks_detached = m_blockchain.end() - (m_blockchain.begin()+height);
  m_blockchain.erase(m_blockchain.begin()+height, m_blockchain.end());
  m_local_bc_height -= blocks_detached;

  for (auto it = m_payments.begin(); it != m_payments.end(); )
  {
    if(height <= it->second.m_block_height)
      it = m_payments.erase(it);
    else
      ++it;
  }

  LOG_PRINT_L0("Detached blockchain on height " << height << ", transfers detached " << transfers_detached << ", blocks detached " << blocks_detached);
}
//----------------------------------------------------------------------------------------------------
bool wallet2::deinit()
{
  return true;
}
//----------------------------------------------------------------------------------------------------
bool wallet2::clear()
{
  m_blockchain.clear();
  m_transfers.clear();
  cryptonote::block b;
  cryptonote::generate_genesis_block(b);
  m_blockchain.push_back(get_block_hash(b));
  m_local_bc_height = 1;
  return true;
}
//----------------------------------------------------------------------------------------------------
bool wallet2::store_keys(const std::string& keys_file_name, const std::string& password)
{
  std::string account_data;
  bool r = epee::serialization::store_t_to_binary(m_account, account_data);
  CHECK_AND_ASSERT_MES(r, false, "failed to serialize wallet keys");
  wallet2::keys_file_data keys_file_data = boost::value_initialized<wallet2::keys_file_data>();

  crypto::chacha8_key key;
  crypto::generate_chacha8_key(password, key);
  std::string cipher;
  cipher.resize(account_data.size());
  keys_file_data.iv = crypto::rand<crypto::chacha8_iv>();
  crypto::chacha8(account_data.data(), account_data.size(), key, keys_file_data.iv, &cipher[0]);
  keys_file_data.account_data = cipher;

  std::string buf;
  r = ::serialization::dump_binary(keys_file_data, buf);
  r = r && epee::file_io_utils::save_string_to_file(keys_file_name, buf); //and never touch wallet_keys_file again, only read
  CHECK_AND_ASSERT_MES(r, false, "failed to generate wallet keys file " << keys_file_name);

  return true;
}
//----------------------------------------------------------------------------------------------------
namespace
{
  bool verify_keys(const crypto::secret_key& sec, const crypto::public_key& expected_pub)
  {
    crypto::public_key pub;
    bool r = crypto::secret_key_to_public_key(sec, pub);
    return r && expected_pub == pub;
  }
}
//----------------------------------------------------------------------------------------------------
void wallet2::load_keys(const std::string& keys_file_name, const std::string& password)
{
  wallet2::keys_file_data keys_file_data;
  std::string buf;
  bool r = epee::file_io_utils::load_file_to_string(keys_file_name, buf);
  THROW_WALLET_EXCEPTION_IF(!r, error::file_read_error, keys_file_name);
  r = ::serialization::parse_binary(buf, keys_file_data);
  THROW_WALLET_EXCEPTION_IF(!r, error::wallet_internal_error, "internal error: failed to deserialize \"" + keys_file_name + '\"');

  crypto::chacha8_key key;
  crypto::generate_chacha8_key(password, key);
  std::string account_data;
  account_data.resize(keys_file_data.account_data.size());
  crypto::chacha8(keys_file_data.account_data.data(), keys_file_data.account_data.size(), key, keys_file_data.iv, &account_data[0]);

  const cryptonote::account_keys& keys = m_account.get_keys();
  r = epee::serialization::load_t_from_binary(m_account, account_data);
  r = r && verify_keys(keys.m_view_secret_key,  keys.m_account_address.m_view_public_key);
  r = r && verify_keys(keys.m_spend_secret_key, keys.m_account_address.m_spend_public_key);
  THROW_WALLET_EXCEPTION_IF(!r, error::invalid_password);
}
//----------------------------------------------------------------------------------------------------
crypto::secret_key wallet2::generate(const std::string& wallet_, const std::string& password, const crypto::secret_key& recovery_param, bool recover, bool two_random)
{
  clear();
  prepare_file_names(wallet_);

  boost::system::error_code ignored_ec;
  THROW_WALLET_EXCEPTION_IF(boost::filesystem::exists(m_wallet_file, ignored_ec), error::file_exists, m_wallet_file);
  THROW_WALLET_EXCEPTION_IF(boost::filesystem::exists(m_keys_file,   ignored_ec), error::file_exists, m_keys_file);

  crypto::secret_key retval = m_account.generate(recovery_param, recover, two_random);

  m_account_public_address = m_account.get_keys().m_account_address;

  bool r = store_keys(m_keys_file, password);
  THROW_WALLET_EXCEPTION_IF(!r, error::file_save_error, m_keys_file);

  r = file_io_utils::save_string_to_file(m_wallet_file + ".address.txt", m_account.get_public_address_str());
  if(!r) LOG_PRINT_RED_L0("String with address text not saved");

  store();
  return retval;
}
//----------------------------------------------------------------------------------------------------
void wallet2::wallet_exists(const std::string& file_path, bool& keys_file_exists, bool& wallet_file_exists)
{
  std::string keys_file, wallet_file;
  do_prepare_file_names(file_path, keys_file, wallet_file);

  boost::system::error_code ignore;
  keys_file_exists = boost::filesystem::exists(keys_file, ignore);
  wallet_file_exists = boost::filesystem::exists(wallet_file, ignore);
}
//----------------------------------------------------------------------------------------------------
bool wallet2::parse_payment_id(const std::string& payment_id_str, crypto::hash& payment_id)
{
  cryptonote::blobdata payment_id_data;
  if(!epee::string_tools::parse_hexstr_to_binbuff(payment_id_str, payment_id_data))
    return false;

  if(sizeof(crypto::hash) != payment_id_data.size())
    return false;

  payment_id = *reinterpret_cast<const crypto::hash*>(payment_id_data.data());
  return true;
}
//----------------------------------------------------------------------------------------------------
bool wallet2::prepare_file_names(const std::string& file_path)
{
  do_prepare_file_names(file_path, m_keys_file, m_wallet_file);
  return true;
}
//----------------------------------------------------------------------------------------------------
bool wallet2::check_connection()
{
  if(m_http_client.is_connected())
    return true;

  net_utils::http::url_content u;
  net_utils::parse_url(m_daemon_address, u);
  if(!u.port)
    u.port = RPC_DEFAULT_PORT;
  return m_http_client.connect(u.host, std::to_string(u.port), WALLET_RCP_CONNECTION_TIMEOUT);
}
//----------------------------------------------------------------------------------------------------
void wallet2::load(const std::string& wallet_, const std::string& password)
{
  clear();
  prepare_file_names(wallet_);

  boost::system::error_code e;
  bool exists = boost::filesystem::exists(m_keys_file, e);
  THROW_WALLET_EXCEPTION_IF(e || !exists, error::file_not_found, m_keys_file);

  load_keys(m_keys_file, password);
  LOG_PRINT_L0("Loaded wallet keys file, with public address: " << m_account.get_public_address_str());

  //keys loaded ok!
  //try to load wallet file. but even if we failed, it is not big problem
  if(!boost::filesystem::exists(m_wallet_file, e) || e)
  {
    LOG_PRINT_L0("file not found: " << m_wallet_file << ", starting with empty blockchain");
    m_account_public_address = m_account.get_keys().m_account_address;
    return;
  }
  bool r = tools::unserialize_obj_from_file(*this, m_wallet_file);
  THROW_WALLET_EXCEPTION_IF(!r, error::file_read_error, m_wallet_file);
  THROW_WALLET_EXCEPTION_IF(
    m_account_public_address.m_spend_public_key != m_account.get_keys().m_account_address.m_spend_public_key ||
    m_account_public_address.m_view_public_key  != m_account.get_keys().m_account_address.m_view_public_key,
    error::wallet_files_doesnt_correspond, m_keys_file, m_wallet_file);

  if(m_blockchain.empty())
  {
    cryptonote::block b;
    cryptonote::generate_genesis_block(b);
    m_blockchain.push_back(get_block_hash(b));
  }
  m_local_bc_height = m_blockchain.size();
}
//----------------------------------------------------------------------------------------------------
void wallet2::store()
{
  bool r = tools::serialize_obj_to_file(*this, m_wallet_file);
  THROW_WALLET_EXCEPTION_IF(!r, error::file_save_error, m_wallet_file);
}
//----------------------------------------------------------------------------------------------------
uint64_t wallet2::unlocked_balance()
{
  uint64_t amount = 0;
  BOOST_FOREACH(transfer_details& td, m_transfers)
    if(!td.m_spent && is_transfer_unlocked(td))
      amount += td.amount();

  return amount;
}
//----------------------------------------------------------------------------------------------------
uint64_t wallet2::balance()
{
  uint64_t amount = 0;
  BOOST_FOREACH(auto& td, m_transfers)
    if(!td.m_spent)
      amount += td.amount();

  BOOST_FOREACH(auto& utx, m_unconfirmed_txs)
    amount+= utx.second.m_change;

  return amount;
}
//----------------------------------------------------------------------------------------------------
void wallet2::get_transfers(wallet2::transfer_container& incoming_transfers) const
{
  incoming_transfers = m_transfers;
}
//----------------------------------------------------------------------------------------------------
void wallet2::get_payments(const crypto::hash& payment_id, std::list<wallet2::payment_details>& payments, uint64_t min_height) const
{
  auto range = m_payments.equal_range(payment_id);
  std::for_each(range.first, range.second, [&payments, &min_height](const payment_container::value_type& x) {
    if (min_height < x.second.m_block_height)
    {
      payments.push_back(x.second);
    }
  });
}
//----------------------------------------------------------------------------------------------------
bool wallet2::is_transfer_unlocked(const transfer_details& td) const
{
  if(!is_tx_spendtime_unlocked(td.m_tx.unlock_time))
    return false;

  if(td.m_block_height + DEFAULT_TX_SPENDABLE_AGE > m_blockchain.size())
    return false;

  return true;
}
//----------------------------------------------------------------------------------------------------
bool wallet2::is_tx_spendtime_unlocked(uint64_t unlock_time) const
{
  if(unlock_time < CRYPTONOTE_MAX_BLOCK_NUMBER)
  {
    //interpret as block index
    if(m_blockchain.size()-1 + CRYPTONOTE_LOCKED_TX_ALLOWED_DELTA_BLOCKS >= unlock_time)
      return true;
    else
      return false;
  }else
  {
    //interpret as time
    uint64_t current_time = static_cast<uint64_t>(time(NULL));
    if(current_time + CRYPTONOTE_LOCKED_TX_ALLOWED_DELTA_SECONDS >= unlock_time)
      return true;
    else
      return false;
  }
  return false;
}
//----------------------------------------------------------------------------------------------------
namespace
{
  template<typename T>
  T pop_random_value(std::vector<T>& vec)
  {
    CHECK_AND_ASSERT_MES(!vec.empty(), T(), "Vector must be non-empty");

    size_t idx = crypto::rand<size_t>() % vec.size();
    T res = vec[idx];
    if (idx + 1 != vec.size())
    {
      vec[idx] = vec.back();
    }
    vec.resize(vec.size() - 1);

    return res;
  }
}
//----------------------------------------------------------------------------------------------------
// Select random input sources for transaction.
// returns:
//    direct return: amount of money found
//    modified reference: selected_transfers, a list of iterators/indices of input sources
uint64_t wallet2::select_transfers(uint64_t needed_money, bool add_dust, uint64_t dust, std::list<transfer_container::iterator>& selected_transfers)
{
  std::vector<size_t> unused_transfers_indices;
  std::vector<size_t> unused_dust_indices;

  // aggregate sources available for transfers
  // if dust needed, take dust from only one source (so require source has at least dust amount)
  for (size_t i = 0; i < m_transfers.size(); ++i)
  {
    const transfer_details& td = m_transfers[i];
    if (!td.m_spent && is_transfer_unlocked(td))
    {
      if (dust < td.amount())
        unused_transfers_indices.push_back(i);
      else
        unused_dust_indices.push_back(i);
    }
  }

  bool select_one_dust = add_dust && !unused_dust_indices.empty();
  uint64_t found_money = 0;
  while (found_money < needed_money && (!unused_transfers_indices.empty() || !unused_dust_indices.empty()))
  {
    size_t idx;
    if (select_one_dust)
    {
      idx = pop_random_value(unused_dust_indices);
      select_one_dust = false;
    }
    else
    {
      idx = !unused_transfers_indices.empty() ? pop_random_value(unused_transfers_indices) : pop_random_value(unused_dust_indices);
    }

    transfer_container::iterator it = m_transfers.begin() + idx;
    selected_transfers.push_back(it);
    found_money += it->amount();
  }

  return found_money;
}
//----------------------------------------------------------------------------------------------------
void wallet2::add_unconfirmed_tx(const cryptonote::transaction& tx, uint64_t change_amount)
{
  unconfirmed_transfer_details& utd = m_unconfirmed_txs[cryptonote::get_transaction_hash(tx)];
  utd.m_change = change_amount;
  utd.m_sent_time = time(NULL);
  utd.m_tx = tx;
}
//----------------------------------------------------------------------------------------------------
void wallet2::transfer(const std::vector<cryptonote::tx_destination_entry>& dsts, size_t fake_outputs_count,
                       uint64_t unlock_time, uint64_t fee, const std::vector<uint8_t>& extra, cryptonote::transaction& tx, pending_tx& ptx)
{
  transfer(dsts, fake_outputs_count, unlock_time, fee, extra, detail::digit_split_strategy, tx_dust_policy(fee), tx, ptx);
}
//----------------------------------------------------------------------------------------------------
void wallet2::transfer(const std::vector<cryptonote::tx_destination_entry>& dsts, size_t fake_outputs_count,
                       uint64_t unlock_time, uint64_t fee, const std::vector<uint8_t>& extra)
{
  cryptonote::transaction tx;
  pending_tx ptx;
  transfer(dsts, fake_outputs_count, unlock_time, fee, extra, tx, ptx);
}

namespace {
// split_amounts(vector<cryptonote::tx_destination_entry> dsts, size_t num_splits)
//
// split amount for each dst in dsts into num_splits parts
// and make num_splits new vector<crypt...> instances to hold these new amounts
std::vector<std::vector<cryptonote::tx_destination_entry>> split_amounts(
    std::vector<cryptonote::tx_destination_entry> dsts, size_t num_splits)
{
  std::vector<std::vector<cryptonote::tx_destination_entry>> retVal;

  if (num_splits <= 1)
  {
    retVal.push_back(dsts);
    return retVal;
  }

  // for each split required
  for (size_t i=0; i < num_splits; i++)
  {
    std::vector<cryptonote::tx_destination_entry> new_dsts;

    // for each destination
    for (size_t j=0; j < dsts.size(); j++)
    {
      cryptonote::tx_destination_entry de;
      uint64_t amount;

      amount = dsts[j].amount;
      amount = amount / num_splits;

      // if last split, add remainder
      if (i + 1 == num_splits)
      {
        amount += dsts[j].amount % num_splits;
      }

      de.addr = dsts[j].addr;
      de.amount = amount;

      new_dsts.push_back(de);
    }

    retVal.push_back(new_dsts);
  }

  return retVal;
}
} // anonymous namespace

//----------------------------------------------------------------------------------------------------
// take a pending tx and actually send it to the daemon
void wallet2::commit_tx(pending_tx& ptx)
{
  using namespace cryptonote;
  COMMAND_RPC_SEND_RAW_TX::request req;
  req.tx_as_hex = epee::string_tools::buff_to_hex_nodelimer(tx_to_blob(ptx.tx));
  COMMAND_RPC_SEND_RAW_TX::response daemon_send_resp;
  bool r = epee::net_utils::invoke_http_json_remote_command2(m_daemon_address + "/sendrawtransaction", req, daemon_send_resp, m_http_client, 200000);
  THROW_WALLET_EXCEPTION_IF(!r, error::no_connection_to_daemon, "sendrawtransaction");
  THROW_WALLET_EXCEPTION_IF(daemon_send_resp.status == CORE_RPC_STATUS_BUSY, error::daemon_busy, "sendrawtransaction");
  THROW_WALLET_EXCEPTION_IF(daemon_send_resp.status != CORE_RPC_STATUS_OK, error::tx_rejected, ptx.tx, daemon_send_resp.status);

  add_unconfirmed_tx(ptx.tx, ptx.change_dts.amount);

  LOG_PRINT_L2("transaction " << get_transaction_hash(ptx.tx) << " generated ok and sent to daemon, key_images: [" << ptx.key_images << "]");

  BOOST_FOREACH(transfer_container::iterator it, ptx.selected_transfers)
    it->m_spent = true;

  LOG_PRINT_L0("Transaction successfully sent. <" << get_transaction_hash(ptx.tx) << ">" << ENDL
            << "Commission: " << print_money(ptx.fee+ptx.dust) << " (dust: " << print_money(ptx.dust) << ")" << ENDL
            << "Balance: " << print_money(balance()) << ENDL
            << "Unlocked: " << print_money(unlocked_balance()) << ENDL
            << "Please, wait for confirmation for your balance to be unlocked.");
}

void wallet2::commit_tx(std::vector<pending_tx>& ptx_vector)
{
  for (auto & ptx : ptx_vector)
  {
    commit_tx(ptx);
  }
}

//----------------------------------------------------------------------------------------------------
// separated the call(s) to wallet2::transfer into their own function
//
// this function will make multiple calls to wallet2::transfer if multiple
// transactions will be required
std::vector<wallet2::pending_tx> wallet2::create_transactions(std::vector<cryptonote::tx_destination_entry> dsts, const size_t fake_outs_count, const uint64_t unlock_time, const uint64_t fee, const std::vector<uint8_t> extra)
{

  // failsafe split attempt counter
  size_t attempt_count = 0;

  for(attempt_count = 1; ;attempt_count++)
  {
    auto split_values = split_amounts(dsts, attempt_count);

    // Throw if split_amounts comes back with a vector of size different than it should
    if (split_values.size() != attempt_count)
    {
      throw std::runtime_error("Splitting transactions returned a number of potential tx not equal to what was requested");
    }

    std::vector<pending_tx> ptx_vector;
    try
    {
      // for each new destination vector (i.e. for each new tx)
      for (auto & dst_vector : split_values)
      {
        cryptonote::transaction tx;
        pending_tx ptx;
        transfer(dst_vector, fake_outs_count, unlock_time, fee, extra, tx, ptx);
        ptx_vector.push_back(ptx);

        // mark transfers to be used as "spent"
        BOOST_FOREACH(transfer_container::iterator it, ptx.selected_transfers)
          it->m_spent = true;
      }

      // if we made it this far, we've selected our transactions.  committing them will mark them spent,
      // so this is a failsafe in case they don't go through
      // unmark pending tx transfers as spent
      for (auto & ptx : ptx_vector)
      {
        // mark transfers to be used as not spent
        BOOST_FOREACH(transfer_container::iterator it2, ptx.selected_transfers)
          it2->m_spent = false;

      }

      // if we made it this far, we're OK to actually send the transactions
      return ptx_vector;

    }
    // only catch this here, other exceptions need to pass through to the calling function
    catch (const tools::error::tx_too_big& e)
    {

      // unmark pending tx transfers as spent
      for (auto & ptx : ptx_vector)
      {
        // mark transfers to be used as not spent
        BOOST_FOREACH(transfer_container::iterator it2, ptx.selected_transfers)
          it2->m_spent = false;

      }

      if (attempt_count >= MAX_SPLIT_ATTEMPTS)
      {
        throw;
      }
    }
    catch (...)
    {
      // in case of some other exception, make sure any tx in queue are marked unspent again

      // unmark pending tx transfers as spent
      for (auto & ptx : ptx_vector)
      {
        // mark transfers to be used as not spent
        BOOST_FOREACH(transfer_container::iterator it2, ptx.selected_transfers)
          it2->m_spent = false;

      }

      throw;
    }
  }
}
}

max_stars_repo_name: techqc/SiZ

max_issues_repo_name: techqc/SiZ

max_forks_repo_name: techqc/SiZ


text:
/*    This file is part of the Gudhi Library - https://gudhi.inria.fr/ - which is released under MIT.
 *    See file LICENSE or go to https://gudhi.inria.fr/licensing/ for full license details.
 *    Author(s):       Vincent Rouvreau
 *
 *    Copyright (C) 2015 Inria
 *
 *    Modification(s):
 *      - YYYY/MM Author: Description of the modification
 */

#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE "alpha_complex_3d"
#include <boost/test/unit_test.hpp>
#include <boost/mpl/list.hpp>

#include <cmath>  // float comparison
#include <limits>
#include <string>
#include <vector>
#include <random>
#include <cstddef>  // for std::size_t

#include <gudhi/Alpha_complex_3d.h>
#include <gudhi/graph_simplicial_complex.h>
#include <gudhi/Simplex_tree.h>
#include <gudhi/Unitary_tests_utils.h>
// to construct Alpha_complex from a OFF file of points
#include <gudhi/Points_3D_off_io.h>

#include <CGAL/Random.h>
#include <CGAL/point_generators_3.h>

using Fast_periodic_alpha_complex_3d =
    Gudhi::alpha_complex::Alpha_complex_3d<Gudhi::alpha_complex::complexity::FAST, false, true>;
using Safe_periodic_alpha_complex_3d =
    Gudhi::alpha_complex::Alpha_complex_3d<Gudhi::alpha_complex::complexity::SAFE, false, true>;
using Exact_periodic_alpha_complex_3d =
    Gudhi::alpha_complex::Alpha_complex_3d<Gudhi::alpha_complex::complexity::EXACT, false, true>;

#ifdef GUDHI_DEBUG
typedef boost::mpl::list<Fast_periodic_alpha_complex_3d, Safe_periodic_alpha_complex_3d,
                         Exact_periodic_alpha_complex_3d>
    periodic_variants_type_list;

BOOST_AUTO_TEST_CASE_TEMPLATE(Alpha_complex_periodic_throw, Periodic_alpha_complex_3d, periodic_variants_type_list) {
  std::clog << "Periodic alpha complex 3d exception throw" << std::endl;
  using Bare_point_3 = typename Periodic_alpha_complex_3d::Bare_point_3;
  std::vector<Bare_point_3> p_points;

  // Not important, this is not what we want to check
  p_points.push_back(Bare_point_3(0.0, 0.0, 0.0));

  std::clog << "Check exception throw in debug mode" << std::endl;
  // Check it throws an exception when the cuboid is not iso
  BOOST_CHECK_THROW(Periodic_alpha_complex_3d periodic_alpha_complex(p_points, 0., 0., 0., 0.9, 1., 1.),
                    std::invalid_argument);
  BOOST_CHECK_THROW(Periodic_alpha_complex_3d periodic_alpha_complex(p_points, 0., 0., 0., 1., 0.9, 1.),
                    std::invalid_argument);
  BOOST_CHECK_THROW(Periodic_alpha_complex_3d periodic_alpha_complex(p_points, 0., 0., 0., 1., 1., 0.9),
                    std::invalid_argument);
  BOOST_CHECK_THROW(Periodic_alpha_complex_3d periodic_alpha_complex(p_points, 0., 0., 0., 1.1, 1., 1.),
                    std::invalid_argument);
  BOOST_CHECK_THROW(Periodic_alpha_complex_3d periodic_alpha_complex(p_points, 0., 0., 0., 1., 1.1, 1.),
                    std::invalid_argument);
  BOOST_CHECK_THROW(Periodic_alpha_complex_3d periodic_alpha_complex(p_points, 0., 0., 0., 1., 1., 1.1),
                    std::invalid_argument);
}
#endif

BOOST_AUTO_TEST_CASE(Alpha_complex_periodic) {
  // ---------------------
  // Fast periodic version
  // ---------------------
  std::clog << "Fast periodic alpha complex 3d" << std::endl;

  using Creator = CGAL::Creator_uniform_3<double, Fast_periodic_alpha_complex_3d::Bare_point_3>;
  CGAL::Random random(7);
  CGAL::Random_points_in_cube_3<Fast_periodic_alpha_complex_3d::Bare_point_3, Creator> in_cube(1, random);
  std::vector<Fast_periodic_alpha_complex_3d::Bare_point_3> p_points;

  for (int i = 0; i < 50; i++) {
    Fast_periodic_alpha_complex_3d::Bare_point_3 p = *in_cube++;
    p_points.push_back(p);
  }

  Fast_periodic_alpha_complex_3d periodic_alpha_complex(p_points, -1., -1., -1., 1., 1., 1.);

  Gudhi::Simplex_tree<> stree;
  periodic_alpha_complex.create_complex(stree);

  for (std::size_t index = 0; index < p_points.size(); index++) {
    bool found = false;
    Fast_periodic_alpha_complex_3d::Bare_point_3 ap = periodic_alpha_complex.get_point(index);
    for (auto point : p_points) {
      if ((point.x() == ap.x()) && (point.y() == ap.y()) && (point.z() == ap.z())) {
        found = true;
        break;
      }
    }
    // Check all points from alpha complex are found in the input point cloud
    BOOST_CHECK(found);
  }
  // Exception if we go out of range
  BOOST_CHECK_THROW(periodic_alpha_complex.get_point(p_points.size()), std::out_of_range);

  // ----------------------
  // Exact periodic version
  // ----------------------
  std::clog << "Exact periodic alpha complex 3d" << std::endl;

  std::vector<Exact_periodic_alpha_complex_3d::Bare_point_3> e_p_points;

  for (auto p : p_points) {
    e_p_points.push_back(Exact_periodic_alpha_complex_3d::Bare_point_3(p[0], p[1], p[2]));
  }

  Exact_periodic_alpha_complex_3d exact_alpha_complex(e_p_points, -1., -1., -1., 1., 1., 1.);

  Gudhi::Simplex_tree<> exact_stree;
  exact_alpha_complex.create_complex(exact_stree);

  // ---------------------
  // Compare both versions
  // ---------------------
  std::clog << "Exact periodic alpha complex 3d is of dimension " << exact_stree.dimension() << " - Non exact is "
            << stree.dimension() << std::endl;
  BOOST_CHECK(exact_stree.dimension() == stree.dimension());
  std::clog << "Exact periodic alpha complex 3d num_simplices " << exact_stree.num_simplices() << " - Non exact is "
            << stree.num_simplices() << std::endl;
  BOOST_CHECK(exact_stree.num_simplices() == stree.num_simplices());
  std::clog << "Exact periodic alpha complex 3d num_vertices " << exact_stree.num_vertices() << " - Non exact is "
            << stree.num_vertices() << std::endl;
  BOOST_CHECK(exact_stree.num_vertices() == stree.num_vertices());

  // We cannot compare as objects from dispatcher on the alpha shape is not deterministic.
  // cf. https://github.com/CGAL/cgal/issues/3346
  auto sh = stree.filtration_simplex_range().begin();
  auto sh_exact = exact_stree.filtration_simplex_range().begin();

  while (sh != stree.filtration_simplex_range().end() || sh_exact != exact_stree.filtration_simplex_range().end()) {
    GUDHI_TEST_FLOAT_EQUALITY_CHECK(stree.filtration(*sh), exact_stree.filtration(*sh_exact), 1e-14);

    std::vector<int> vh(stree.simplex_vertex_range(*sh).begin(), stree.simplex_vertex_range(*sh).end());
    std::vector<int> exact_vh(exact_stree.simplex_vertex_range(*sh_exact).begin(),
                              exact_stree.simplex_vertex_range(*sh_exact).end());

    BOOST_CHECK(vh.size() == exact_vh.size());
    ++sh;
    ++sh_exact;
  }

  BOOST_CHECK(sh == stree.filtration_simplex_range().end());
  BOOST_CHECK(sh_exact == exact_stree.filtration_simplex_range().end());

  // ----------------------
  // Safe periodic version
  // ----------------------
  std::clog << "Safe periodic alpha complex 3d" << std::endl;

  std::vector<Safe_periodic_alpha_complex_3d::Bare_point_3> s_p_points;

  for (auto p : p_points) {
    s_p_points.push_back(Safe_periodic_alpha_complex_3d::Bare_point_3(p[0], p[1], p[2]));
  }

  Safe_periodic_alpha_complex_3d safe_alpha_complex(s_p_points, -1., -1., -1., 1., 1., 1.);

  Gudhi::Simplex_tree<> safe_stree;
  safe_alpha_complex.create_complex(safe_stree);

  // ---------------------
  // Compare both versions
  // ---------------------
  // We cannot compare as objects from dispatcher on the alpha shape is not deterministic.
  // cf. https://github.com/CGAL/cgal/issues/3346
  sh = stree.filtration_simplex_range().begin();
  auto sh_safe = safe_stree.filtration_simplex_range().begin();

  while (sh != stree.filtration_simplex_range().end() || sh_safe != safe_stree.filtration_simplex_range().end()) {
    GUDHI_TEST_FLOAT_EQUALITY_CHECK(stree.filtration(*sh), safe_stree.filtration(*sh_safe), 1e-14);

    std::vector<int> vh(stree.simplex_vertex_range(*sh).begin(), stree.simplex_vertex_range(*sh).end());
    std::vector<int> safe_vh(safe_stree.simplex_vertex_range(*sh_safe).begin(),
                             safe_stree.simplex_vertex_range(*sh_safe).end());

    BOOST_CHECK(vh.size() == safe_vh.size());
    ++sh;
    ++sh_safe;
  }

  BOOST_CHECK(sh == stree.filtration_simplex_range().end());
  BOOST_CHECK(sh_safe == safe_stree.filtration_simplex_range().end());
}


text:
#include <bunsan/curl/http/header.hpp>

#include <bunsan/curl/http/error.hpp>

#include <boost/algorithm/string/case_conv.hpp>
#include <boost/assert.hpp>
#include <boost/io/detail/quoted_manip.hpp>
#include <boost/regex.hpp>

namespace bunsan {
namespace curl {
namespace http {

std::string header::merger::operator()(const std::string &value) const {
  BOOST_ASSERT(m_name);
  if (value.empty())
    return *m_name + ':';
  else
    return *m_name + ": " + value;
}

const std::string &header::value() const {
  if (!unique_value())
    BOOST_THROW_EXCEPTION(header_non_unique_value_error()
                          << header_non_unique_value_error::name(name()));
  return m_values[0];
}

header::values_const_range header::values() const {
  return values_const_range(m_values.begin(), m_values.end());
}

header::plain_const_range header::plain_headers() const {
  return plain_const_range(
      plain_const_iterator(m_values.begin(), merger(&m_name)),
      plain_const_iterator(m_values.end(), merger(&m_name)));
}

void header::merge(const header &h) {
  if (name() != h.name())
    BOOST_THROW_EXCEPTION(
        header_merge_incompatible_name_error()
        << header_merge_incompatible_name_error::name(name())
        << header_merge_incompatible_name_error::other_name(h.name()));
  m_values.insert(m_values.end(), h.m_values.begin(), h.m_values.end());
}

void header::merge(header &&h) {
  if (name() != h.name())
    BOOST_THROW_EXCEPTION(
        header_merge_incompatible_name_error()
        << header_merge_incompatible_name_error::name(name())
        << header_merge_incompatible_name_error::other_name(h.name()));
  for (std::string &value : h.m_values) m_values.push_back(std::move(value));
  h.m_name.clear();
  h.m_values.clear();
}

std::string header::make_name(const std::string &raw_name) {
  return boost::algorithm::to_lower_copy(raw_name);
}

header header::parse(const std::string &data) {
  static const boost::regex general_header(
      "^(?<name>[^ ]+)"
      " *: *"
      "(?<value>([^ ](.*[^ ])?)?)"
      " *$");
  boost::smatch result;
  if (boost::regex_match(data, result, general_header)) {
    const boost::ssub_match name = result["name"];
    const boost::ssub_match value = result["value"];
    BOOST_ASSERT(name.matched);
    BOOST_ASSERT(value.matched);
    return header{make_name(name), value};
  }
  BOOST_THROW_EXCEPTION(header_parse_error()
                        << header_parse_error::message("Not a header")
                        << header_parse_error::header_data(data));
}

std::ostream &operator<<(std::ostream &out, const header &h) {
  out << h.name() << ':';
  if (h.unique_value()) {
    if (!h.value().empty()) out << ' ';
    out << h.value();
  } else {
    out << " [";
    bool first = true;
    for (const std::string &value : h.values()) {
      if (!first) out << ", ";
      first = false;
      out << boost::io::quoted(value);
    }
    out << ']';
  }
  return out;
}

}  // namespace http
}  // namespace curl
}  // namespace bunsan


text:
//
//  multivector_AWT.cpp
//
//  Created by r. on 18/05/14
//

// Disables checks in boost
#ifndef NDEBUG
#define NDEBUG
#endif

//
#include "../include/reporter.hpp"

#include <iostream>
#include "../include/stopwatch.hpp"
#include "../include/multivector.hpp"
#include "../include/multivector_AWT.hpp"
#include "../include/tFEM.hpp"
#include "../include/AWT.hpp"

#include <boost/numeric/ublas/io.hpp>
#include <boost/numeric/ublas/matrix_sparse.hpp>

namespace mypara
{
	using namespace std;
	namespace mpi = boost::mpi;
	namespace ublas = boost::numeric::ublas;

	void test_multivector_AWT_basic()
	{
		cout << "Enter: mypara::test_multivector_AWT_basic()" << endl;
		stopwatch::Time time(stopwatch::watches, "mypara::test_multivector_AWT_basic()");

		mpi::communicator world;

		typedef ublas::matrix<double> matrix;

		using namespace mypara;

		unsigned int size1 = 3; // Number of rows
		unsigned int size2 = 9; // Number of columns

		// Create AWT
		double T = 4;
		spacetime::tmesh te;
		te.makeuniform(0, T, size2);

		spacetime::tFEM tfem(te);

		unsigned int nu = 2;
		mypara::AWT awt(tfem.AtE, tfem.MtE, nu);

		// Check generalized "eigenvalues" of awt
		{
			spacetime::AWT awt2(tfem.AtE, tfem.MtE, nu);
			bool ok = true;
			for (auto i = 0; i != awt.gamma.size(); ++i) {
				ok = ok && (fabs(awt.gamma[i] - awt2.gamma[i]) <= 1e-8);
			}
			cout << "Eigenvalues OK? " << (ok ? "YES" : "NO") << endl;
			assert(ok);
		}

		matrix v_ref(size1, size2); v_ref.clear();
		// Create matrix to be distributed
		{
			for (unsigned int j = 0; j != size2; ++j)
			{
				v_ref(j % size1, j) = 1;
//				v_ref(j, j) = 1;
			}
		}

		multivector v(size1, size2, world);
		// Distributed matrix
		{
			for (unsigned int j = v.getja(); j < v.getjb(); ++j) {
				v.colio_local(j) = ublas::column(v_ref, j);
			}
		}

		// Check multivector::get_whole()
		{
			matrix z = (v_ref - v.getwhole());
			bool ok = (ublas::norm_frobenius(z) == 0);
			cout << "Get whole OK? " << (ok ? "YES" : "NO") << endl;
			assert(ok);
			world.barrier();
		}

		// Print info
		{
			for (unsigned int j = v.getja(); j < v.getjb(); ++j) {
				cout << "Proc " << world.rank() << ": " << "column #" << j << " is " << v.colio_local(j) << endl;
			}
			cout.flush(); world.barrier();
		}

		// Multiplication 1
		{
			// Print info
			{
				if (!world.rank()) cout << "Testing right multiplication by T" << endl;
				cout.flush(); world.barrier();
			}

			multivector w = awt.uT(v);

			matrix w_ref;
			{
				spacetime::AWT awt(tfem.AtE, tfem.MtE, nu);
				w_ref = ublas::prod(v_ref, awt.V);
			}

			// Print info
			{
				for (unsigned int j = w.getja(); j < w.getjb(); ++j) {
					cout << "Proc " << world.rank() << ": " << "column #" << j << " is " << w.colio_local(j) << endl;
				}

				multivector::dense_matrix w_whole = w.getwhole();
				if (!world.rank()) cout << "w_whole: " << w_whole << endl;

				cout.flush(); world.barrier();
			}

			// Check multiplication result
			{
				if (!world.rank()) cout << "w_ref: " << w_ref << endl;
				matrix z = (w_ref - w.getwhole());
				bool ok = (ublas::norm_frobenius(z) <= 1e-10);
				cout << "Multiplication 1 OK? " << (ok ? "YES" : "NO") << endl;
				assert(ok);
			}
		}

		// Multiplication 2
		{
			// Print info
			{
				if (!world.rank()) cout << "Testing right multiplication by Tt" << endl;
				cout.flush(); world.barrier();
			}

			multivector w = awt.uTt(v);

			matrix w_ref;
			{
				spacetime::AWT awt(tfem.AtE, tfem.MtE, nu);
				w_ref = ublas::prod(v_ref, ublas::trans(awt.V));
			}

			// Print info
			{
				for (unsigned int j = w.getja(); j < w.getjb(); ++j) {
					cout << "Proc " << world.rank() << ": " << "column #" << j << " is " << w.colio_local(j) << endl;
				}

				multivector::dense_matrix w_whole = w.getwhole();
				if (!world.rank()) cout << "w_whole: " << w_whole << endl;

				cout.flush(); world.barrier();
			}

			// Check multiplication result
			{
				if (!world.rank()) cout << "w_ref: " << w_ref << endl;
				matrix z = (w_ref - w.getwhole());
				bool ok = (ublas::norm_frobenius(z) <= 1e-10);
				cout << "Multiplication 2 OK? " << (ok ? "YES" : "NO") << endl;
				assert(ok);
			}
		}

		//
		{
			multivector::dense_matrix v_whole = v.getwhole();

			// Print info
			{
				if (!world.rank()) cout << "v_whole: " << v_whole << endl;
				cout.flush(); world.barrier();
			}

		}

		cout << "Exit: mypara::test_multivector_AWT_basic()" << endl;
	}

//	void test_multivector_AWT_large()
//	{
//		cout << "Enter: mypara::test_multivector_AWT_large()" << endl;
//		stopwatch::Time time(stopwatch::watches, "mypara::test_multivector_AWT_large()");
//
//		mpi::communicator world;
//
//		unsigned int size1 = 100000;
//		unsigned int size2 = (1 << 12);
//
//		multivector v(size1, size2, world);
//
//		{
//			typedef ublas::compressed_matrix<double> sparse_matrix;
//
//			sparse_matrix m(size2, size2, 3*size2); m.clear();
//			m = ublas::identity_matrix<>(size2);
//
//			stopwatch::StopWatch w;
//			w.tic();
//			v * m;
//			w.add();
//
//			// Print timings
//			{
//				cout.flush(); world.barrier();
//				if (!world.rank())
//				{
//					cout << "@iden: ";
//					cout << "size2: " << size2 << " ";
//					cout << "time(ms): " << w.ms().count() << " ";
//					cout << endl;
//				}
//				world.barrier();
//			}
//		}
//
//		cout << "Exit: mypara::test_multivector_AWT_large()" << endl;
//	}

	void test_multivector_AWT_scale()
	{
		cout << "Enter: mypara::test_multivector_AWT_scale()" << endl;
		stopwatch::Time time(stopwatch::watches, "mypara::test_multivector_AWT_scale()");

		reporter::note("Parallel AWT scalability test");
		reporter::note("Timings are in milliseconds");

		typedef ublas::matrix<double> matrix;
		typedef ublas::compressed_matrix<double> sparse_matrix;

		mpi::communicator world;

		//unsigned int n1 = 12; // size1 = dimV increases up to (2 ^ n1)
		unsigned int n2 = 14; // size2 = dimE increases up to (2 ^ n2)

		//for (unsigned int size1 = (1 << n1); size1 <= (1 << n1); size1 *= 2)
		unsigned size1 = 1953;
		reporter::note["dimV"] = size1;
		reporter::note("Number of temporal elements")["N = []"];
		reporter::note("Multiplication by T [ms]")["T = []"];
		reporter::note("Multiplication by V [ms]")["V = []"];
		{
			for (unsigned int size2 = 1; size2 <= (1 << n2); size2 *= 2)
			{
				reporter::note[""];
				reporter::note["n"] = size2;

				multivector v(size1, 1 + size2, world);

				// Create AWT
				double T = 2;
				spacetime::tmesh te;
				te.makeuniform(0, T, v.getot());

				spacetime::tFEM tfem(te);

				unsigned int nu = 2;
				AWT awt(tfem.AtE, tfem.MtE, nu);

				double t_max = 0;

				// Multiply by T
				{
					stopwatch::StopWatch w;
					//awt.uT(v); // compute jplan
					w.tic();
					awt.uT(v);
					w.add();
					double t = w.ms().count();
					t_max = max(t, t_max);

					// Print timings
					{
						cout.flush(); world.barrier();
						if (!world.rank())
						{
							cout << "@T: ";
							cout << "size1: " << size1 << " ";
							cout << "size2: " << size2 << " ";
							cout << "time(ms): " << t << " ";
							cout << endl;
						}
						world.barrier();
					}

					reporter::note["t"] = t;
				}

				// Multiply by Tt
				{
					stopwatch::StopWatch w;
					//awt.uTt(v); // compute jplan
					w.tic();
					awt.uTt(v);
					w.add();
					double v = w.ms().count();
					t_max = max(v, t_max);

					// Print timings
					{
						cout.flush(); world.barrier();
						if (!world.rank())
						{
							cout << "@V: ";
							cout << "size1: " << size1 << " ";
							cout << "size2: " << size2 << " ";
							cout << "time(ms): " << v << " ";
							cout << endl;
						}
						world.barrier();
					}

					reporter::note["v"] = v;
				}

				reporter::note["N.append(n);"];
				reporter::note["T.append(t);"];
				reporter::note["V.append(v);"];

				// Abort loop if the trafo is taking too long
				double t_max_ok = 4 * 60e3; // seconds
				if (t_max >= t_max_ok) break;
			} // for size2
		} // for size1

		cout << "Exit: mypara::test_multivector_AWT_scale()" << endl;
	}
}

void test()
{
	reporter::note.is_quiet = (boost::mpi::communicator().rank() != 0);

	mypara::test_multivector_AWT_basic();
//    mypara::test_multivector_AWT_large();
    mypara::test_multivector_AWT_scale();
}

max_stars_repo_name: numpde/parabolic

max_issues_repo_name: numpde/parabolic

max_forks_repo_name: numpde/parabolic


text:
// FILE NAME:       $HeadURL: svn+ssh://svn.cm.aol.com/advertising/adlearn/gen1/trunk/lib/cpp/DataProxy/test/PartitionNodeTest.hpp $
//
// REVISION:        $Revision: 280002 $
//
// COPYRIGHT:       (c) 2006 Advertising.com All Rights Reserved.
//
// LAST UPDATED:    $Date: 2013-06-03 15:11:03 -0400 (Mon, 03 Jun 2013) $
// UPDATED BY:      $Author: sstrick $

#ifndef _PARTITION_NODE_TEST_HPP_
#define _PARTITION_NODE_TEST_HPP_

#include <cppunit/TestFixture.h>
#include <cppunit/extensions/HelperMacros.h>
#include <boost/scoped_ptr.hpp>

class TempDirectory;

class PartitionNodeTest : public CppUnit::TestFixture
{
private:
	CPPUNIT_TEST_SUITE( PartitionNodeTest );
	CPPUNIT_TEST( testInvalidXml );
	CPPUNIT_TEST( testOperationAttributeParsing );
	CPPUNIT_TEST( testPing );
	CPPUNIT_TEST( testLoad );
	CPPUNIT_TEST( testLoadNotSupported );
	CPPUNIT_TEST( testStore );
	CPPUNIT_TEST( testStoreSkipSort );
	CPPUNIT_TEST( testStoreNoData );
	CPPUNIT_TEST( testStoreExceptions );
	CPPUNIT_TEST( testDelete );
	CPPUNIT_TEST( testDeleteNotSupported );
	CPPUNIT_TEST_SUITE_END();

public:
	PartitionNodeTest();
	virtual ~PartitionNodeTest();

	void setUp();
	void tearDown();

	void testInvalidXml();
	void testOperationAttributeParsing();
	void testPing();
	void testLoad();
	void testLoadNotSupported();
	void testStore();
	void testStoreSkipSort();
	void testStoreNoData();
	void testStoreExceptions();
	void testDelete();
	void testDeleteNotSupported();

private:
	boost::scoped_ptr<TempDirectory> m_pTempDir;
};

#endif //_PARTITION_NODE_TEST_HPP_

ext: hpp

max_stars_repo_name: aol/DataProxyLibrary

max_issues_repo_name: aol/DataProxyLibrary

max_forks_repo_name: aol/DataProxyLibrary


text:
////////////////////////////////////////////////////////////////////////////////
/// Copyright 2018-present Xinyan DAI<xinyan.dai@outlook.com>
///
/// permission is hereby granted, free of charge, to any person obtaining a copy
/// of this software and associated documentation files (the "Software"), to
/// deal in the Software without restriction, including without limitation the
/// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
/// sell copies of the Software, and to permit persons to whom the Software is
/// furnished to do so, subject to the following conditions:
///
/// The above copyright notice and this permission notice shall be included in
/// all copies or substantial portions ofthe Software.
///
/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
/// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
/// IN THE SOFTWARE.

/// @version 0.1
/// @author  Xinyan DAI
/// @contact xinyan.dai@outlook.com
//////////////////////////////////////////////////////////////////////////////

#pragma once

#include <utility>
#include <vector>
#include <random>
#include <unordered_map>
#include <boost/progress.hpp>

#include "rptree.hpp"
#include "rptree.hpp"
#include "joint_inverted.hpp"
#include "../index.hpp"

namespace ss {

    using std::vector;

    template<class DataType>
    class MultiPQIndex : public Index<DataType > {
    protected:
        vector<KMeansIndex<DataType > * >   _left_joint_index;
        vector<KMeansIndex<DataType > * >   _right_joint_index;
        int                                 _left_dimension;
        int                                 _right_dimension;
    public:
        explicit MultiPQIndex(const parameter& para) :
            Index<DataType >(para), _left_joint_index(para.forest_size), _right_joint_index(para.forest_size)  {
        }
        ~MultiPQIndex() {
            for (KMeansIndex<DataType> * pointer : _left_joint_index) { if (pointer) delete pointer;}
            for (KMeansIndex<DataType> * pointer : _right_joint_index) { if (pointer) delete pointer; }
        }

        void Train(const Matrix<DataType > & data) override {
            _left_dimension = data.getDim() / 2;
            _right_dimension = data.getDim() - data.getDim() / 2;
            auto left = ss::GroupCenters(
                    Visitor<DataType >(data, 0, _left_dimension), this->_para);
            auto right = ss::GroupCenters(
                    Visitor<DataType >(data, _left_dimension, _right_dimension), this->_para);

            for (int l = 0; l < this->_para.forest_size; ++l) {
                _left_joint_index[l] = new KMeansIndex<DataType >(this->_para);
                _left_joint_index[l]->set_centers(left[l]);

                _right_joint_index[l] = new KMeansIndex<DataType >(this->_para);
                _right_joint_index[l]->set_centers(right[l]);
            }
        }

        void Add(const Matrix<DataType > & data) override {

            for (int l = 0; l < this->_para.forest_size; ++l) {
                _left_joint_index[l]->Assign(Visitor<DataType >(data, 0, _left_dimension));
                _right_joint_index[l]->Assign(Visitor<DataType >(data, _left_dimension, _right_dimension));
            }
        }

        void Search(const DataType *query, const std::function<void (int)>& prober) override {
            for (int l = 0; l < this->_para.forest_size; ++l) {
                const vector<int>& left_idx = _left_joint_index[l]->Search(query);

                for (int i = 0; i < this->_para.forest_size; ++i) {
                    const vector<int>& right_idx = _right_joint_index[i]->Search(query + _left_dimension);
                    std::vector<int> indices;
                    indices.reserve(std::min(left_idx.size(), right_idx.size()));

                    std::set_intersection(
                            left_idx.begin(),left_idx.end(),
                            right_idx.begin(),right_idx.end(),
                            std::back_inserter(indices));
                    for (int id : indices) {
                        prober(id);
                    }
                }
            }
        }

    };

} // namespace ss

max_stars_repo_name: xinyandai/similarity-search

max_issues_repo_name: xinyandai/similarity-search

max_forks_repo_name: xinyandai/similarity-search


text:
/*
	Provides future_select free functions, which allow
	creation of a future which becomes ready based on the states of
	a group of input futures.  A future returned by future_select
	becomes ready when any one
	of the input futures becomes ready or has an exception.

	begin: Frank Hess <frank.hess@nist.gov>  2008-05-20
*/

//  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 _POET_FUTURE_SELECT_HPP
#define _POET_FUTURE_SELECT_HPP

#include <boost/bind.hpp>
#include <boost/config.hpp>
#include <boost/enable_shared_from_this.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/weak_ptr.hpp>
#include <cstddef>
#include <iterator>
#include <poet/future.hpp>
#include <poet/detail/nonvoid.hpp>
#include <poet/detail/utility.hpp>
#include <deque>
#include <list>

namespace poet
{
	template<typename R, typename Combiner, typename T1>
	future<R> future_combining_barrier(const Combiner &combiner, const future<T1> &f1);

	namespace detail
	{
		template<typename T>
		const typename nonvoid<T>::type& nonvoid_future_body_get(const future_body_base<T> &body)
		{
			return body.getValue();
		}
		inline const nonvoid<void>::type& nonvoid_future_body_get(const future_body_untyped_base &body)
		{
			return template_static<nonvoid<void>, nonvoid<void>::type>::object;
		}

		template<typename T>
			class future_selector_body: public boost::enable_shared_from_this<future_selector_body<T> >
		{
			typedef std::list<boost::shared_ptr<typename nonvoid_future_body_base<T>::type> > dependencies_type;
			typedef future_body<typename nonvoid<T>::type> dependent_type;
			typedef std::deque<boost::weak_ptr<dependent_type> > selected_container_type;
			typedef std::deque<boost::shared_ptr<dependent_type> > fulfilled_container_type;
			struct dependency_eraser_info
			{
				dependency_eraser_info(): iterator_valid(false)
				{}
				boost::signals2::connection waiter_connection;
				typename dependencies_type::iterator iterator;
				bool iterator_valid;
			};
		public:
			static boost::shared_ptr<future_selector_body> create()
			{
				boost::shared_ptr<future_selector_body> new_object(new future_selector_body);
				new_object->_waiter_callbacks.set_owner(new_object);
				new_object->pop_selected();
				return new_object;
			}
			boost::shared_ptr<future_selector_body> clone() const
			{
				boost::shared_ptr<future_selector_body> new_object(new future_selector_body(*this));
				new_object->_waiter_callbacks.set_owner(new_object);
				typename dependencies_type::iterator it;
				for(it = new_object->_dependencies.begin(); it != new_object->_dependencies.end(); ++it)
				{
					new_object->connect_to_dependency(it);
				}
				return new_object;
			}
			void push(const future<T> &f)
			{
				const boost::shared_ptr<typename nonvoid_future_body_base<T>::type> body = get_future_body(f);
				const boost::shared_ptr<dependency_eraser_info> eraser_info(new dependency_eraser_info);
				typename dependencies_type::iterator dep_it;
				{
					boost::unique_lock<boost::mutex> lock(_mutex);

					dep_it = _dependencies.insert(_dependencies.end(), body);
					++_dependencies_size;
				}
				connect_to_dependency(dep_it);
			}
			future<T> selected() const
			{
				boost::unique_lock<boost::mutex> lock(_mutex);
				return create_future<T>(_selected);
			}
			void pop_selected()
			{
				boost::unique_lock<boost::mutex> lock(_mutex);
				if(_fulfilled_promises.empty())
				{
					lock.unlock();

					boost::shared_ptr<dependent_type> dependent = dependent_type::create();
					dependent->waiter_callbacks().observe(_waiter_callbacks);

					/* stick a shared_ptr that owns this onto the dependent so it will keep us alive
					as long as it needs us. */
					dependent->add_dependency(this->shared_from_this());

					lock.lock();
					_selected = dependent;
					_selected_promises.push_back(dependent);
				}else
				{
					_selected = _fulfilled_promises.front();
					_fulfilled_promises.pop_front();
				}
			}
			std::ptrdiff_t size() const
			{
				boost::unique_lock<boost::mutex> lock(_mutex);
				return _dependencies_size +_fulfilled_promises.size() - _selected_promises.size() + 1;
			}
			/* detach means the user isn't going to call push or pop_selected any more,
			since future_selector object has destructed.  So cancel futures that
			cannot possibly complete otherwise. */
			void detach()
			{
				boost::unique_lock<boost::mutex> lock(_mutex);
				const int extra_selected = _selected_promises.size() - _dependencies_size;
				int i;
				boost::shared_ptr<dependent_type> dependent;
				for(i = 0; i < extra_selected; ++i)
				{
					dependent = _selected_promises.back().lock();
					if(dependent) dependent->cancel(poet::copy_exception(uncertain_future()));
					_selected_promises.pop_back();
				}

				_selected.reset();
				_fulfilled_promises.clear();
			}
		private:
			future_selector_body():
				_waiter_callbacks(_mutex, _condition), _dependencies_size(0)
			{
			}
			future_selector_body(const future_selector_body &other):
				_waiter_callbacks(_mutex, _condition)
			{
				boost::unique_lock<boost::mutex> lock(other._mutex);

				/* _selected_promises in new_object should have same size as original,
				but only has expired weak_ptr, since the original will handle fulfilling
				the its real _selected_promises. */
				_selected_promises.resize(other._selected_promises.size());
				_selected = other._selected;
				_fulfilled_promises = other._fulfilled_promises;
				_dependencies = other._dependencies;
				_dependencies_size = other._dependencies_size;
			}
			void wait_event(typename dependencies_type::iterator completed_dependency)
			{
				boost::shared_ptr<typename nonvoid_future_body_base<T>::type> dependency;
				boost::shared_ptr<dependent_type> fulfilled_promise;
 				{
					boost::unique_lock<boost::mutex> lock(_mutex);
					if(_selected_promises.empty())
					{
						fulfilled_promise = dependent_type::create();
						_fulfilled_promises.push_back(fulfilled_promise);
					}else
					{
						fulfilled_promise = _selected_promises.front().lock();
						_selected_promises.pop_front();
					}
					dependency = *completed_dependency;
					_dependencies.erase(completed_dependency);
					--_dependencies_size;
				}
				if(fulfilled_promise == false) return;

				const bool dep_ready = dependency->ready();

				if(dep_ready)
				{
					fulfilled_promise->setValue(nonvoid_future_body_get(*dependency));
				}else
				{
					exception_ptr ep = dependency->get_exception_ptr();
					fulfilled_promise->cancel(ep);
				}
			}
			void check_dependency(const boost::weak_ptr<typename nonvoid_future_body_base<T>::type> &weak_dependency,
				const boost::shared_ptr<dependency_eraser_info> &dependency_eraser_info)
			{
				boost::shared_ptr<typename nonvoid_future_body_base<T>::type> dependency = weak_dependency.lock();
				if(!dependency)
				{
					throw boost::signals2::expired_slot();
				}

				const bool dep_ready = dependency->ready();
				exception_ptr ep;

				if(!dep_ready) ep = dependency->get_exception_ptr();

				if(dep_ready || ep)
				{
					{
						boost::unique_lock<boost::mutex> lock(_mutex);
						if(dependency_eraser_info->iterator_valid == false)
						{
							throw boost::signals2::expired_slot();
						}
						dependency_eraser_info->iterator_valid = false;
						dependency_eraser_info->waiter_connection.disconnect();
					}
					_waiter_callbacks.post(boost::bind(&future_selector_body::wait_event, this, dependency_eraser_info->iterator));
					throw boost::signals2::expired_slot();
				}
			}
			void connect_to_dependency(typename dependencies_type::iterator dep_it)
			{
				const boost::shared_ptr<typename nonvoid_future_body_base<T>::type> body = *dep_it;

				boost::shared_ptr<dependency_eraser_info> eraser_info(new dependency_eraser_info);
				eraser_info->iterator = dep_it;
				eraser_info->iterator_valid = true;
				eraser_info->waiter_connection = _waiter_callbacks.observe(body->waiter_callbacks());

				typedef typename future_body_untyped_base::update_signal_type::slot_type update_slot_type;
				update_slot_type update_slot(&future_selector_body::check_dependency, this,
					make_weak(body), eraser_info);
				update_slot.track(this->shared_from_this());
				boost::signals2::connection conn;
				conn = body->connectUpdate(update_slot);
				// deal with futures which completed before we got them
				try
				{
					update_slot();
				}
				catch(const boost::signals2::expired_slot &)
				{
					conn.disconnect();
				}
			}

			waiter_event_queue _waiter_callbacks;
			mutable boost::mutex _mutex;
			mutable boost::condition _condition;
			selected_container_type _selected_promises;
			fulfilled_container_type _fulfilled_promises;
			boost::shared_ptr<dependent_type> _selected;
			dependencies_type _dependencies;
			std::size_t _dependencies_size;
		};

		/* future_body for void futures returned by future_select.  Becomes ready
			when any of the futures on its list have become ready or has an exception.
		*/
		template<typename T>
		class future_select_body;

		template<>
		class future_select_body<void>:
			public virtual future_body_untyped_base
		{
			typedef boost::shared_ptr<future_body_untyped_base > future_body_dependency_type;
			// needed by msvc9
			template<typename U>
			friend class future_select_body;
		public:
			typedef future_body_untyped_base::update_signal_type update_signal_type;

			template<typename InputIterator>
			static boost::shared_ptr<future_select_body> create(InputIterator future_begin, InputIterator future_end)
			{
				boost::shared_ptr<future_select_body> new_object(new future_select_body);
				init(new_object, future_begin, future_end);
				return new_object;
			}

			virtual bool ready() const
			{
				boost::unique_lock<boost::mutex> lock(mutex());
				return nolock_ready();
			}
			virtual void join() const
			{
				boost::unique_lock<boost::mutex> lock(mutex());
				condition().wait(lock, boost::bind(&future_select_body::check_if_complete, this, &lock));
			}
			virtual bool timed_join(const boost::system_time &absolute_time) const
			{
				boost::unique_lock<boost::mutex> lock(mutex());
				return condition().timed_wait(lock, absolute_time, boost::bind(&future_select_body::check_if_complete, this, &lock));
			}
			virtual void cancel(const poet::exception_ptr &exp)
			{}
			virtual exception_ptr get_exception_ptr() const
			{
				boost::unique_lock<boost::mutex> lock(mutex());
				if(!_first_complete_dependency) return exception_ptr();
				return _first_complete_dependency->get_exception_ptr();
			}
			virtual waiter_event_queue& waiter_callbacks() const
			{
				return _waiter_callbacks;
			}
		protected:
			future_select_body(): _waiter_callbacks(future_body_untyped_base::mutex(), future_body_untyped_base::condition())
			{}
			template<typename InputIterator>
			static void init(const boost::shared_ptr<future_select_body> &new_object, InputIterator future_begin, InputIterator future_end)
			{
				new_object->_waiter_callbacks.set_owner(new_object);

				InputIterator it;
				for(it = future_begin; it != future_end; ++it)
				{
					typedef update_signal_type::slot_type update_slot_type;
					update_slot_type update_slot(&future_select_body::check_dependency, new_object.get(),
						make_weak(get_future_body(*it)));
					update_slot.track(new_object);
					boost::signals2::connection conn;
					conn = get_future_body(*it)->connectUpdate(update_slot);
					try
					{
						update_slot();
					}
					catch(const boost::signals2::expired_slot &)
					{
						conn.disconnect();
						break;
					}

					new_object->waiter_callbacks().observe(get_future_body(*it)->waiter_callbacks());

					new_object->_dependencies.push_back(get_future_body(*it));
				}
			}
			bool check_if_complete(boost::unique_lock<boost::mutex> *lock) const
			{
				if(_first_complete_dependency) return true;
				lock->unlock();
				_waiter_callbacks.poll();
				lock->lock();
				return _first_complete_dependency.get() != 0;
			}

			mutable future_body_dependency_type _first_complete_dependency;
		private:
			void check_dependency(const boost::weak_ptr<future_body_untyped_base> &weak_dependency) const
			{
				boost::shared_ptr<future_body_untyped_base> dependency(weak_dependency);
				if(dependency == false)
				{
					throw boost::signals2::expired_slot();
				}
				bool emit_signal = false;
				{
					boost::unique_lock<boost::mutex> lock(mutex());
					if(!_first_complete_dependency)
					{
						if(dependency->ready() || dependency->get_exception_ptr())
						{
							_first_complete_dependency = dependency;
							_dependencies.clear();
							emit_signal = true;
							condition().notify_all();
						}
					}
				}
				if(emit_signal)
				{
					this->_updateSignal();
					_waiter_callbacks.close_posting();
					throw boost::signals2::expired_slot();
				}
			}
			bool nolock_ready() const
			{
				if(!_first_complete_dependency) return false;
				return _first_complete_dependency->ready();
			}

			mutable std::vector<boost::shared_ptr<future_body_untyped_base> > _dependencies;
			mutable waiter_event_queue _waiter_callbacks;
		};

		template<typename T>
		class future_select_body: public future_select_body<void>,
			public future_body_base<T>
		{
			typedef boost::shared_ptr<future_body_base<T> > future_body_dependency_type;
		public:
			typedef future_body_untyped_base::update_signal_type update_signal_type;

			template<typename InputIterator>
			static boost::shared_ptr<future_select_body> create(InputIterator future_begin, InputIterator future_end)
			{
				boost::shared_ptr<future_select_body> new_object(new future_select_body);
				new_object->init(new_object, future_begin, future_end);
				return new_object;
			}

			virtual const T& getValue() const
			{
				boost::shared_ptr<future_body_base<T> > typed_dependency;
				{
					boost::unique_lock<boost::mutex> lock(mutex());
					condition().wait(lock, boost::bind(&future_select_body<void>::check_if_complete, this, &lock));
					typed_dependency =
						boost::dynamic_pointer_cast<future_body_base<T> >(_first_complete_dependency);
				}
				return typed_dependency->getValue();
			}
			virtual void setValue(const T &value)
			{
				BOOST_ASSERT(false);
			}
		private:
			future_select_body()
			{}
#ifdef BOOST_MSVC
#pragma warning( suppress : 4250 ) // suppress msvc 9 warning
#endif
		};
	} // namespace detail

	template<typename T>
		class future_selector
	{
	public:
		typedef future<T> value_type;
		typedef std::size_t size_type;
		typedef std::ptrdiff_t difference_type;

		future_selector(): _selector_body(detail::future_selector_body<T>::create())
		{}
		future_selector(const future_selector &other):
			_selector_body(other._selector_body->clone())
		{}

		~future_selector()
		{
			_selector_body->detach();
		}

		future_selector& operator=(const future_selector &rhs)
		{
			if(&rhs == this) return *this;
			future_selector temp(rhs);
			swap(temp);
			return *this;
		}
		future<T> selected() const
		{
			return _selector_body->selected();
		}
		void pop_selected()
		{
			_selector_body->pop_selected();
		}
		void push(const future<T> &f)
		{
			_selector_body->push(f);
		}
		template<typename Converter, typename ExceptionHandler, typename U>
		void push(const Converter &converter, const ExceptionHandler &exception_handler, const future<U> &f)
		{
			future<T> converted_f = future_combining_barrier<T>(converter, exception_handler, f);
			push(converted_f);
		}
		difference_type size() const
		{
			return _selector_body->size();
		}
		void reset()
		{
			future_selector temp;
			swap(temp);
		}
		void swap(future_selector &other)
		{
			using std::swap;
			swap(_selector_body, other._selector_body);
		}
	private:
		boost::shared_ptr<detail::future_selector_body<T> > _selector_body;
	};

	template<typename T>
	void swap(future_selector<T> &a, future_selector<T> &b)
	{
		a.swap(b);
	}

	template<typename InputIterator>
	typename std::iterator_traits<InputIterator>::value_type future_select_range(InputIterator future_begin, InputIterator future_end)
	{
		typedef typename std::iterator_traits<InputIterator>::value_type future_type;
		if(future_begin == future_end) return future_type();
		typedef detail::future_select_body<typename future_type::value_type> body_type;
		future_type result = detail::create_future<typename future_type::value_type>(
			body_type::create(future_begin, future_end));
		return result;
	}
}

#ifndef POET_FUTURE_SELECT_MAX_ARGS
#define POET_FUTURE_SELECT_MAX_ARGS 10
#endif

#define BOOST_PP_ITERATION_LIMITS (2, POET_FUTURE_SELECT_MAX_ARGS)
#define BOOST_PP_FILENAME_1 <poet/detail/future_select_template.hpp>
#include BOOST_PP_ITERATE()

#endif // _POET_FUTURE_WAITS_HPP

max_stars_repo_name: fmhess/libpoet

max_issues_repo_name: fmhess/libpoet

max_forks_repo_name: fmhess/libpoet