text:
#include <iostream>
#include <array>
#include <bluetoe/service.hpp>

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

#include "test_attribute_access.hpp"
#include "hexdump.hpp"

namespace blued = bluetoe::details;

BOOST_AUTO_TEST_SUITE( implicit_characteristic_uuid )

    static std::int64_t x_pos;
    static std::int64_t y_pos;
    static std::int64_t z_pos;

    using auto_uuid_service = bluetoe::service<
        bluetoe::characteristic<
            bluetoe::bind_characteristic_value< decltype( x_pos ), &x_pos >
        >,
        bluetoe::characteristic<
            bluetoe::bind_characteristic_value< decltype( y_pos ), &y_pos >
        >,
        bluetoe::characteristic<
            bluetoe::bind_characteristic_value< decltype( z_pos ), &z_pos >
        >,

        bluetoe::service_uuid< 0xD7E08435, 0xA713, 0x4A51, 0x92DB, 0x004A8C63B6F8 >

        // if this is changed to a 16 bit UUID, it should not compile
        //bluetoe::service_uuid16< 0x0815 >
    >;

    BOOST_FIXTURE_TEST_CASE( check_expected_number_of_attributes, auto_uuid_service )
    {
        BOOST_CHECK_EQUAL( int( number_of_attributes ), 7 );
    }

    BOOST_FIXTURE_TEST_CASE( three_different_uuids_in_characteristic_value_declaration, auto_uuid_service )
    {
        static const std::array< std::uint8_t, 16u > service_uuid = { {
            0xf8, 0xb6, 0x63, 0x8c, 0x4a, 0x00, 0xdb, 0x92,
            0x51, 0x4a, 0x13, 0xa7, 0x35, 0x84, 0xe0, 0xd7
        } };

        static const std::size_t attribute_indices[] = { 1, 3, 5 };

        for ( int attribute_index = 0; attribute_index != sizeof( attribute_indices ) / sizeof( attribute_indices[ 0 ] ); ++attribute_index )
        {
             // the expected UUID is the service uuid, with the lsb xored by the characteristic index
            auto expected_char_uuid = service_uuid;
            expected_char_uuid[ 0 ] ^= attribute_index +1;

            std::uint8_t uuid[ 16 ] = { 0 };

            auto read = blued::attribute_access_arguments::read( uuid, 3 );
            auto attr = attribute_at< std::tuple<>, 0, std::tuple< auto_uuid_service >, bluetoe::server< auto_uuid_service > >( attribute_indices[ attribute_index ] );

            auto result = attr.access( read, attribute_indices[ attribute_index ] );
            BOOST_CHECK( result == blued::attribute_access_result::success );

            BOOST_CHECK_EQUAL_COLLECTIONS( std::begin( expected_char_uuid ), std::end( expected_char_uuid ), std::begin( uuid ), std::begin( uuid ) + read.buffer_size );
        }
    }

BOOST_AUTO_TEST_SUITE_END()

ext: cpp

max_stars_repo_name: TorstenRobitzki/bluetoe

max_issues_repo_name: TorstenRobitzki/bluetoe

max_forks_repo_name: TorstenRobitzki/bluetoe


text:
#include "asioext/detail/url_parser.hpp"

#include "asioext/error.hpp"

#include <boost/test/unit_test.hpp>

ASIOEXT_NS_BEGIN

BOOST_AUTO_TEST_SUITE(asioext_url_parser)

using asioext::detail::parsed_url;
using asioext::detail::parse_url;

parsed_url parse_url(std::string_view input, asioext::error_code& ec)
{
  parsed_url p;
  parse_url(input.data(), input.data() + input.size(), p, ec);
  return p;
}

BOOST_AUTO_TEST_CASE(simple)
{
  parsed_url p;
  asioext::error_code ec;

  p = parse_url("http://example.com/home/tim/test.txt", ec);
  BOOST_REQUIRE_MESSAGE(!ec, "ec:" << ec);
  BOOST_CHECK_EQUAL(p.scheme, "http");
  BOOST_CHECK_EQUAL(p.userinfo, "");
  BOOST_CHECK_EQUAL(p.host, "example.com");
  BOOST_CHECK_EQUAL(p.port, "");
  BOOST_CHECK_EQUAL(p.port_value, 0);
  BOOST_CHECK_EQUAL(p.path, "/home/tim/test.txt");
  BOOST_CHECK_EQUAL(p.query, "");
  BOOST_CHECK_EQUAL(p.fragment, "");

  p = parse_url("http://example.com:80/home/tim/test.txt", ec);
  BOOST_REQUIRE_MESSAGE(!ec, "ec:" << ec);
  BOOST_CHECK_EQUAL(p.scheme, "http");
  BOOST_CHECK_EQUAL(p.userinfo, "");
  BOOST_CHECK_EQUAL(p.host, "example.com");
  BOOST_CHECK_EQUAL(p.port, "80");
  BOOST_CHECK_EQUAL(p.port_value, 80);
  BOOST_CHECK_EQUAL(p.path, "/home/tim/test.txt");
  BOOST_CHECK_EQUAL(p.query, "");
  BOOST_CHECK_EQUAL(p.fragment, "");
}

BOOST_AUTO_TEST_CASE(simple_invalid)
{
  parsed_url p;
  asioext::error_code ec;

  (void)parse_url("h__p://example.com/home/tim/test.txt", ec);
  BOOST_CHECK(ec == url_error::invalid_character);

  (void)parse_url("http://example.com/ho me/tim/test.txt", ec);
  BOOST_CHECK(ec == url_error::invalid_character);
}

BOOST_AUTO_TEST_CASE(simple_with_userinfo)
{
  parsed_url p;
  asioext::error_code ec;

  p = parse_url("http://@example.com/home/tim/test.txt", ec);
  BOOST_REQUIRE_MESSAGE(!ec, "ec:" << ec);
  BOOST_CHECK_EQUAL(p.scheme, "http");
  BOOST_CHECK_EQUAL(p.userinfo, "");
  BOOST_CHECK_EQUAL(p.host, "example.com");
  BOOST_CHECK_EQUAL(p.port, "");
  BOOST_CHECK_EQUAL(p.port_value, 0);
  BOOST_CHECK_EQUAL(p.path, "/home/tim/test.txt");
  BOOST_CHECK_EQUAL(p.query, "");
  BOOST_CHECK_EQUAL(p.fragment, "");

  p = parse_url("http://test:test!$&'()*+,;=1@example.com:80/home/tim/test.txt", ec);
  BOOST_REQUIRE_MESSAGE(!ec, "ec:" << ec);
  BOOST_CHECK_EQUAL(p.scheme, "http");
  BOOST_CHECK_EQUAL(p.userinfo, "test:test!$&'()*+,;=1");
  BOOST_CHECK_EQUAL(p.host, "example.com");
  BOOST_CHECK_EQUAL(p.port, "80");
  BOOST_CHECK_EQUAL(p.port_value, 80);
  BOOST_CHECK_EQUAL(p.path, "/home/tim/test.txt");
  BOOST_CHECK_EQUAL(p.query, "");
  BOOST_CHECK_EQUAL(p.fragment, "");
}

BOOST_AUTO_TEST_CASE(special)
{
  parsed_url p;
  asioext::error_code ec;

  p = parse_url("file:///home/tim/test.txt", ec);
  BOOST_REQUIRE_MESSAGE(!ec, "ec:" << ec);
  BOOST_CHECK_EQUAL(p.scheme, "file");
  BOOST_CHECK_EQUAL(p.userinfo, "");
  BOOST_CHECK_EQUAL(p.host, "");
  BOOST_CHECK_EQUAL(p.port, "");
  BOOST_CHECK_EQUAL(p.port_value, 0);
  BOOST_CHECK_EQUAL(p.path, "/home/tim/test.txt");
  BOOST_CHECK_EQUAL(p.query, "");
  BOOST_CHECK_EQUAL(p.fragment, "");

  p = parse_url("file:/home/tim/test.txt", ec);
  BOOST_REQUIRE_MESSAGE(!ec, "ec:" << ec);
  BOOST_CHECK_EQUAL(p.scheme, "file");
  BOOST_CHECK_EQUAL(p.userinfo, "");
  BOOST_CHECK_EQUAL(p.host, "");
  BOOST_CHECK_EQUAL(p.port, "");
  BOOST_CHECK_EQUAL(p.port_value, 0);
  BOOST_CHECK_EQUAL(p.path, "/home/tim/test.txt");
  BOOST_CHECK_EQUAL(p.query, "");
  BOOST_CHECK_EQUAL(p.fragment, "");

  p = parse_url("javascript:alert(1)", ec);
  BOOST_REQUIRE_MESSAGE(!ec, "ec:" << ec);
  BOOST_CHECK_EQUAL(p.scheme, "javascript");
  BOOST_CHECK_EQUAL(p.userinfo, "");
  BOOST_CHECK_EQUAL(p.host, "");
  BOOST_CHECK_EQUAL(p.port, "");
  BOOST_CHECK_EQUAL(p.port_value, 0);
  BOOST_CHECK_EQUAL(p.path, "alert(1)");
  BOOST_CHECK_EQUAL(p.query, "");
  BOOST_CHECK_EQUAL(p.fragment, "");
}

BOOST_AUTO_TEST_SUITE_END()

ASIOEXT_NS_END


text:
#pragma once
#include "golos_tester.hpp"
#include <boost/algorithm/string/replace.hpp>

namespace eosio { namespace testing {

using mvo = fc::mutable_variant_object;
using action_result = base_tester::action_result;

// allows to use ' quotes instead of ", but will break if ' used not as quote
inline fc::variant json_str_to_obj(std::string s) {
    return fc::json::from_string(boost::replace_all_copy(s, "'", "\""));
}

inline account_name user_name(size_t n) {
    string ret_str("user");
    while (n) {
        constexpr auto q = 'z' - 'a' + 1;
        ret_str += std::string(1, 'a' + n % q);
        n /= q;
    }
    return string_to_name(ret_str.c_str());
};

struct base_contract_api {
    using signers_t = std::vector<account_name>;
protected:
    uint32_t billed_cpu_time_us = base_tester::DEFAULT_BILLED_CPU_TIME_US;
    uint64_t billed_ram_bytes = base_tester::DEFAULT_BILLED_RAM_BYTES;
public:
    golos_tester* _tester;
    name _code;

    base_contract_api(golos_tester* tester, name code): _tester(tester), _code(code) {}

    base_tester::action_result push_msig(action_name name, signers_t signers, const variant_object& data) {
        std::vector<permission_level> perms{signers.size()};
        std::transform(signers.begin(), signers.end(), perms.begin(), [](const auto& s){
            return permission_level{s, config::active_name};
        });
        return _tester->push_action_msig_tx(_code, name, perms, signers, data, false); // NOTE: doesn't produce block
    }

    base_tester::action_result push_msig(action_name name, std::vector<permission_level> perms, signers_t signers,
        const variant_object& data
    ) {
        return _tester->push_action_msig_tx(_code, name, perms, signers, data);
    }

    variant get_struct(uint64_t scope, name tbl, uint64_t id, const string& name) const {
        return _tester->get_chaindb_struct(_code, scope, tbl, id, name);
    }

    variant get_singleton(uint64_t scope, name tbl, const string& name) const {
        return _tester->get_chaindb_singleton(_code, scope, tbl, name);
    }

    virtual mvo args() {
        return mvo();
    }

    void set_billed(uint32_t cpu_time_us, uint64_t ram_bytes) {
        billed_cpu_time_us = cpu_time_us;
        billed_ram_bytes   = ram_bytes;
    }

    action_result push(action_name name, account_name signer, const variant_object& data) {
        try {
            signed_transaction trx;
            vector<permission_level> auths;

            auths.push_back( permission_level{signer, config::active_name} );

            trx.actions.emplace_back( _tester->get_action( _code, name, auths, data ) );
            _tester->set_transaction_headers( trx, _tester->DEFAULT_EXPIRATION_DELTA, 0 );
            for (const auto& auth : auths) {
                trx.sign( _tester->get_private_key( auth.actor, auth.permission.to_string() ), _tester->control->get_chain_id() );
            }

            _tester->push_transaction(trx, fc::time_point::maximum(), billed_cpu_time_us, billed_ram_bytes);

        } catch (const fc::exception& ex) {
            edump((ex.to_detail_string()));
            return _tester->error(ex.top_message());
        }
        return _tester->success();
    }

};

} }

ext: hpp


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

#include <boost/python.hpp>
#include <boost/python/raw_function.hpp>
#include <boost/python/detail/api_placeholder.hpp>

namespace boost { namespace python {

namespace detail {

  template <class F>
  struct raw_constructor_dispatcher
  {
      raw_constructor_dispatcher(F f)
     : f(make_constructor(f)) {}

      PyObject* operator()(PyObject* args, PyObject* keywords)
      {
          borrowed_reference_t* ra = borrowed_reference(args);
          object a(ra);
          return incref(
              object(
                  f(
                      object(a[0])
                    , object(a.slice(1, len(a)))
                    , keywords ? dict(borrowed_reference(keywords)) : dict()
                  )
              ).ptr()
          );
      }

   private:
      object f;
  };

} // namespace detail

template <class F>
object raw_constructor(F f, std::size_t min_args = 0)
{
    return detail::make_raw_function(
        objects::py_function(
            detail::raw_constructor_dispatcher<F>(f)
          , mpl::vector2<void, object>()
          , min_args+1
          , (std::numeric_limits<unsigned>::max)()
        )
    );
}

}} // namespace boost::python

max_stars_repo_name: zahangircse/copperhead

max_issues_repo_name: zahangircse/copperhead

max_forks_repo_name: zahangircse/copperhead


text:
/*
 * Copyright 2016 Klemens D. Morgenstern
 *
 * Distributed under the Boost Software License, Version 1.0.
 * See http://www.boost.org/LICENSE_1_0.txt
 */

#ifndef BOOST_WINAPI_ENVIRONMENT_HPP_INCLUDED_
#define BOOST_WINAPI_ENVIRONMENT_HPP_INCLUDED_

#include <boost/winapi/basic_types.hpp>

#ifdef BOOST_HAS_PRAGMA_ONCE
#pragma once
#endif

#if BOOST_WINAPI_PARTITION_DESKTOP || BOOST_WINAPI_PARTITION_SYSTEM

#include <boost/winapi/detail/header.hpp>

#if defined(GetEnvironmentStrings)
// Unlike most of the WinAPI, GetEnvironmentStrings is a real function and GetEnvironmentStringsA is a macro.
// In UNICODE builds, GetEnvironmentStrings is also defined as a macro that redirects to GetEnvironmentStringsW,
// and the narrow character version become inaccessible. Facepalm.
#if defined(_MSC_VER) || defined(__GNUC__)
#pragma push_macro("GetEnvironmentStrings")
#endif
#undef GetEnvironmentStrings
#define BOOST_WINAPI_DETAIL_GET_ENVIRONMENT_STRINGS_UNDEFINED
#endif // defined(GetEnvironmentStrings)

#if !defined( BOOST_USE_WINDOWS_H )
extern "C" {
#if !defined( BOOST_NO_ANSI_APIS )
BOOST_WINAPI_IMPORT boost::winapi::LPSTR_ BOOST_WINAPI_WINAPI_CC GetEnvironmentStrings();
BOOST_WINAPI_IMPORT boost::winapi::BOOL_ BOOST_WINAPI_WINAPI_CC FreeEnvironmentStringsA(boost::winapi::LPSTR_);

BOOST_WINAPI_IMPORT boost::winapi::DWORD_ BOOST_WINAPI_WINAPI_CC GetEnvironmentVariableA(
    boost::winapi::LPCSTR_ lpName,
    boost::winapi::LPSTR_ lpBuffer,
    boost::winapi::DWORD_ nSize
);

BOOST_WINAPI_IMPORT boost::winapi::BOOL_ BOOST_WINAPI_WINAPI_CC SetEnvironmentVariableA(
    boost::winapi::LPCSTR_ lpName,
    boost::winapi::LPCSTR_ lpValue
);
#endif // !defined( BOOST_NO_ANSI_APIS )

BOOST_WINAPI_IMPORT boost::winapi::LPWSTR_ BOOST_WINAPI_WINAPI_CC GetEnvironmentStringsW();
BOOST_WINAPI_IMPORT boost::winapi::BOOL_ BOOST_WINAPI_WINAPI_CC FreeEnvironmentStringsW(boost::winapi::LPWSTR_);

BOOST_WINAPI_IMPORT boost::winapi::DWORD_ BOOST_WINAPI_WINAPI_CC GetEnvironmentVariableW(
    boost::winapi::LPCWSTR_ lpName,
    boost::winapi::LPWSTR_ lpBuffer,
    boost::winapi::DWORD_ nSize
);

BOOST_WINAPI_IMPORT boost::winapi::BOOL_ BOOST_WINAPI_WINAPI_CC SetEnvironmentVariableW(
    boost::winapi::LPCWSTR_ lpName,
    boost::winapi::LPCWSTR_ lpValue
);
} // extern "C"
#endif // !defined( BOOST_USE_WINDOWS_H )

namespace boost {
namespace winapi {

#if !defined( BOOST_NO_ANSI_APIS )
using ::GetEnvironmentStrings;
using ::FreeEnvironmentStringsA;
using ::GetEnvironmentVariableA;
using ::SetEnvironmentVariableA;
#endif // !defined( BOOST_NO_ANSI_APIS )

using ::GetEnvironmentStringsW;
using ::FreeEnvironmentStringsW;
using ::GetEnvironmentVariableW;
using ::SetEnvironmentVariableW;

template< typename Char >
Char* get_environment_strings();

#if !defined( BOOST_NO_ANSI_APIS )

template< >
BOOST_FORCEINLINE char* get_environment_strings< char >()
{
    return GetEnvironmentStrings();
}

BOOST_FORCEINLINE BOOL_ free_environment_strings(LPSTR_ p)
{
    return FreeEnvironmentStringsA(p);
}

BOOST_FORCEINLINE DWORD_ get_environment_variable(LPCSTR_ name, LPSTR_ buffer, DWORD_ size)
{
    return GetEnvironmentVariableA(name, buffer, size);
}

BOOST_FORCEINLINE BOOL_ set_environment_variable(LPCSTR_ name, LPCSTR_ value)
{
    return SetEnvironmentVariableA(name, value);
}

#endif // !defined( BOOST_NO_ANSI_APIS )

template< >
BOOST_FORCEINLINE wchar_t* get_environment_strings< wchar_t >()
{
    return GetEnvironmentStringsW();
}

BOOST_FORCEINLINE BOOL_ free_environment_strings(LPWSTR_ p)
{
    return FreeEnvironmentStringsW(p);
}

BOOST_FORCEINLINE DWORD_ get_environment_variable(LPCWSTR_ name, LPWSTR_ buffer, DWORD_ size)
{
    return GetEnvironmentVariableW(name, buffer, size);
}

BOOST_FORCEINLINE BOOL_ set_environment_variable(LPCWSTR_ name, LPCWSTR_ value)
{
    return SetEnvironmentVariableW(name, value);
}

} // namespace winapi
} // namespace boost

#if defined(BOOST_WINAPI_DETAIL_GET_ENVIRONMENT_STRINGS_UNDEFINED)
#if defined(_MSC_VER) || defined(__GNUC__)
#pragma pop_macro("GetEnvironmentStrings")
#elif defined(UNICODE)
#define GetEnvironmentStrings GetEnvironmentStringsW
#endif
#undef BOOST_WINAPI_DETAIL_GET_ENVIRONMENT_STRINGS_UNDEFINED
#endif // defined(BOOST_WINAPI_DETAIL_GET_ENVIRONMENT_STRINGS_UNDEFINED)

#include <boost/winapi/detail/footer.hpp>

#endif // BOOST_WINAPI_PARTITION_DESKTOP || BOOST_WINAPI_PARTITION_SYSTEM

#endif // BOOST_WINAPI_ENVIRONMENT_HPP_INCLUDED_

max_stars_repo_name: kindlychung/mediasoup-sfu-cpp

max_issues_repo_name: kindlychung/mediasoup-sfu-cpp

max_forks_repo_name: kindlychung/mediasoup-sfu-cpp


text:
/******************************
      Author: Joel Veness
        Date: 2011
******************************/

#include "cts.hpp"
#include "fastmath.hpp"

#include <vector>
#include <cassert>
#include <stack>
#include <iostream>
#include <cmath>

// boost includes
#include <boost/utility.hpp>

// do we use discounting with the KT-estimator?
static const bool UseDiscounting = true;
static const count_t Gamma       = count_t(0.02);
static const count_t Discount    = count_t(1.0) - Gamma;
static const count_t KT_Alpha = 0.0625f;
static const count_t KT_Alpha2 = KT_Alpha + KT_Alpha;

// initialise weight for switching model
static const double SwitchPrior        = 0.925;

// precompute some commonly used logarithms
static const double log_switch_prior   = std::log(SwitchPrior);
static const double log_kt_prior       = std::log(1.0 - SwitchPrior);

// do we use unique path pruning?
static const bool UseUniquePathPruning       = true;
static const bool StrictModePathPruning      = true;

// do we use fast numerical approximations
static const bool UseFastLog         = true;
static const bool UseFastExp         = true;
static const bool UseFastJacobianLog = true;

/* compute a natural logarithm */
inline double ctsLog(double x) {
    return UseFastLog ? fast_log(x) : std::log(x);
}

/* compute an exponential */
inline double ctsExp(double x) {
    return UseFastExp ? fast_exp(x) : std::exp(x);
}

/* given log(x) and log(y), compute log(x+y). uses the following identity:
   log(x + y) = log(x) + log(1 + y/x) = log(x) + log(1+exp(log(y)-log(x))) */
inline double ctsLogAdd(double log_x, double log_y) {

    if (UseFastJacobianLog) {

        if (log_x < log_y) {
            return fast_jacoblog(log_y - log_x) + log_x;
        } else {
            return fast_jacoblog(log_x - log_y) + log_y;
        }

    } else {
        if (log_x < log_y) {
            return std::log(1.0 + std::exp(log_y - log_x)) + log_x;
        } else {
            return std::log(1.0 + std::exp(log_x - log_y)) + log_y;
        }
    }
}

/* display an SNode */
std::ostream &operator<<(std::ostream &o, const SNode &sn) {

    o << "(est: " << sn.m_log_prob_est
      << ", weighted: " << sn.m_log_prob_weighted
      << ", b: " << sn.m_log_b
      << ", s: " << sn.m_log_s
      << ", counts: " << sn.m_count[0] << "/" << sn.m_count[1]
      << ", pidx: " << sn.m_pruned_idx
      << ", children: " << sn.m_child[0] << "/" << sn.m_child[1]
      << ")";

    return o;
}

/* create a new switching node */
SNode::SNode(int depth) :
    m_log_prob_est(0.0),
    m_log_prob_weighted(0.0),
    m_log_b(log_kt_prior),
    m_log_s(log_switch_prior),
    m_pruned_idx(-1)
{
    m_count[0] = 0;    m_count[1] = 0;
    m_child[0] = NULL; m_child[1] = NULL;
}

/* create a new switching node from a pruned node */
SNode::SNode(const SNode &rhs, int pindx) :
    m_log_prob_est(rhs.m_log_prob_est),
    m_log_prob_weighted(rhs.m_log_prob_weighted),
    m_log_b(rhs.m_log_b),
    m_log_s(rhs.m_log_s),
    m_pruned_idx(pindx)
{
    m_count[0] = rhs.m_count[0];
    m_count[1] = rhs.m_count[1];
    m_child[0] = NULL;
    m_child[1] = NULL;
}

/* process a new binary symbol, with switching rate alpha, and blend 1-2*alpha */
void SNode::update(bit_t b, double log_alpha, double log_blend, double log_split_mul) {

    // update the KT estimate and counts
    double log_est_mul = logKTMul(b);
    m_log_prob_est += log_est_mul;
    if (UseDiscounting) {
        m_count[0] *= Discount;
        m_count[1] *= Discount;
    }
    m_count[b]++;

    if (isLeaf()) {

        if (m_pruned_idx >= 0) {
            // if we have pruned, we know weighted_pr == estimated_pr
            m_log_prob_weighted = logProbEstimated();
            m_log_b = ctsLogAdd(log_alpha + m_log_prob_weighted, log_blend + m_log_b + log_est_mul);
            m_log_s = ctsLogAdd(log_alpha + m_log_prob_weighted, log_blend + m_log_s + log_est_mul);
        } else {
            m_log_prob_weighted = logProbEstimated();
        }

        return;
    }

    m_log_prob_weighted = ctsLogAdd(m_log_b + log_est_mul, m_log_s + log_split_mul);
    m_log_b = ctsLogAdd(log_alpha + m_log_prob_weighted, log_blend + m_log_b + log_est_mul);
    m_log_s = ctsLogAdd(log_alpha + m_log_prob_weighted, log_blend + m_log_s + log_split_mul);
}

/* compute the result of an update call non-destructively */
double SNode::updateNonDestructive(bit_t b, double c_weighted, double c_weighted_old) const {

    // compute the KT estimate
    double log_est_mul = logKTMul(b);
    double log_prob_est = m_log_prob_est;
    log_prob_est += log_est_mul;

    if (isLeaf()) return log_prob_est;

    double log_split_mul = c_weighted - c_weighted_old;
    return ctsLogAdd(m_log_b + log_est_mul, m_log_s + log_split_mul);
}

/* is the current node a leaf node? */
bool SNode::isLeaf() const {

    return child(0) == NULL && child(1) == NULL;
}

/* Krichevski-Trofimov estimated log probability accessor */
weight_t SNode::logProbEstimated() const {

    return m_log_prob_est;
}

/* logarithmic weighted probability estimate accessor */
weight_t SNode::logProbWeighted() const {
    return m_log_prob_weighted;
}

/* child corresponding to a particular symbol */
const SNode *SNode::child(bit_t b) const {

    return m_child[b];
}

/* the number of times this context been visited */
count_t SNode::visits() const {

    return m_count[0] + m_count[1];
}

/* compute the logarithm of the KT-estimator update multiplier */
inline double SNode::logKTMul(bit_t b) const {

    count_t kt_mul_numer = m_count[b] + KT_Alpha;
    count_t kt_mul_denom = m_count[0] + m_count[1] + KT_Alpha2;

    return ctsLog(kt_mul_numer / kt_mul_denom);
}

/* number of descendents of a node in the context tree */
size_t SNode::size() const {

    size_t rval = 1;
    rval += child(0) ? child(0)->size() : 0;
    rval += child(1) ? child(1)->size() : 0;
    return rval;
}

/* determine whether two contexts are identical */
bool SwitchingTree::contextsEqual(const context_t &lhs, const context_t &rhs) {

    assert(lhs.size() == rhs.size());

    for (size_t i=0; i < lhs.size(); i++) {
        if (lhs[i] != rhs[i]) return false;
    }

    return true;
}

/* create (if necessary) all of the nodes in the current context */
void SwitchingTree::createNodesInCurrentContext(const context_t &context) {

    SNode **ctn = &m_root;

    if (!UseUniquePathPruning) {

        for (size_t i = 0; i < context.size(); i++) {
            ctn = &((*ctn)->m_child[context[i]]);
            if (*ctn == NULL) {
                void *p = m_ctnode_pool.malloc();
                assert(p != NULL);  // TODO: make more robust
                *ctn = new (p) SNode(static_cast<int>(i));
            }
        }
        return;
    }

    // unique path pruning - only create nodes that are needed!
    for (size_t i = 0; i < context.size(); i++) {

        SNode *n = *ctn;
        // if we encountered a node with pruning, restore the statistics
        if (n->m_pruned_idx >= 0) {

            // get the pruned context
            getContext(m_history, m_pcontext, n->m_pruned_idx);

            // strict unique path pruning check: if contexts are identical,
            // don't create _any_ more new nodes!
            if (StrictModePathPruning && contextsEqual(m_context, m_pcontext)) return;

            // now expand the old context out till it is unique again,
            // copying in the old relevant information
            SNode **pctn = ctn;
            int pidx = n->m_pruned_idx;
            for (size_t j=i; j < m_pcontext.size(); j++) {

                (*pctn)->m_pruned_idx = -1;

                pctn = &((*pctn)->m_child[m_pcontext[j]]);
                void *p = m_ctnode_pool.malloc();
                assert(p != NULL);  // TODO: make more robust
                *pctn = new (p) SNode(*n, j == m_pcontext.size()-1 ? -1 : pidx);

                if (m_pcontext[j] != context[j]) break;
            }
        }

        // create new node
        ctn = &((*ctn)->m_child[context[i]]);
        if (*ctn == NULL) {
            void *p = m_ctnode_pool.malloc();
            assert(p != NULL);  // TODO: make more robust
            *ctn = new (p) SNode(static_cast<int>(i));
            if (i+1 < m_context.size())
                (*ctn)->m_pruned_idx = static_cast<int>(m_history.size());
            break;
        }
    }
}

/* create a context tree of specified maximum depth and size */
SwitchingTree::SwitchingTree(history_t &history, size_t depth, int phase/*=-1*/) :
    m_ctnode_pool(sizeof(SNode)),
    m_root(new (m_ctnode_pool.malloc()) SNode(0)),
    m_phase(phase),
    m_depth(depth),
    m_history(history),
    m_prob_cache(-1)
{
}

/* delete the context tree */
SwitchingTree::~SwitchingTree(void) {
    deleteCT(m_root);
}

/* recursively deletes the nodes in a context tree */
void SwitchingTree::deleteCT(SNode *n) {

    if (n == NULL) return;

    if (n->m_child[0] != NULL) deleteCT(n->m_child[0]);
    if (n->m_child[1] != NULL) deleteCT(n->m_child[1]);

    m_ctnode_pool.free(n);
}

/* compute the current binary context */
void SwitchingTree::getContext(const history_t &h, context_t &context, int idx /* = -1 */) {

    size_t offset = idx < 0 ? h.size() : size_t(idx);
    context.clear();

    for (size_t i=0; i < m_depth; ++i) {
        context.push_back(h[offset-i-1]);
    }
}

/* computes the context, creates relevant nodes and determine the path to update */
void SwitchingTree::makeContextAndPath() {

    // compute the current context
    getContext(m_history, m_context);

    // 1. create new nodes in the context tree (if necessary)
    createNodesInCurrentContext(m_context);

    // 2. walk down the tree to the relevant leaf, saving the path as we go
    m_path.clear(); m_log_old_weights.clear();
    SNode *ctn = m_root;
    m_log_old_weights.push_back(m_root->logProbWeighted());
    m_path.push_back(m_root); // add the empty context

    for (size_t i = 0; i < m_context.size(); i++) {
        ctn = ctn->m_child[m_context[i]];
        if (ctn == NULL) break;
        m_log_old_weights.push_back(ctn->logProbWeighted());
        m_path.push_back(ctn);
    }
}

/* compute the switching rate for a given time t */
double SwitchingTree::switchRate(size_t t) const {

    return 1.0 / double(t - m_depth + 3);
}

/* updates the context tree with a single bit */
void SwitchingTree::update(bit_t b) {

    // avoid recomputing context and path if prob() just called
    if (m_prob_cache != static_cast<int>(m_history.size())) makeContextAndPath();

    // 3. update the probability estimates from the leaf node back up to the root
    double alpha = switchRate(m_history.size());

    double log_alpha = ctsLog(alpha);
    double log_blend = ctsLog(1.0 - 2.0*alpha);
    double log_split_mul = 0.0;

    SNode **sn = &m_path[m_path.size()-1];
    SNode *snc = NULL;
    size_t c = m_path.size()-1;

    while (!m_path.empty()) {
        (*sn)->update(b, log_alpha, log_blend, log_split_mul);
        log_split_mul = (*sn)->logProbWeighted() - m_log_old_weights[c];
        snc = *sn;
        sn--;
        c--;
        m_path.pop_back();
    }

    // 4. update the history
    m_history.push_back(b != 0);
}

/* the probability of seeing a particular symbol next */
double SwitchingTree::prob(bit_t b) {

    double before = logBlockProbability();

    makeContextAndPath();

    // remember for later so we can avoid calling makeContextAndPath
    // if update() is called immediately after this
    m_prob_cache = static_cast<int>(m_history.size());

     // 3. compute the probability estimates from the leaf node back up to the root
    double c_weighted = 0.0, c_old_weighted = 0.0;
    SNode *snc = NULL;
    SNode **sn = &m_path[m_path.size()-1];
    size_t c = 0;
    while (c < m_path.size()) {
        c_weighted = (*sn)->updateNonDestructive(b, c_weighted, c_old_weighted);
        c_old_weighted =  m_log_old_weights[m_path.size()-c-1];
        snc = *sn;
        sn--;
        c++;
    }

    return ctsExp(c_weighted - before);
}

/* the depth of the context tree */
size_t SwitchingTree::depth() const {

    return m_depth;
}

/* number of nodes in the context tree */
size_t SwitchingTree::size(void) const {

    return m_root->size();
}

/* recover the memory used by a node */
void SwitchingTree::reclaimMemory(SNode *n) {

    m_ctnode_pool.free(n);
}

/* the logarithm of the block probability of the whole sequence */
double SwitchingTree::logBlockProbability(void) const {

    return m_root->logProbWeighted();
}

max_stars_repo_name: mgbellemare/SkipCTS

max_issues_repo_name: GitHubBeinner/SkipCTS

max_forks_repo_name: GitHubBeinner/SkipCTS


text: #include <boost/fusion/include/single_view.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
// Copyright 2021 Tinkerrer

#include "RockDatabase.h"

#include <boost/log/trivial.hpp>
#include <iostream>

#include "../PicoSHA2/picosha2.h"

RockDatabase::RockDatabase(const std::string& database) { open(database); }

void RockDatabase::open(const std::string& database) {
  // Получаем вектор имен Column Families
  std::vector<std::string> column_families_names;
  DB::ListColumnFamilies(DBOptions(), database, &column_families_names);

  // Создаем вектор параметров открытия каждой Column Families
  std::vector<ColumnFamilyDescriptor> column_families;
  for (auto& col_name : column_families_names) {
    column_families.push_back(
        ColumnFamilyDescriptor(col_name, ColumnFamilyOptions()));
  }

  // Открываем текущие DB
  Options options;
  options.create_if_missing = true;

  Status s = DB::Open(options, database, column_families, &handles, &db);

  // Выводим лог об ошибке

  printLog(s, "database open status");
}

void RockDatabase::print() {
  for (const auto& handle : handles) {
    Iterator* iterator = db->NewIterator(ReadOptions(), handle);
    std::cout << handle->GetName() << std::endl;
    for (iterator->SeekToFirst(); iterator->Valid(); iterator->Next()) {
      std::cout << iterator->key().ToString() << ": "
                << iterator->value().ToString() << std::endl;
    }
    delete iterator;
    std::cout << "=============================\n";
  }
}

void RockDatabase::close() {
  Status s;
  for (auto& handle : handles) {
    s = db->DestroyColumnFamilyHandle(handle);
    printLog(s, "destroying handle");
  }
  s = db->Close();
  printLog(s, "database closing status");
  delete db;
}

void RockDatabase::copy_hashed(RockDatabase& db_to_paste) {
  Status s;

  for (auto& handle : db_to_paste.handles) {
    // Система не позволяет сделать drop для default column, поэтому приходится
    // обходить этот запрет
    if (handle->GetName() == "default") {
      continue;
    }
    s = db_to_paste.db->DropColumnFamily(handle);
    printLog(s, "dropping column family \"" + handle->GetName() + "\" status");
  }

  db_to_paste.handles.resize(handles.size());

  for (size_t i = 0; i < handles.size(); ++i) {
    if (db_to_paste.handles[i]) {
      continue;
    }
    s = db_to_paste.db->CreateColumnFamily(
        ColumnFamilyOptions(), handles[i]->GetName(), &db_to_paste.handles[i]);
    printLog(s,
             "creating column family \"" + handles[i]->GetName() + "\" status");
  }

  for (size_t i = 0; i < handles.size(); ++i) {
    Iterator* base_iterator = db->NewIterator(ReadOptions(), handles[i]);
    for (base_iterator->SeekToFirst(); base_iterator->Valid();
         base_iterator->Next()) {
      // PicoSHA2 time
      std::string hash_hex_str;
      picosha2::hash256_hex_string(
          base_iterator->key().ToString() + base_iterator->value().ToString(),
          hash_hex_str);
      s = db_to_paste.db->Put(WriteOptions(), db_to_paste.handles[i],
                              base_iterator->key(), hash_hex_str);
      printLog(s, "adding element: \nkey: " + base_iterator->key().ToString() +
                      "\tvalue: " + hash_hex_str + "\nstatus");
    }
    delete base_iterator;
  }
}

RockDatabase::~RockDatabase() { close(); }

void RockDatabase::printLog(const Status& s, const std::string& message) {
  if (!s.ok()) {
    BOOST_LOG_TRIVIAL(error) << message << " : " << s.ToString();
    return;
  }
  BOOST_LOG_TRIVIAL(info) << message << " : " << s.ToString();
}

max_stars_repo_name: Tinkerrer/RocksDb-hashing-database

max_issues_repo_name: Tinkerrer/RocksDb-hashing-database

max_forks_repo_name: Tinkerrer/RocksDb-hashing-database


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

#include "qt/passion/subscription/subscriptionwidget.h"
#include "qt/passion/subscription/ui_subscriptionwidget.h"
#include "qt/passion/qtutils.h"
#include "qt/passion/subscription/subrow.h"
#include "qt/passion/subscription/subsite.h"
#include "qt/passion/mninfodialog.h"
#include "qt/passion/guitransactionsutils.h"
#include "qt/passion/masternodewizarddialog.h"
#include "qt/passion/optionbutton.h"
#include "activemasternode.h"
#include "clientmodel.h"
#include "guiutil.h"
#include "init.h"
#include "optionsmodel.h"
#include "masternode-sync.h"
#include "masternodeconfig.h"
#include "masternodeman.h"
#include "sync.h"
#include "wallet/wallet.h"
#include "walletmodel.h"
#include "askpassphrasedialog.h"
#include "util.h"
#include <boost/filesystem.hpp>
#include <iostream>
#include <fstream>
#include <QNetworkRequest>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QByteArray>
#include <QJsonObject>
#include <QString>
#include <QUrl>
#include <QUrlQuery>
#include <QJsonDocument>
#include <QUrl>
#include <QtCore>
#include <QDesktopServices>
#include <QCryptographicHash>

#define DECORATION_SIZE 65
#define NUM_ITEMS 3

class SubHolder : public FurListRow<QWidget*>
{
public:
    SubHolder();

    explicit SubHolder(bool _isLightTheme) : FurListRow(), isLightTheme(_isLightTheme){}

    SubRow* createHolder(int pos) override{
        if(!cachedRow) cachedRow = new SubRow();
        return cachedRow;
    }

    void init(QWidget* holder,const QModelIndex &index, bool isHovered, bool isSelected) const override{
        SubRow* row = static_cast<SubRow*>(holder);
        QString domain = index.sibling(index.row(), SubscriptionModel::DOMAIN).data(Qt::DisplayRole).toString();
        QString key = index.sibling(index.row(), SubscriptionModel::KEY).data(Qt::DisplayRole).toString();
        QString paymentaddress = index.sibling(index.row(), SubscriptionModel::ADDRESS).data(Qt::DisplayRole).toString();
        QString expire = index.sibling(index.row(), SubscriptionModel::EXPIRE).data(Qt::DisplayRole).toString();
        QString status = index.sibling(index.row(), SubscriptionModel::STATUS).data(Qt::DisplayRole).toString();
        QString sitefee = index.sibling(index.row(), SubscriptionModel::SITEFEE).data(Qt::DisplayRole).toString();
        QString registeraddress = index.sibling(index.row(), SubscriptionModel::REGISTERADDRESS).data(Qt::DisplayRole).toString();
        QString registeraddressbalance = index.sibling(index.row(), SubscriptionModel::REGISTERADDRESSBALANCE).data(Qt::DisplayRole).toString();
        row->updateView(domain, key, paymentaddress, sitefee,registeraddress,registeraddressbalance, expire, status);

    }

    QColor rectColor(bool isHovered, bool isSelected) override{
        return getRowColor(isLightTheme, isHovered, isSelected);
    }

    ~SubHolder() override{}

    bool isLightTheme;
    SubRow* cachedRow = nullptr;
};

SubscriptionWidget::SubscriptionWidget(PassionGUI *parent) :
    PWidget(parent),
    ui(new Ui::SubscriptionWidget)
{
    ui->setupUi(this);

    delegate = new FurAbstractListItemDelegate(
            DECORATION_SIZE,
            new SubHolder(isLightTheme()),
            this
    );
    //mnModel = new MNModel(this);
    subscriptionModel = new SubscriptionModel(this);
    coinControl = new CCoinControl();
    this->setStyleSheet(parent->styleSheet());

    /* Containers */
    setCssProperty(ui->left, "container");
    ui->left->setContentsMargins(0,20,0,20);
    setCssProperty(ui->right, "container-right");
    ui->right->setContentsMargins(20,20,20,20);
    ui->right->setVisible(false);

    /* Light Font */
    QFont fontLight;
    fontLight.setWeight(QFont::Light);

    /* Title */
    ui->labelTitle->setText(tr("Website Subscription System"));
    setCssTitleScreen(ui->labelTitle);
    ui->labelTitle->setFont(fontLight);

    ui->labelSubtitle1->setText(tr("PASSION provides a one-click subscription system where you can register and pay with one click."));
    setCssSubtitleScreen(ui->labelSubtitle1);

    setCssProperty(ui->lblDomain, "text-list-title1");
    initCssEditLine(ui->txtDomainInput);
    ui->txtDebug->setVisible(false);
    //setCssProperty(ui->txtDomainInput, "edit-primary-multi-book");
    setCssBtnSecondary(ui->btnPay);
    setCssBtnSecondary(ui->btnRegister);
    ui->btnPay->setVisible(false);

    /* Options */
    ui->btnAbout->setTitleClassAndText("btn-title-grey", "What is a Masternode?");
    ui->btnAbout->setSubTitleClassAndText("text-subtitle", "FAQ explaining what Masternodes are");
    ui->btnAboutController->setTitleClassAndText("btn-title-grey", "What is a Controller?");
    ui->btnAboutController->setSubTitleClassAndText("text-subtitle", "FAQ explaining what is a Masternode Controller");

    setCssProperty(ui->listSites, "container");
    ui->listSites->setItemDelegate(delegate);
    ui->listSites->setIconSize(QSize(DECORATION_SIZE, DECORATION_SIZE));
    ui->listSites->setMinimumHeight(NUM_ITEMS * (DECORATION_SIZE + 2));
    ui->listSites->setAttribute(Qt::WA_MacShowFocusRect, false);
    ui->listSites->setSelectionBehavior(QAbstractItemView::SelectRows);

    connect(ui->btnRegister, SIGNAL(clicked()), this, SLOT(onRegisterClicked()));
    connect(ui->btnPay, SIGNAL(clicked()), this, SLOT(onPayClicked()));
    connect(ui->listSites, SIGNAL(clicked(QModelIndex)), this, SLOT(onMNClicked(QModelIndex)));
}

void SubscriptionWidget::showEvent(QShowEvent *event){
    if (subscriptionModel) subscriptionModel->updateMNList();
    if(!timer) {
        timer = new QTimer(this);
        connect(timer, &QTimer::timeout, [this]() {subscriptionModel->updateMNList();});
    }
    timer->start(30000);
}

void SubscriptionWidget::hideEvent(QHideEvent *event){
    if(timer) timer->stop();
}

void SubscriptionWidget::loadWalletModel(){
    if(walletModel) {
        ui->listSites->setModel(subscriptionModel);
        ui->listSites->setModelColumn(0);
        subscriptionModel->setWallet(this->walletModel);
        updateListState();
    }
}

void SubscriptionWidget::updateListState() {
    if (subscriptionModel->rowCount() > 0) {
        ui->listSites->setVisible(true);
    } else {
        ui->listSites->setVisible(false);
    }
}

void SubscriptionWidget::onMNClicked(const QModelIndex &index){
    ui->listSites->setCurrentIndex(index);
    QRect rect = ui->listSites->visualRect(index);
    QPoint pos = rect.topRight();
    pos.setX(pos.x() - (DECORATION_SIZE * 2));
    pos.setY(pos.y() + (DECORATION_SIZE * 1.5));
    if(!this->menu){
        this->menu = new SubscriptionTipMenu(window, this);
        this->menu->setVisitBtnText(tr("Visit"));
        this->menu->setFundBtnText(tr("Fund"));
        this->menu->setPayBtnText(tr("Pay"));
        this->menu->setInfoBtnText(tr("Info"));
        this->menu->setDeleteBtnText(tr("Delete"));
        connect(this->menu, &TooltipMenu::message, this, &AddressesWidget::message);
        connect(this->menu, SIGNAL(onVisitClicked()), this, SLOT(onVisitMNClicked()));
        connect(this->menu, SIGNAL(onFundClicked()), this, SLOT(onFundMNClicked()));
        connect(this->menu, SIGNAL(onDeleteClicked()), this, SLOT(onDeleteMNClicked()));
        connect(this->menu, SIGNAL(onPayClicked()), this, SLOT(onPayMNClicked()));
        connect(this->menu, SIGNAL(onInfoClicked()), this, SLOT(onInfoMNClicked()));
        this->menu->adjustSize();
    }else {
        this->menu->hide();
    }
    this->index = index;
    menu->move(pos);
    menu->show();

    // Back to regular status
    ui->listSites->scrollTo(index);
    ui->listSites->clearSelection();
    ui->listSites->setFocus();
}

void SubscriptionWidget::onVisitMNClicked(){
    QString domain = index.sibling(this->index.row(), SubscriptionModel::DOMAIN).data(Qt::DisplayRole).toString();
    QString key = index.sibling(this->index.row(), SubscriptionModel::KEY).data(Qt::DisplayRole).toString();
    QString sitehash = QCryptographicHash::hash(domain.toUtf8(),QCryptographicHash::Sha256).toHex();
    inform("Site will be opend in the browser");
    QDesktopServices::openUrl(QUrl((domain+"?key=" + key + "&sitehash=" + sitehash), QUrl::TolerantMode));
}
void SubscriptionWidget::onFundMNClicked(){
    inform("Fund clicked");
}
void SubscriptionWidget::onRegisterClicked() {
    RegisterToSite();
}
void SubscriptionWidget::onPayClicked() {
    /*
    int nDisplayUnit = this->walletModel->getOptionsModel()->getDisplayUnit();
    QString destinationAddress = index.sibling(index.row(), SubscriptionModel::ADDRESS).data(Qt::DisplayRole).toString();
    QString registerAddress = index.sibling(index.row(), SubscriptionModel::REGISTERADDRESS).data(Qt::DisplayRole).toString();
    QString domain = "WSS: " + index.sibling(index.row(), SubscriptionModel::DOMAIN).data(Qt::DisplayRole).toString();
    CAmount nSiteFee = index.sibling(index.row(), SubscriptionModel::SITEFEE).data(Qt::DisplayRole).toLongLong() * COIN;
    CCoinControl *cControl = new CCoinControl();
    std::map<QString, std::vector<COutput>> mapCoins;
    if(this->walletModel) {
        CAmount nSum = 0;
        this->walletModel->listCoins(mapCoins);
        for (PAIRTYPE(QString, std::vector<COutput>) coins : mapCoins) {
            QString sWalletAddress = coins.first;
            //if(sWalletAddress == registerAddress) {
            if(!QString::compare(sWalletAddress, registerAddress, Qt::CaseSensitive)) {
                for(const COutput& out: coins.second) {
                    nSum += out.tx->vout[out.i].nValue;
                    COutPoint outpt(out.tx->GetHash(), out.i);
                    cControl->Select(outpt);
                }
            }
        }
        // It is necessary that we can have at least on input from the registered address otherwise it could not be detected that you are wright one
        if(!nSum) {
            inform("No funds at registered address. Do internal funding first");
            return;
        } else if(nSum < nSiteFee) {
            for (PAIRTYPE(QString, std::vector<COutput>) coins : mapCoins) {
                for(const COutput& out: coins.second) {
                    nSum += out.tx->vout[out.i].nValue;
                    COutPoint outpt(out.tx->GetHash(), out.i);
                    cControl->Select(outpt);
                }
                if(nSum > nSiteFee) break;
            }
        }
    }

    cControl->destChange =CBitcoinAddress(registerAddress.toStdString()).Get();
    // const QString& addr, const QString& label, const CAmount& amount, const QString& message
    SendCoinsRecipient sendCoinsRecipient(destinationAddress, domain, nSiteFee, "");
    // Send the 10 tx to one of your address
    QList<SendCoinsRecipient> recipients;
    recipients.append(sendCoinsRecipient);
    WalletModelTransaction currentTransaction(recipients);
    WalletModel::SendCoinsReturn transactionStatus;

    transactionStatus = walletModel->prepareTransaction(currentTransaction,cControl);

    // process prepareStatus and on error generate message shown to user
    processSendCoinsReturn(transactionStatus,BitcoinUnits::formatWithUnit(nDisplayUnit,currentTransaction.getTransactionFee()),true);
    if (transactionStatus.status != WalletModel::OK) {
        inform("Error prepare transaction");
        delete(cControl);
        return;
    }
    transactionStatus = walletModel->sendCoins(currentTransaction);
    // process sendStatus and on error generate message shown to user
    processSendCoinsReturn(transactionStatus);
    if (transactionStatus.status == WalletModel::OK) {
        inform("Transaction Send");
        subscriptionModel->setData(index, QVariant(),Qt::DisplayRole);
    } else {
        inform("Error sending...");
    }
    delete(cControl);
    */
    inform("Pay Clicked...");
}

void SubscriptionWidget::RegisterToSite() {
    /*
    QNetworkRequest request(QUrl("http://btadng.ddns.net:8888/getid.php"));
    QNetworkAccessManager nam;

    QNetworkReply *reply = nam.get(request);
    while (!reply->isFinished())
    {
        qApp->processEvents();
    }
    QByteArray response_data = reply->readAll();
    QJsonDocument json = QJsonDocument::fromJson(response_data);
    reply->deleteLater();
    QJsonObject obj = json.object();

    int expire = obj["expire"].toInt(); // QString::number(expire)
    int time = obj["time"].toInt(); // QString::number(time)

    QString siteurl = ui->txtDomainInput->text();
    QString messageToSign = obj["hash"].toString();
    QString registerAddr =getNewAddress();
    QString signature = signRegisterMessage(registerAddr,messageToSign);
    QString sitehash = QCryptographicHash::hash(siteurl.toUtf8(),QCryptographicHash::Sha256).toHex();

    QUrl serviceUrl = QUrl("http://btadng.ddns.net:8888/register2.php");
    QByteArray postData;
    QUrlQuery query;
    query.addQueryItem("addr",registerAddr);
    query.addQueryItem("hash",messageToSign);
    query.addQueryItem("url",siteurl);
    query.addQueryItem("sig",signature);
    query.addQueryItem("sitehash", sitehash);
    query.addQueryItem("submit","true");

    postData = query.toString(QUrl::FullyEncoded).toUtf8();

    // Call the webservice
    QNetworkAccessManager *networkManager = new QNetworkAccessManager(this);
    QNetworkRequest networkRequest(serviceUrl);
    networkRequest.setHeader(QNetworkRequest::ContentTypeHeader,"application/x-www-form-urlencoded");

    QNetworkReply *reply2 = networkManager->post(networkRequest,postData);
    while (!reply2->isFinished())
    {
        qApp->processEvents();
    }
    QByteArray response_data2 = reply2->readAll();
    QJsonDocument json2 = QJsonDocument::fromJson(response_data2);
    reply->deleteLater();
    QString strJson(json2.toJson(QJsonDocument::Compact));
    ui->txtDebug->document()->setPlainText(strJson);
    QJsonObject obj2 = json2.object();
    if(obj2["status"] == 0) {
        inform("ERROR " +obj2["message"].toString());
    } else {
        QString domain = siteurl;
        QString key = obj2["key"].toString();
        QString paymentaddress = obj2["siteaddr"].toString();
        int sitefee = obj2["sitefee"].toInt();
        int expire = obj["time"].toInt()*0;
        int status = obj2["status"].toInt();
        subscriptionModel->addMn(domain,key,paymentaddress,registerAddr,sitefee,expire,status);
        inform("Site successfully registered");
    }
    */
   inform("Register clicked!");

}
QString SubscriptionWidget::getNewAddress() {
    /*
    try {
        if (!verifyWalletUnlocked()) return nullptr;
        CBitcoinAddress address;
        PairResult r = walletModel->getNewAddress(address, "");
        // Check for validity
        if(!r.result) {
            inform(r.status->c_str());
            return nullptr;
        }
        return QString::fromStdString(address.ToString());
    } catch (const std::runtime_error& error){
        // Error generating address
        inform("Error generating address");
        return nullptr;
    }*/
}
QString SubscriptionWidget::signRegisterMessage(const QString strSignAddress, const QString message) {
    /*
    if (!walletModel) {
        inform(tr("Error: No Wallet Model"));
        return nullptr;
    }
    CBitcoinAddress addr(strSignAddress.toStdString());
    if (!addr.IsValid()) {
        inform(tr("Error: No valid Address"));
        return nullptr;
    }
    CKeyID keyID;
    if (!addr.GetKeyID(keyID)) {
        return nullptr;
    }
    WalletModel::UnlockContext ctx(walletModel->requestUnlock(AskPassphraseDialog::Context::Sign_Message, true));
    if (!ctx.isValid()) {
        return nullptr;
    }

    CKey key;
    if (!pwalletMain->GetKey(keyID, key)) {
        return nullptr;
    }

    CDataStream ss(SER_GETHASH, 0);
    ss << strMessageMagic;
    ss << message.toStdString(); //obj["hash"].toString().toStdString();

    std::vector<unsigned char> vchSig;
    if (!key.SignCompact(Hash(ss.begin(), ss.end()), vchSig)) {
        return nullptr;
    }
    return QString::fromStdString(EncodeBase64(&vchSig[0], vchSig.size()));
    */
   return "";
}

void SubscriptionWidget::onInfoMNClicked(){
    QString destinationAddress = index.sibling(index.row(), SubscriptionModel::ADDRESS).data(Qt::DisplayRole).toString();
    QString registerAddress = index.sibling(index.row(), SubscriptionModel::REGISTERADDRESS).data(Qt::DisplayRole).toString();
    CAmount nSiteFee = index.sibling(index.row(), SubscriptionModel::SITEFEE).data(Qt::DisplayRole).toLongLong() * COIN;
    inform("dest: " + destinationAddress + " : " + registerAddress + " : " + QString::number(nSiteFee/COIN));
}

void SubscriptionWidget::onDeleteMNClicked(){
    subscriptionModel->removeMn(index);
    inform(tr("Site successfully removed"));
}

void SubscriptionWidget::onPayMNClicked(){
    onPayClicked();
}

void SubscriptionWidget::changeTheme(bool isLightTheme, QString& theme){
    static_cast<SubHolder*>(this->delegate->getRowFactory())->isLightTheme = isLightTheme;
}

void SubscriptionWidget::processSendCoinsReturn(const WalletModel::SendCoinsReturn& sendCoinsReturn, const QString& msgArg, bool fPrepare)
{
    /*
    bool fAskForUnlock = false;

    QPair<QString, CClientUIInterface::MessageBoxFlags> msgParams;
    // Default to a warning message, override if error message is needed
    msgParams.second = CClientUIInterface::MSG_WARNING;

    // This comment is specific to SendCoinsDialog usage of WalletModel::SendCoinsReturn.
    // WalletModel::TransactionCommitFailed is used only in WalletModel::sendCoins()
    // all others are used only in WalletModel::prepareTransaction()
    switch (sendCoinsReturn.status) {
        case WalletModel::InvalidAddress:
            msgParams.first = tr("The recipient address is not valid, please recheck.");
            break;
        case WalletModel::InvalidAmount:
            msgParams.first = tr("The amount to pay must be larger than 0.");
            break;
        case WalletModel::AmountExceedsBalance:
            msgParams.first = tr("The amount exceeds your balance.");
            break;
        case WalletModel::AmountWithFeeExceedsBalance:
            msgParams.first = tr("The total exceeds your balance when the %1 transaction fee is included.").arg(msgArg);
            break;
        case WalletModel::DuplicateAddress:
            msgParams.first = tr("Duplicate address found, can only send to each address once per send operation.");
            break;
        case WalletModel::TransactionCreationFailed:
            msgParams.first = tr("Transaction creation failed!");
            msgParams.second = CClientUIInterface::MSG_ERROR;
            break;
        case WalletModel::TransactionCommitFailed:
            msgParams.first = tr("The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.");
            msgParams.second = CClientUIInterface::MSG_ERROR;
            break;
        case WalletModel::AnonymizeOnlyUnlocked:
            // Unlock is only need when the coins are send
            if(!fPrepare)
                fAskForUnlock = true;
            else
                msgParams.first = tr("Error: The wallet was unlocked only to anonymize coins.");
            break;

        case WalletModel::InsaneFee:
            msgParams.first = tr("A fee %1 times higher than %2 per kB is considered an insanely high fee.").arg(10000).arg(BitcoinUnits::formatWithUnit(walletModel->getOptionsModel()->getDisplayUnit(), ::minRelayTxFee.GetFeePerK()));
            break;
            // included to prevent a compiler warning.
        case WalletModel::OK:
        default:
            return;
    }

    // Unlock wallet if it wasn't fully unlocked already
    if(fAskForUnlock) {
        walletModel->requestUnlock(AskPassphraseDialog::Context::Unlock_Full, false);
        if(walletModel->getEncryptionStatus () != WalletModel::Unlocked) {
            msgParams.first = tr("Error: The wallet was unlocked only to anonymize coins. Unlock canceled.");
        }
        else {
            // Wallet unlocked
            return;
        }
    }
    inform(msgParams.first);*/
}
SubscriptionWidget::~SubscriptionWidget()
{
    delete ui;
}

max_stars_repo_name: PassionCash/PassionCashCoin

max_issues_repo_name: PassionCash/PassionCashCoin

max_forks_repo_name: PassionCash/PassionCashCoin


text:
#ifndef STAN_MATH_PRIM_MAT_PROB_MATRIX_NORMAL_PREC_LOG_HPP
#define STAN_MATH_PRIM_MAT_PROB_MATRIX_NORMAL_PREC_LOG_HPP

#include <stan/math/prim/meta.hpp>
#include <stan/math/prim/mat/fun/Eigen.hpp>
#include <stan/math/prim/mat/prob/matrix_normal_prec_lpdf.hpp>
#include <boost/math/tools/promotion.hpp>

namespace stan {
namespace math {
/**
 * The log of the matrix normal density for the given y, mu, Sigma and D
 * where Sigma and D are given as precision matrices, not covariance
 * matrices.
 *
 * @deprecated use matrix_normal_prec_lpdf
 *
 * @param y An mxn matrix.
 * @param Mu The mean matrix.
 * @param Sigma The mxm inverse covariance matrix (i.e., the precision
 *   matrix) of the rows of y.
 * @param D The nxn inverse covariance matrix (i.e., the precision
 *   matrix) of the columns of y.
 * @return The log of the matrix normal density.
 * @throw std::domain_error if Sigma or D are not square, not symmetric,
 * or not semi-positive definite.
 * @tparam T_y Type of scalar.
 * @tparam T_Mu Type of location.
 * @tparam T_Sigma Type of Sigma.
 * @tparam T_D Type of D.
 */
template <bool propto, typename T_y, typename T_Mu, typename T_Sigma,
          typename T_D>
return_type_t<T_y, T_Mu, T_Sigma, T_D> matrix_normal_prec_log(
    const Eigen::Matrix<T_y, Eigen::Dynamic, Eigen::Dynamic>& y,
    const Eigen::Matrix<T_Mu, Eigen::Dynamic, Eigen::Dynamic>& Mu,
    const Eigen::Matrix<T_Sigma, Eigen::Dynamic, Eigen::Dynamic>& Sigma,
    const Eigen::Matrix<T_D, Eigen::Dynamic, Eigen::Dynamic>& D) {
  return matrix_normal_prec_lpdf<propto, T_y, T_Mu, T_Sigma, T_D>(y, Mu, Sigma,
                                                                  D);
}

/**
 * @deprecated use matrix_normal_prec_lpdf
 */
template <typename T_y, typename T_Mu, typename T_Sigma, typename T_D>
return_type_t<T_y, T_Mu, T_Sigma, T_D> matrix_normal_prec_log(
    const Eigen::Matrix<T_y, Eigen::Dynamic, Eigen::Dynamic>& y,
    const Eigen::Matrix<T_Mu, Eigen::Dynamic, Eigen::Dynamic>& Mu,
    const Eigen::Matrix<T_Sigma, Eigen::Dynamic, Eigen::Dynamic>& Sigma,
    const Eigen::Matrix<T_D, Eigen::Dynamic, Eigen::Dynamic>& D) {
  return matrix_normal_prec_lpdf<T_y, T_Mu, T_Sigma, T_D>(y, Mu, Sigma, D);
}

}  // namespace math
}  // namespace stan
#endif

max_stars_repo_name: PhilClemson/math

max_issues_repo_name: PhilClemson/math

max_forks_repo_name: alashworth/stan-monorepo


text:
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8
// basic_xml_archive.cpp:

// (C) Copyright 2002 Robert Ramey - http://www.rrsd.com .
// Use, modification and distribution is subject to the Boost Software
// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

//  See http://www.boost.org for updates, documentation, and revision history.

#define BOOST_ARCHIVE_SOURCE
#include <boost/archive/basic_xml_archive.hpp>

namespace boost {
namespace archive {

BOOST_SYMBOL_VISIBLE const char *
BOOST_ARCHIVE_XML_OBJECT_ID(){
    return "object_id";
}
BOOST_SYMBOL_VISIBLE const char *
BOOST_ARCHIVE_XML_OBJECT_REFERENCE(){
    return "object_id_reference";
}
BOOST_SYMBOL_VISIBLE const char *
BOOST_ARCHIVE_XML_CLASS_ID(){
    return "class_id";
}
BOOST_SYMBOL_VISIBLE const char *
BOOST_ARCHIVE_XML_CLASS_ID_REFERENCE(){
    return "class_id_reference";
}
BOOST_SYMBOL_VISIBLE const char *
BOOST_ARCHIVE_XML_CLASS_NAME(){
    return "class_name";
}
BOOST_SYMBOL_VISIBLE const char *
BOOST_ARCHIVE_XML_TRACKING(){
    return "tracking_level";
}
BOOST_SYMBOL_VISIBLE const char *
BOOST_ARCHIVE_XML_VERSION(){
    return "version";
}
BOOST_SYMBOL_VISIBLE const char *
BOOST_ARCHIVE_XML_SIGNATURE(){
    return "signature";
}

}// namespace archive
}// namespace boost

max_stars_repo_name: SunguckLee/real-mongodb

max_issues_repo_name: SunguckLee/real-mongodb

max_forks_repo_name: SunguckLee/real-mongodb


text:
/*=============================================================================
    Copyright (c) 2001-2009 Joel de Guzman
    Copyright (c) 2001-2009 Hartmut Kaiser

    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)
==============================================================================*/
#if !defined(BOOST_SPIRIT_ATTRIBUTES_JANUARY_29_2007_0954AM)
#define BOOST_SPIRIT_ATTRIBUTES_JANUARY_29_2007_0954AM

#if defined(_MSC_VER)
#pragma once
#endif

#include <boost/spirit/home/support/unused.hpp>
#include <boost/spirit/home/support/has_semantic_action.hpp>
#include <boost/spirit/home/support/attributes_fwd.hpp>
#include <boost/spirit/home/support/detail/as_variant.hpp>
#include <boost/optional/optional.hpp>
#include <boost/fusion/include/transform.hpp>
#include <boost/fusion/include/filter_if.hpp>
#include <boost/fusion/include/as_vector.hpp>
#include <boost/fusion/include/push_front.hpp>
#include <boost/fusion/include/pop_front.hpp>
#include <boost/fusion/include/is_sequence.hpp>
#include <boost/fusion/include/for_each.hpp>
#include <boost/utility/value_init.hpp>
#include <boost/type_traits/is_same.hpp>
#include <boost/type_traits/is_convertible.hpp>
#include <boost/mpl/eval_if.hpp>
#include <boost/mpl/end.hpp>
#include <boost/mpl/find_if.hpp>
#include <boost/mpl/identity.hpp>
#include <boost/variant.hpp>
#include <vector>
#include <utility>

///////////////////////////////////////////////////////////////////////////////
namespace boost { namespace spirit { namespace traits
{
    ///////////////////////////////////////////////////////////////////////////
    // This file deals with attribute related functions and metafunctions
    // including generalized attribute transformation utilities for Spirit
    // components.
    ///////////////////////////////////////////////////////////////////////////

    template <typename T>
    struct not_is_variant
      : mpl::true_
    {};

    template <BOOST_VARIANT_ENUM_PARAMS(typename T)>
    struct not_is_variant<boost::variant<BOOST_VARIANT_ENUM_PARAMS(T)> >
      : mpl::false_
    {};

    template <typename T>
    struct not_is_variant<boost::optional<T> >
      : not_is_variant<T>
    {};

    // we treat every type as if it where the variant (as this meta function is
    // invoked for variant types only)
    template <typename T>
    struct variant_type
      : mpl::identity<T>
    {};

    template <typename T>
    struct variant_type<boost::optional<T> >
      : variant_type<T>
    {};

    ///////////////////////////////////////////////////////////////////////////
    template <typename T>
    struct not_is_optional
      : mpl::true_
    {};

    template <typename T>
    struct not_is_optional<boost::optional<T> >
      : mpl::false_
    {};

    ///////////////////////////////////////////////////////////////////////////
    // attribute_of
    //
    // Get the component's attribute
    ///////////////////////////////////////////////////////////////////////////
    template <typename Component
      , typename Context = unused_type, typename Iterator = unused_type>
    struct attribute_of
    {
        typedef typename Component::template
            attribute<Context, Iterator>::type type;
    };

    ///////////////////////////////////////////////////////////////////////////
    // attribute_not_unused
    //
    // An mpl metafunction class that determines whether a component's
    // attribute is not unused.
    ///////////////////////////////////////////////////////////////////////////
    template <typename Context, typename Iterator = unused_type>
    struct attribute_not_unused
    {
        template <typename Component>
        struct apply
          : not_is_unused<typename
                attribute_of<Component, Context, Iterator>::type>
        {};
    };

    ///////////////////////////////////////////////////////////////////////////
    // pass_attribute
    //
    // Determines how we pass attributes to semantic actions. This
    // may be specialized. By default, all attributes are wrapped in
    // a fusion sequence, because the attribute has to be treated as being
    // a single value in any case (even if it actually already is a fusion
    // sequence in its own).
    ///////////////////////////////////////////////////////////////////////////
    template <typename Component, typename Attribute, typename Enable/* = void*/>
    struct pass_attribute
    {
        typedef fusion::vector1<Attribute&> type;
    };

    ///////////////////////////////////////////////////////////////////////////
    // Subclass a pass_attribute specialization from this to wrap
    // the attribute in a tuple only IFF it is not already a fusion tuple.
    ///////////////////////////////////////////////////////////////////////////
    template <typename Attribute, typename Force = mpl::false_>
    struct wrap_if_not_tuple
      : mpl::if_<
            fusion::traits::is_sequence<Attribute>
          , Attribute&, fusion::vector1<Attribute&> >
    {};

    template <typename Attribute>
    struct wrap_if_not_tuple<Attribute, mpl::true_>
    {
        typedef fusion::vector1<Attribute&> type;
    };

    template <>
    struct wrap_if_not_tuple<unused_type, mpl::false_>
    {
        typedef unused_type type;
    };

    template <>
    struct wrap_if_not_tuple<unused_type const, mpl::false_>
    {
        typedef unused_type type;
    };

    ///////////////////////////////////////////////////////////////////////////
    // build_optional
    //
    // Build a boost::optional from T. Return unused_type if T is unused_type.
    ///////////////////////////////////////////////////////////////////////////
    template <typename T>
    struct build_optional
    {
        typedef optional<T> type;
    };

    template <>
    struct build_optional<unused_type>
    {
        typedef unused_type type;
    };

    ///////////////////////////////////////////////////////////////////////////
    // build_std_vector
    //
    // Build a std::vector from T. Return unused_type if T is unused_type.
    ///////////////////////////////////////////////////////////////////////////
    template <typename T>
    struct build_std_vector
    {
        typedef std::vector<T> type;
    };

    template <>
    struct build_std_vector<unused_type>
    {
        typedef unused_type type;
    };

    ///////////////////////////////////////////////////////////////////////////
    // filter_unused_attributes
    //
    // Remove unused_types from a sequence
    ///////////////////////////////////////////////////////////////////////////

    // Compute the list of all *used* attributes of sub-components
    // (filter all unused attributes from the list)
    template <typename Sequence>
    struct filter_unused_attributes
      : fusion::result_of::filter_if<Sequence, not_is_unused<mpl::_> >
    {};

    ///////////////////////////////////////////////////////////////////////////
    // build_fusion_vector
    //
    // Build a fusion vector from a fusion sequence. All unused attributes
    // are filtered out. If the result is empty after the removal of unused
    // types, return unused_type. If the input sequence is an unused_type,
    // also return unused_type.
    ///////////////////////////////////////////////////////////////////////////
    template <typename Sequence>
    struct build_fusion_vector
    {
        // Remove all unused attributes
        typedef typename
            filter_unused_attributes<Sequence>::type
        filtered_attributes;

        // Build a fusion vector from a fusion sequence (Sequence),
        // But *only if* the sequence is not empty. i.e. if the
        // sequence is empty, our result will be unused_type.

        typedef typename
            mpl::eval_if<
                fusion::result_of::empty<filtered_attributes>
              , mpl::identity<unused_type>
              , fusion::result_of::as_vector<filtered_attributes>
            >::type
        type;
    };

    template <>
    struct build_fusion_vector<unused_type>
    {
        typedef unused_type type;
    };

    ///////////////////////////////////////////////////////////////////////////
    // build_attribute_sequence
    //
    // Build a fusion sequence attribute sequence from a sequence of
    // components. Transform<T>::type is called on each element.
    ///////////////////////////////////////////////////////////////////////////
    template <typename Sequence, typename Context
      , template <typename T> class Transform, typename Iterator = unused_type>
    struct build_attribute_sequence
    {
        struct element_attribute
        {
            template <typename T>
            struct result;

            template <typename F, typename Element>
            struct result<F(Element)>
            {
                typedef typename
                    Transform<
                        typename attribute_of<Element, Context, Iterator>::type
                    >::type
                type;
            };

            // never called, but needed for decltype-based result_of (C++0x)
            template <typename Element>
            typename result<element_attribute(Element)>::type
            operator()(Element&) const;
        };

        // Compute the list of attributes of all sub-components
        typedef typename
            fusion::result_of::transform<Sequence, element_attribute>::type
        type;
    };

    ///////////////////////////////////////////////////////////////////////////
    // has_no_unused
    //
    // Test if there are no unused attributes in Sequence
    ///////////////////////////////////////////////////////////////////////////
    template <typename Sequence>
    struct has_no_unused
      : is_same<
            typename mpl::find_if<Sequence, is_same<mpl::_, unused_type> >::type
          , typename mpl::end<Sequence>::type>
    {};

    namespace detail
    {
        template <typename Sequence, bool no_unused
            , int size = mpl::size<Sequence>::value>
        struct build_collapsed_variant;

        // N element case, no unused
        template <typename Sequence, int size>
        struct build_collapsed_variant<Sequence, true, size>
            : spirit::detail::as_variant<Sequence> {};

        // N element case with unused
        template <typename Sequence, int size>
        struct build_collapsed_variant<Sequence, false, size>
        {
            typedef optional<
                typename spirit::detail::as_variant<
                    typename fusion::result_of::pop_front<Sequence>::type
                >::type
            > type;
        };

        // 1 element case, no unused
        template <typename Sequence>
        struct build_collapsed_variant<Sequence, true, 1>
            : mpl::front<Sequence> {};

        // 1 element case, with unused
        template <typename Sequence>
        struct build_collapsed_variant<Sequence, false, 1>
            : mpl::front<Sequence> {};

        // 2 element case, no unused
        template <typename Sequence>
        struct build_collapsed_variant<Sequence, true, 2>
            : spirit::detail::as_variant<Sequence> {};

        // 2 element case, with unused
        template <typename Sequence>
        struct build_collapsed_variant<Sequence, false, 2>
        {
            typedef optional<
                typename mpl::deref<
                    typename mpl::next<
                        typename mpl::begin<Sequence>::type
                    >::type
                >::type
            >
            type;
        };
    }

    ///////////////////////////////////////////////////////////////////////////
    // build_variant
    //
    // Build a boost::variant from a fusion sequence. build_variant makes sure
    // that 1) all attributes in the variant are unique 2) puts the unused
    // attribute, if there is any, to the front and 3) collapses single element
    // variants, variant<T> to T.
    ///////////////////////////////////////////////////////////////////////////
    template <typename Sequence>
    struct build_variant
    {
        // Remove all unused attributes.
        typedef typename
            filter_unused_attributes<Sequence>::type
        filtered_attributes;

        typedef has_no_unused<Sequence> no_unused;

        // If the original attribute list does not contain any unused
        // attributes, it is used, otherwise a single unused_type is
        // pushed to the front of the list. This is to make sure that if
        // there is an unused_type in the list, it is the first one.
        typedef typename
            mpl::eval_if<
                no_unused,
                mpl::identity<Sequence>,
                fusion::result_of::push_front<filtered_attributes, unused_type>
            >::type
        attribute_sequence;

        // Make sure each of the types occur only once in the type list
        typedef typename
            mpl::fold<
                attribute_sequence, mpl::vector<>,
                mpl::if_<
                    mpl::contains<mpl::_1, mpl::_2>,
                    mpl::_1, mpl::push_back<mpl::_1, mpl::_2>
                >
            >::type
        no_duplicates;

        // If there is only one type in the list of types we strip off the
        // variant. IOTW, collapse single element variants, variant<T> to T.
        // Take note that this also collapses variant<unused_type, T> to T.
        typedef typename
            traits::detail::build_collapsed_variant<
                no_duplicates, no_unused::value>::type
        type;
    };

    ///////////////////////////////////////////////////////////////////////////
    // transform_attribute
    //
    // Sometimes the user needs to transform the attribute types for certain
    // attributes. This template can be used as a customization point, where
    // the user is able specify specific transformation rules for any attribute
    // type.
    //
    // The default attribute transformation (where the exposed attribute type is
    // different from the required transformed attribute type) relies on the
    // convertibility 'exposed type' --> 'transformed type', which has to exist
    // in order to successfully execute the pre transform step.
    ///////////////////////////////////////////////////////////////////////////
    template <typename Exposed, typename Transformed, typename Enable/* = void*/>
    struct transform_attribute
    {
        typedef Transformed type;

        static Transformed pre(Exposed& val) { return Transformed(val); }

        // By default do post transformation only if types are convertible,
        // otherwise we assume no post transform is required (i.e. the user
        // utilizes nview et.al.).
        static void post(Exposed&, Transformed const&, mpl::false_)
        {
        }
        static void post(Exposed& val, Transformed const& attr, mpl::true_)
        {
            assign_to(attr, val);
        }

        static void post(Exposed& val, Transformed const& attr)
        {
            post(val, attr, is_convertible<Transformed, Exposed>());
        }
    };

    template <typename Exposed, typename Transformed>
    struct transform_attribute<Exposed const, Transformed>
    {
        typedef Transformed type;
        static Transformed pre(Exposed const& val) { return Transformed(val); }
        // Karma only, no post() required
    };

    // handle case where no transformation is required as the types are the same
    template <typename Attribute>
    struct transform_attribute<Attribute, Attribute>
    {
        typedef Attribute& type;
        static Attribute& pre(Attribute& val) { return val; }
        static void post(Attribute&, Attribute const&) {}
    };

    template <typename Attribute>
    struct transform_attribute<Attribute const, Attribute>
    {
        typedef Attribute const& type;
        static Attribute const& pre(Attribute const& val) { return val; }
        // Karma only, no post() required
    };

    // reference types need special handling
    template <typename Exposed, typename Transformed>
    struct transform_attribute<Exposed&, Transformed>
      : transform_attribute<Exposed, Transformed>
    {};

    template <typename Attribute>
    struct transform_attribute<Attribute&, Attribute>
    {
        typedef Attribute& type;
        static Attribute& pre(Attribute& val) { return val; }
        static void post(Attribute&, Attribute const&) {}
    };

    template <typename Attribute>
    struct transform_attribute<Attribute const&, Attribute>
      : transform_attribute<Attribute const, Attribute>
    {};

    // unused_type needs some special handling as well
    template <>
    struct transform_attribute<unused_type, unused_type>
    {
        typedef unused_type type;
        static unused_type pre(unused_type) { return unused; }
        static void post(unused_type, unused_type) {}
    };

    template <>
    struct transform_attribute<unused_type const, unused_type>
      : transform_attribute<unused_type, unused_type>
    {};

    template <typename Attribute>
    struct transform_attribute<unused_type, Attribute>
      : transform_attribute<unused_type, unused_type>
    {};

    template <typename Attribute>
    struct transform_attribute<unused_type const, Attribute>
      : transform_attribute<unused_type, unused_type>
    {};

    template <typename Attribute>
    struct transform_attribute<Attribute, unused_type>
      : transform_attribute<unused_type, unused_type>
    {};

    template <typename Attribute>
    struct transform_attribute<Attribute const, unused_type>
      : transform_attribute<unused_type, unused_type>
    {};

    ///////////////////////////////////////////////////////////////////////////
    template <typename Transformed, typename Exposed>
    typename spirit::result_of::pre_transform<Exposed, Transformed>::type
    pre_transform(Exposed& attr BOOST_PROTO_DISABLE_IF_IS_CONST(Exposed))
    {
        return transform_attribute<Exposed, Transformed>::pre(attr);
    }

    template <typename Transformed, typename Exposed>
    typename spirit::result_of::pre_transform<Exposed const, Transformed>::type
    pre_transform(Exposed const& attr)
    {
        return transform_attribute<Exposed const, Transformed>::pre(attr);
    }

    ///////////////////////////////////////////////////////////////////////////
    template <typename Exposed, typename Transformed>
    void post_transform(Exposed& dest, Transformed const& attr)
    {
        return transform_attribute<Exposed, Transformed>::post(dest, attr);
    }

    ///////////////////////////////////////////////////////////////////////////
    // make_attribute
    //
    // All parsers and generators have specific attribute types.
    // Spirit parsers and generators are passed an attribute; these are either
    // references to the expected type, or an unused_type -- to flag that we do
    // not care about the attribute. For semantic actions, however, we need to
    // have a real value to pass to the semantic action. If the client did not
    // provide one, we will have to synthesize the value. This class takes care
    // of that.
    ///////////////////////////////////////////////////////////////////////////
    template <typename Attribute, typename ActualAttribute>
    struct make_attribute
    {
        typedef typename
            mpl::if_<
                is_same<typename remove_const<ActualAttribute>::type, unused_type>
              , typename remove_const<Attribute>::type
              , ActualAttribute&>::type
        type;

        typedef typename
            mpl::if_<
                is_same<typename remove_const<ActualAttribute>::type, unused_type>
              , typename remove_const<Attribute>::type
              , ActualAttribute>::type
        value_type;

        static Attribute call(unused_type)
        {
             // synthesize the attribute/parameter
            return boost::get(value_initialized<Attribute>());
        }

        template <typename T>
        static T& call(T& value)
        {
            return value; // just pass the one provided
        }
    };

    template <typename Attribute, typename ActualAttribute>
    struct make_attribute<Attribute&, ActualAttribute>
      : make_attribute<Attribute, ActualAttribute>
    {};

    template <typename Attribute, typename ActualAttribute>
    struct make_attribute<Attribute const&, ActualAttribute>
      : make_attribute<Attribute, ActualAttribute>
    {};

    template <typename ActualAttribute>
    struct make_attribute<unused_type, ActualAttribute>
    {
        typedef unused_type type;
        typedef unused_type value_type;
        static unused_type call(unused_type)
        {
            return unused;
        }
    };

    ///////////////////////////////////////////////////////////////////////////
    // swap_impl
    //
    // Swap (with proper handling of unused_types)
    ///////////////////////////////////////////////////////////////////////////
    template <typename A, typename B>
    void swap_impl(A& a, B& b)
    {
        A temp = a;
        a = b;
        b = temp;
    }

    template <typename T>
    void swap_impl(T& a, T& b)
    {
        using namespace std;
        swap(a, b);
    }

    template <typename A>
    void swap_impl(A& a, unused_type)
    {
    }

    template <typename A>
    void swap_impl(unused_type, A& a)
    {
    }

    inline void swap_impl(unused_type, unused_type)
    {
    }

    ///////////////////////////////////////////////////////////////////////////
    //  Strips single element fusion vectors into its 'naked'
    //  form: vector<T> --> T
    ///////////////////////////////////////////////////////////////////////////
    template <typename T>
    struct strip_single_element_vector
    {
        typedef T type;
    };

    template <typename T>
    struct strip_single_element_vector<fusion::vector1<T> >
    {
        typedef T type;
    };

    template <typename T>
    struct strip_single_element_vector<fusion::vector<T> >
    {
        typedef T type;
    };

    ///////////////////////////////////////////////////////////////////////////
    // meta function to return whether the argument is a one element fusion
    // sequence
    ///////////////////////////////////////////////////////////////////////////
    template <typename T>
    struct one_element_sequence
      : mpl::false_
    {};

    template <typename T>
    struct one_element_sequence<fusion::vector1<T> >
      : mpl::true_
    {};

    template <typename T>
    struct one_element_sequence<fusion::vector<T> >
      : mpl::true_
    {};

    ///////////////////////////////////////////////////////////////////////////
    // clear
    //
    // Clear data efficiently
    ///////////////////////////////////////////////////////////////////////////
    template <typename T>
    void clear(T& val);

    namespace detail
    {
        // this is used by the variant and fusion sequence dispatch
        struct clear_visitor : static_visitor<>
        {
            template <typename T>
            void operator()(T& val) const
            {
                clear(val);
            }
        };

        // default
        template <typename T>
        void clear_impl2(T& val, mpl::false_)
        {
            val = T();
        }

        // for fusion sequences
        template <typename T>
        void clear_impl2(T& val, mpl::true_)
        {
            fusion::for_each(val, clear_visitor());
        }

        // dispatch default or fusion sequence
        template <typename T>
        void clear_impl(T& val, mpl::false_)
        {
            clear_impl2(val, fusion::traits::is_sequence<T>());
        }

        // STL containers
        template <typename T>
        void clear_impl(T& val, mpl::true_)
        {
            val.clear();
        }
    }

    template <typename T, typename Enable/* = void*/>
    struct clear_value
    {
        static void call(T& val)
        {
            detail::clear_impl(val, typename is_container<T>::type());
        }
    };

    // optionals
    template <typename T>
    struct clear_value<optional<T> >
    {
        static void call(optional<T>& val)
        {
            if (val)
                val = none_t();    // leave optional uninitialized
        }
    };

    // variants
    template <BOOST_VARIANT_ENUM_PARAMS(typename T)>
    struct clear_value<variant<BOOST_VARIANT_ENUM_PARAMS(T)> >
    {
        static void call(variant<BOOST_VARIANT_ENUM_PARAMS(T)>& val)
        {
            apply_visitor(detail::clear_visitor(), val);
        }
    };

    // main dispatch
    template <typename T>
    void clear(T& val)
    {
        clear_value<T>::call(val);
    }

    // for unused
    inline void clear(unused_type)
    {
    }
}}}

///////////////////////////////////////////////////////////////////////////////
namespace boost { namespace spirit { namespace result_of
{
    template <typename Exposed, typename Transformed>
    struct pre_transform
      : traits::transform_attribute<Exposed, Transformed>
    {};
}}}

#endif

max_stars_repo_name: EricBoittier/vina-carb-docker

max_issues_repo_name: EricBoittier/vina-carb-docker

max_forks_repo_name: EricBoittier/vina-carb-docker


text:
//
// Copyright (c) 2016-2019 Vinnie Falco (vinnie dot falco at gmail dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// Official repository: https://github.com/boostorg/beast
//

#ifndef BOOST_BEAST_IMPL_BUFFERED_READ_STREAM_HPP
#define BOOST_BEAST_IMPL_BUFFERED_READ_STREAM_HPP

#include <boost/asio/post.hpp>
#include <boost/beast/core/async_base.hpp>
#include <boost/beast/core/bind_handler.hpp>
#include <boost/beast/core/detail/is_invocable.hpp>
#include <boost/beast/core/error.hpp>
#include <boost/beast/core/read_size.hpp>
#include <boost/beast/core/stream_traits.hpp>
#include <boost/throw_exception.hpp>

namespace boost {
namespace beast {

template <class Stream, class DynamicBuffer>
struct buffered_read_stream<Stream, DynamicBuffer>::ops {

  template <class MutableBufferSequence, class Handler>
  class read_op
      : public async_base<Handler, beast::executor_type<buffered_read_stream>> {
    buffered_read_stream &s_;
    MutableBufferSequence b_;
    int step_ = 0;

  public:
    read_op(read_op &&) = default;
    read_op(read_op const &) = delete;

    template <class Handler_>
    read_op(Handler_ &&h, buffered_read_stream &s,
            MutableBufferSequence const &b)
        : async_base<Handler, beast::executor_type<buffered_read_stream>>(
              std::forward<Handler_>(h), s.get_executor()),
          s_(s), b_(b) {
      (*this)({}, 0);
    }

    void operator()(error_code ec, std::size_t bytes_transferred) {
      // VFALCO TODO Rewrite this using reenter/yield
      switch (step_) {
      case 0:
        if (s_.buffer_.size() == 0) {
          if (s_.capacity_ == 0) {
            // read (unbuffered)
            step_ = 1;
            return s_.next_layer_.async_read_some(b_, std::move(*this));
          }
          // read
          step_ = 2;
          return s_.next_layer_.async_read_some(
              s_.buffer_.prepare(read_size(s_.buffer_, s_.capacity_)),
              std::move(*this));
        }
        step_ = 3;
        return net::post(s_.get_executor(),
                         beast::bind_front_handler(std::move(*this), ec, 0));

      case 1:
        // upcall
        break;

      case 2:
        s_.buffer_.commit(bytes_transferred);
        BOOST_FALLTHROUGH;

      case 3:
        bytes_transferred = net::buffer_copy(b_, s_.buffer_.data());
        s_.buffer_.consume(bytes_transferred);
        break;
      }
      this->complete_now(ec, bytes_transferred);
    }
  };

  struct run_read_op {
    template <class ReadHandler, class Buffers>
    void operator()(ReadHandler &&h, buffered_read_stream *s,
                    Buffers const &b) {
      // If you get an error on the following line it means
      // that your handler does not meet the documented type
      // requirements for the handler.

      static_assert(
          beast::detail::is_invocable<ReadHandler,
                                      void(error_code, std::size_t)>::value,
          "ReadHandler type requirements not met");

      read_op<Buffers, typename std::decay<ReadHandler>::type>(
          std::forward<ReadHandler>(h), *s, b);
    }
  };
};

//------------------------------------------------------------------------------

template <class Stream, class DynamicBuffer>
template <class... Args>
buffered_read_stream<Stream, DynamicBuffer>::buffered_read_stream(
    Args &&... args)
    : next_layer_(std::forward<Args>(args)...) {}

template <class Stream, class DynamicBuffer>
template <class ConstBufferSequence, class WriteHandler>
BOOST_BEAST_ASYNC_RESULT2(WriteHandler)
buffered_read_stream<Stream, DynamicBuffer>::async_write_some(
    ConstBufferSequence const &buffers, WriteHandler &&handler) {
  static_assert(is_async_write_stream<next_layer_type>::value,
                "AsyncWriteStream type requirements not met");
  static_assert(net::is_const_buffer_sequence<ConstBufferSequence>::value,
                "ConstBufferSequence type requirements not met");
  static_assert(
      detail::is_invocable<WriteHandler, void(error_code, std::size_t)>::value,
      "WriteHandler type requirements not met");
  return next_layer_.async_write_some(buffers,
                                      std::forward<WriteHandler>(handler));
}

template <class Stream, class DynamicBuffer>
template <class MutableBufferSequence>
std::size_t buffered_read_stream<Stream, DynamicBuffer>::read_some(
    MutableBufferSequence const &buffers) {
  static_assert(is_sync_read_stream<next_layer_type>::value,
                "SyncReadStream type requirements not met");
  static_assert(net::is_mutable_buffer_sequence<MutableBufferSequence>::value,
                "MutableBufferSequence type requirements not met");
  error_code ec;
  auto n = read_some(buffers, ec);
  if (ec)
    BOOST_THROW_EXCEPTION(system_error{ec});
  return n;
}

template <class Stream, class DynamicBuffer>
template <class MutableBufferSequence>
std::size_t buffered_read_stream<Stream, DynamicBuffer>::read_some(
    MutableBufferSequence const &buffers, error_code &ec) {
  static_assert(is_sync_read_stream<next_layer_type>::value,
                "SyncReadStream type requirements not met");
  static_assert(net::is_mutable_buffer_sequence<MutableBufferSequence>::value,
                "MutableBufferSequence type requirements not met");
  if (buffer_.size() == 0) {
    if (capacity_ == 0)
      return next_layer_.read_some(buffers, ec);
    buffer_.commit(next_layer_.read_some(
        buffer_.prepare(read_size(buffer_, capacity_)), ec));
    if (ec)
      return 0;
  } else {
    ec = {};
  }
  auto bytes_transferred = net::buffer_copy(buffers, buffer_.data());
  buffer_.consume(bytes_transferred);
  return bytes_transferred;
}

template <class Stream, class DynamicBuffer>
template <class MutableBufferSequence, class ReadHandler>
BOOST_BEAST_ASYNC_RESULT2(ReadHandler)
buffered_read_stream<Stream, DynamicBuffer>::async_read_some(
    MutableBufferSequence const &buffers, ReadHandler &&handler) {
  static_assert(is_async_read_stream<next_layer_type>::value,
                "AsyncReadStream type requirements not met");
  static_assert(net::is_mutable_buffer_sequence<MutableBufferSequence>::value,
                "MutableBufferSequence type requirements not met");
  if (buffer_.size() == 0 && capacity_ == 0)
    return next_layer_.async_read_some(buffers,
                                       std::forward<ReadHandler>(handler));
  return net::async_initiate<ReadHandler, void(error_code, std::size_t)>(
      typename ops::run_read_op{}, handler, this, buffers);
}

} // namespace beast
} // namespace boost

#endif

max_stars_repo_name: henrywarhurst/matrix

max_issues_repo_name: henrywarhurst/matrix

max_forks_repo_name: henrywarhurst/matrix


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

    @copyright 2016 NumScale SAS

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

#if defined(DOXYGEN_ONLY)
namespace boost { namespace simd
{

  /*!
    @ingroup group-predicates

    This function object returns @ref True if neither x nor y is @ref Nan and x is not equal to y.

    @par Header <boost/simd/function/is_lessgreater.hpp>

    @par Note

     Using `is_lessgreater(x,y)` is similar to: `(x == x) && (y == y) && (x!= y)`

    @par Decorators

     - std_ can be used to call std::islessgreater

    @par Example:

      @snippet is_lessgreater.cpp is_lessgreater

    @par Possible output:

      @snippet is_lessgreater.txt is_lessgreater

  **/
  as_logical_t<Value> is_lessgreater(Value const& x, Value const& y);
} }
#endif

#include <boost/simd/function/scalar/is_lessgreater.hpp>
#include <boost/simd/function/simd/is_lessgreater.hpp>

#endif

max_stars_repo_name: SylvainCorlay/pythran

max_issues_repo_name: SylvainCorlay/pythran

max_forks_repo_name: SylvainCorlay/pythran