text:
#pragma once

#include <unordered_map>
#include <atomic>
#include <shared_mutex>
#include <functional>
#include <vector>
#include <algorithm>
#include <unordered_set>

#include <boost/noncopyable.hpp>
#include <boost/call_traits.hpp>

#include "random_id_generator.hpp"

namespace pgl {
	template <typename S, typename T>
	auto member_variable_pointer_t_impl(T S::* p) -> T;

	template <typename T>
	using member_variable_pointer_variable_t = decltype(member_variable_pointer_t_impl(std::declval<T>()));

	template <typename IdType, typename S, auto S::* UniqueVariable>
	class unique_variables_container_impl {
		using member_t = member_variable_pointer_variable_t<decltype(UniqueVariable)>;
		using s_param_t = typename boost::call_traits<S>::param_type;
		using id_param_t = typename boost::call_traits<IdType>::param_type;
	protected:
		void add_or_update_variable(id_param_t id, s_param_t data) {
			auto unique_value = get_unique_value(data);
			used_variable_.insert(unique_value);
			id_to_variable_map_.emplace(id, unique_value);
		}

		void remove_variable(id_param_t id, s_param_t data) {
			used_variable_.erase(get_unique_value(data));
			id_to_variable_map_.erase(id);
		}

		// If variable is same with variable of id, consider the variable as unique even if the variable is in used_variables.
		bool is_unique(id_param_t id, s_param_t data) const {
			auto unique_value = get_unique_value(data);
			auto it = id_to_variable_map_.find(id);
			if (it == id_to_variable_map_.end()) { return used_variable_.find(unique_value) == used_variable_.end(); }

			return it->second == unique_value;
		}

		bool is_unique(s_param_t data) const {
			auto unique_value = get_unique_value(data);
			return used_variable_.find(unique_value) == used_variable_.end();
		}

	private:
		std::unordered_map<IdType, member_t> id_to_variable_map_;
		std::unordered_set<member_t> used_variable_;

		static member_t get_unique_value(s_param_t data) { return data.*UniqueVariable; }
	};

	// A container which holds unique member variables.
	template <typename IdType, typename S, auto S::* ... UniqueVariables>
	class unique_variables_container
		final : boost::noncopyable, unique_variables_container_impl<IdType, S, UniqueVariables>... {
		using s_param_t = typename boost::call_traits<S>::param_type;
		using id_param_t = typename boost::call_traits<IdType>::param_type;
	public:
		void add_or_update_variables(id_param_t id, s_param_t data) {
			(unique_variables_container_impl<IdType, S, UniqueVariables>::add_or_update_variable(id, data), ...);
		}

		void remove_variables(id_param_t id, s_param_t data) {
			(unique_variables_container_impl<IdType, S, UniqueVariables>::remove_variable(id, data), ...);
		}

		bool is_unique(id_param_t id, s_param_t data) const {
			return (unique_variables_container_impl<IdType, S, UniqueVariables>::is_unique(id, data) && ... && true);
		}

		bool is_unique(s_param_t data) const {
			return (unique_variables_container_impl<IdType, S, UniqueVariables>::is_unique(data) && ... && true);
		}
	};

	class unique_variable_duplication_error final : public std::runtime_error {
	public:
		unique_variable_duplication_error() : runtime_error("A unique member variable is duplicated.") {};
		using runtime_error::runtime_error;
	};

	// A thread safe container of data
	template <typename Id, typename Data, auto Data::* ... UniqueVariables>
	class thread_safe_data_container final : boost::noncopyable {
	public:
		using id_param_type = typename boost::call_traits<Id>::param_type;
		using data_param_type = typename boost::call_traits<Data>::param_type;

		[[nodiscard]] bool is_data_exist(id_param_type id) const {
			std::shared_lock lock(mutex_);
			return data_map_.find(id) != data_map_.end();
		}

		[[nodiscard]] Data get_data(id_param_type id) const {
			std::shared_lock lock(mutex_);
			return data_map_.at(id).load();
		}

		size_t size() const { return data_map_.size(); }

		// unique_variable_duplication_error will be thrown if unique member variable is duplicated.
		void add_data(id_param_type id, data_param_type data) {
			std::lock_guard lock(mutex_);

			if (!unique_variables_.is_unique(data)) { throw unique_variable_duplication_error(); }

			data_map_.emplace(id, data);
			unique_variables_.add_or_update_variables(id, data);
		}

		// unique_variable_duplication_error will be thrown if unique member variable is duplicated.
		Id assign_id_and_add_data(Data& data,
			std::function<void(Data&, id_param_type)>&& id_setter = [](Data&, id_param_type) {},
			std::function<Id()>&& random_id_generator = generate_random_id<Id>) {
			std::lock_guard lock(mutex_);

			if (!unique_variables_.is_unique(data)) { throw unique_variable_duplication_error(); }

			Id id;
			do { id = random_id_generator(); }
			while (data_map_.find(id) != data_map_.end());
			id_setter(data, id);
			data_map_.emplace(id, data);
			unique_variables_.add_or_update_variables(id, data);
			return id;
		}

		std::vector<Data> get_data(std::function<bool(data_param_type, data_param_type)>&& compare_function,
			std::function<bool(data_param_type)>&& filter_function) const {
			std::vector<Data> data;
			{
				std::shared_lock lock(mutex_);
				data.reserve(data_map_.size());
				for (auto&& pair : data_map_) {
					const auto data_elem = pair.second.load();
					if (filter_function(data_elem)) { data.push_back(data_elem); }
				}
			}
			std::sort(data.begin(), data.end(), compare_function);
			return data;
		}

		std::vector<Data> get_range_data(const size_t start_idx, size_t count,
			std::function<bool(data_param_type, data_param_type)>&& compare_function,
			std::function<bool(data_param_type)>&& filter_function) const {
			std::vector<Data> data = get_data(std::move(compare_function), std::move(filter_function));
			count = std::min(count, data.size() >= start_idx ? data.size() - start_idx : 0);
			std::vector<Data> result(count);
			const auto end_idx_plus_one = start_idx + count;
			for (auto i = start_idx; i < end_idx_plus_one; ++i) { result[i - start_idx] = data[i]; }
			return result;
		}

		// unique_variable_duplication_error will be thrown if unique member variable is duplicated.
		void update_data(id_param_type id, data_param_type data) {
			std::shared_lock lock(mutex_);

			if (!unique_variables_.is_unique(id, data)) { throw unique_variable_duplication_error(); }

			unique_variables_.add_or_update_variables(id, data);
			data_map_.at(id) = data;
		}

		void remove_data(id_param_type id) {
			std::lock_guard lock(mutex_);
			auto it = data_map_.find(id);
			unique_variables_.remove_variables(id, it->second);
			data_map_.erase(it);
		}

	private:
		std::unordered_map<Id, std::atomic<Data>> data_map_;
		unique_variables_container<Id, Data, UniqueVariables...> unique_variables_;
		mutable std::shared_mutex mutex_;
	};
}

max_stars_repo_name: InstytutXR/PlanetaMatchMaker

max_issues_repo_name: InstytutXR/PlanetaMatchMaker

max_forks_repo_name: InstytutXR/PlanetaMatchMaker


text:
#pragma once
#include <Fastor/Fastor.h>

#include <OpenVolumeMesh/Mesh/TetrahedralMesh.hh>
#include <boost/container/static_vector.hpp>
#include <boost/range/algorithm/find.hpp>
#include <boost/range/iterator.hpp>

namespace FeltElements
{
using Mesh = OpenVolumeMesh::GeometricTetrahedralMeshV3d;
using Vtxh = OpenVolumeMesh::VertexHandle;
using Vtx = Mesh::PointT;
template <std::size_t dim>
using Vtxhs = std::array<Vtxh, dim>;
using Cellh = OpenVolumeMesh::CellHandle;
using Scalar = Mesh::PointT::value_type;

namespace Tensor
{
enum
{
	i,
	j,
	k,
	l,
	m,
	n,
	a,
	b
};
namespace Func = Fastor;
using Index = Fastor::FASTOR_INDEX;
template <Index... indices>
using Indices = Fastor::Index<indices...>;
template <Index... indices>
using Idxs = Indices<indices...>;
template <Index... indices>
using Order = Fastor::OIndex<indices...>;

template <typename value_type, Index... indices>
using Base = Fastor::Tensor<value_type, indices...>;

template <Index rows = 3, Index cols = rows>
using Matrix = Base<Scalar, rows, cols>;
template <Index dim = 3>
using Vector = Base<Scalar, dim>;
template <Index... indices>
using Multi = Base<Scalar, indices...>;

template <typename value_type, Index... indices>
using BaseMap = Fastor::TensorMap<value_type, indices...>;
template <Index... indices>
using Map = BaseMap<Scalar, indices...>;
template <Index... indices>
using ConstMap = BaseMap<Scalar const, indices...>;
}  // namespace Tensor

namespace Node
{
static constexpr Tensor::Index dim = 3;

using Pos = Tensor::Vector<dim>;
using Force = Tensor::Vector<dim>;
}  // namespace Node

namespace Element
{
static constexpr Tensor::Index num_nodes = 4;
static constexpr Tensor::Index num_faces = 4;

using Vtxhs = FeltElements::Vtxhs<num_nodes>;
using IsoCoordDerivative = Tensor::Matrix<Node::dim, num_nodes>;
using ShapeDerivative = Tensor::Matrix<num_nodes, Node::dim>;
using SurfaceShapeDerivative = Tensor::Matrix<num_nodes - 1, Node::dim - 1>;
using ShapeDerivativeDeterminant = Tensor::Multi<num_nodes, num_nodes, num_nodes>;
using Elasticity = Tensor::Multi<Node::dim, Node::dim, Node::dim, Node::dim>;
using ShapeCartesianTransform = Tensor::Matrix<4, 4>;
using CartesianDerivative = Tensor::Matrix<Node::dim, num_nodes>;
using Gradient = Tensor::Matrix<Node::dim, Node::dim>;
using SurfaceGradient = Tensor::Matrix<Node::dim, Node::dim - 1>;
using Stress = Gradient;
using Stiffness = Tensor::Multi<num_nodes, Node::dim, num_nodes, Node::dim>;
using NodePositions = Fastor::Tensor<Scalar, num_nodes, Node::dim>;
using Forces = Fastor::Tensor<Scalar, num_nodes, Node::dim>;
using StiffnessResidual = std::tuple<Stiffness, Forces>;
}  // namespace Element

namespace BoundaryElement
{
static constexpr Tensor::Index num_nodes = Element::num_nodes - 1;

using Vtxhs = FeltElements::Vtxhs<num_nodes>;
using VtxhIdxs = std::array<Tensor::Index, BoundaryElement::num_nodes>;
using NodePositions = Tensor::Matrix<num_nodes, Node::dim>;
using Stiffness = Tensor::Multi<num_nodes, Node::dim, num_nodes, Node::dim>;
}  // namespace BoundaryElement

namespace Element
{
template <class T>
using PerFace = boost::container::static_vector<T, Element::num_faces>;
using BoundaryVtxhIdxs = PerFace<BoundaryElement::VtxhIdxs>;
using BoundaryNodePositions = PerFace<BoundaryElement::NodePositions>;
}  // namespace Element

template <typename Index = std::size_t, class Haystack, typename Needle>
constexpr Index index_of(Haystack && haystack, Needle && needle)
{
	auto const & it = boost::range::find(
		std::forward<decltype(haystack)>(haystack), std::forward<decltype(needle)>(needle));
	return static_cast<Index>(std::distance(haystack.begin(), it));
}
}  // namespace FeltElements

ext: hpp

max_stars_repo_name: feltech/FeltElements

max_issues_repo_name: feltech/FeltElements

max_forks_repo_name: feltech/FeltElements


text:
/*******************************************************************************
 *
 * MIT License
 *
 * Copyright (c) 2019 Advanced Micro Devices, Inc.
 *
 * 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 of the 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.
 *
 *******************************************************************************/

#pragma once

#include <miopen/db_path.hpp>
#include <miopen/handle.hpp>
#include <miopen/sqlite_db.hpp>
#if MIOPEN_EMBED_DB
#include <miopen_data.hpp>
#endif
#include <boost/filesystem.hpp>

#include <string>

class rocm_meta_version
{
    int val = Unknown;

    public:
    static constexpr int Unknown = 0, // Unset env.vars read as 0.
        AMDHSA_COv2              = 1, // V2 metadata, https://llvm.org/docs/AMDGPUUsage.html
        AMDHSA_COv2_COv3         = 2, // E.g. ROCm 2.10 supports both.
        AMDHSA_COv3              = 3, // V3 metadata, https://llvm.org/docs/AMDGPUUsage.html
        Default                  = AMDHSA_COv2; // Used when auto-detection fails.

    private:
    static constexpr int End = 4, Begin = Unknown;

    public:
    rocm_meta_version(int v) : val(v) {}
    int getValue() const { return val; }
    bool IsValid() const { return Begin <= val && val < End; }
    bool IsUnknown() const { return val == Unknown; }
    bool IsV2() const { return AMDHSA_COv2 <= val && val <= AMDHSA_COv2_COv3; }
    bool IsV2orV3() const { return AMDHSA_COv2 <= val && val <= AMDHSA_COv3; }
    bool IsV3() const { return AMDHSA_COv2_COv3 <= val && val <= AMDHSA_COv3; }
    bool UseV3() const;
};

namespace miopen {

struct ExecutionContext
{
    // Operation modes & environment
    bool do_search               = false;
    bool save_srch_req           = false;
    bool use_asm_kernels         = false;
    bool use_hip_kernels         = true;
    bool use_opencl_convolutions = true;
    bool use_binaries            = true;
    rocm_meta_version rmv        = rocm_meta_version::Default;
    bool disable_search_enforce  = false;
    // Skip perf-db reads and use the default performance configuration. This is used, for example,
    // to optimize the getWorkspaceSize() calls for speed. This specific optimization is correct
    // because Solvers shall be written so that the required workspace size does not depend on the
    // performance config.
    bool disable_perfdb_access                                                = false;
    bool skip_solutions_that_take_long_time_to_build_and_have_narrow_coverage = false;
    bool use_dynamic_solutions_only                                           = false;

    inline Handle& GetStream() const { return *stream; }
    inline void SetStream(Handle* stream_) { stream = stream_; }

    ExecutionContext() = default;
    ExecutionContext(Handle* stream_) : stream(stream_) {}

    void DetectRocm();
#if MIOPEN_EMBED_DB
    std::string GetPerfDbPathEmbed() const
    {
        static const auto result = [&] {
            boost::filesystem::path pdb_path(GetSystemDbPath());
            std::ostringstream filename;
            // clang-format off
            filename << GetStream().GetDbBasename();
#if MIOPEN_ENABLE_SQLITE
            const std::string ext = ".db";
#else
            const std::string ext = ".cd.pdb.txt";
#endif
            filename << ext;
            // clang-format on
            if(miopen_data().find(filename.str() + ".o") != miopen_data().end())
            {
                MIOPEN_LOG_I("Found exact embedded perf database file");
                return (pdb_path / filename.str()).string();
            }
            else
            {
                MIOPEN_LOG_I2("inexact embedded perf database search");
                const auto db_id        = GetStream().GetTargetProperties().DbId();
                const int real_cu_count = GetStream().GetMaxComputeUnits();
                namespace fs            = boost::filesystem;
                int closest_cu          = std::numeric_limits<int>::max();
                fs::path best_path;
                for(auto const& entry : miopen_data())
                {
                    // string the .o from the filename
                    const auto fname = entry.first.substr(0, entry.first.size() - 2);
                    MIOPEN_LOG_I2("Testing embedded file:" << fname);
                    const auto& filepath = pdb_path / fname;
                    if(filepath.extension() == ext &&
                       fname.rfind(db_id, 0) == 0) // starts with db_id
                    {
                        MIOPEN_LOG_I2("Checking embedded perf db file: " << fname);
                        const auto pos = fname.find('_');
                        int cur_count  = -1;
                        try
                        {
                            if(pos != std::string::npos)
                                cur_count = std::stoi(fname.substr(pos + 1));
                            else
                                cur_count = std::stoi(fname.substr(db_id.length()), nullptr, 16);
                        }
                        catch(const std::exception& e)
                        {
                            MIOPEN_LOG_I2("Unable to infer CU count for file: " << fname << " : "
                                                                                << e.what());
                            continue;
                        }

                        if(abs(cur_count - real_cu_count) < (closest_cu))
                        {
                            MIOPEN_LOG_I2("Updating best candidate to: " << filepath.string());
                            best_path  = filepath;
                            closest_cu = abs(cur_count - real_cu_count);
                        }
                    }
                }
                return best_path.string();
            }
            return std::string();
        }();
        return result;
    }
#else
    std::string GetPerfDbPathFile() const
    {
        static const auto result = [&] {
            boost::filesystem::path pdb_path(GetSystemDbPath());
            std::ostringstream filename;
            // clang-format off
        filename << GetStream().GetDbBasename();
#if MIOPEN_ENABLE_SQLITE
        const std::string ext = ".db";
#else
        const std::string ext = ".cd.pdb.txt";
#endif
        filename << ext;
            // clang-format on
            if(boost::filesystem::exists(pdb_path / filename.str()))
            {
                MIOPEN_LOG_I("Found exact perf database file");
                return (pdb_path / filename.str()).string();
            }
            else
            {
                MIOPEN_LOG_I2("inexact perf database search");
                const auto db_id        = GetStream().GetTargetProperties().DbId();
                const int real_cu_count = GetStream().GetMaxComputeUnits();
                namespace fs            = boost::filesystem;
                if(fs::exists(pdb_path) && fs::is_directory(pdb_path))
                {
                    MIOPEN_LOG_I2("Iterating over perf db directory " << pdb_path.string());
                    int closest_cu = std::numeric_limits<int>::max();
                    fs::path best_path;
                    for(auto const& entry : fs::recursive_directory_iterator(pdb_path))
                    {
                        const auto& filepath = entry.path();
                        const auto fname     = filepath.stem().string();
                        if(fs::is_regular_file(entry) && filepath.extension() == ext &&
                           fname.rfind(db_id, 0) == 0) // starts with db_id
                        {
                            MIOPEN_LOG_I2("Checking perf db file: " << fname);
                            const auto pos = fname.find('_');
                            int cur_count  = -1;
                            try
                            {
                                if(pos != std::string::npos)
                                    cur_count = std::stoi(fname.substr(pos + 1));
                                else
                                    cur_count =
                                        std::stoi(fname.substr(db_id.length()), nullptr, 16);
                            }
                            catch(const std::exception& e)
                            {
                                MIOPEN_LOG_I2("Unable to infer CU count for file: "
                                              << fname << " : " << e.what());
                                continue;
                            }

                            if(abs(cur_count - real_cu_count) < (closest_cu))
                            {
                                MIOPEN_LOG_I2("Updating best candidate to: " << filepath.string());
                                best_path  = filepath;
                                closest_cu = abs(cur_count - real_cu_count);
                            }
                        }
                    }
                    return best_path.string();
                }
                else
                {
                    MIOPEN_LOG_I("Database directory does not exist");
                }
            }
            return std::string();
        }();
        return result;
    }
#endif

    std::string GetPerfDbPath() const
    {
#if MIOPEN_EMBED_DB
        return GetPerfDbPathEmbed();
#else
        return GetPerfDbPathFile();
#endif
    }

    std::string GetUserPerfDbPath() const
    {
        // an empty user-db path indicates user intent to disable
        // the database. Default in when dev builds are on
        // clang-format off
	const auto& udb = GetUserDbPath();
	if(udb.empty())
		return "";
        boost::filesystem::path pdb_path(udb);
        std::ostringstream filename;
        filename << GetStream().GetDbBasename();
#if MIOPEN_ENABLE_SQLITE
        filename << "_" << SQLitePerfDb::MIOPEN_PERFDB_SCHEMA_VER << ".udb";
#else
        filename << "."
             << GetUserDbSuffix()
             << ".cd.updb.txt";
#endif
        // clang-format on
        return (pdb_path / filename.str()).string();
    }

    private:
    Handle* stream = nullptr;
};

class AutoUseFastDynamicSolutions
{
    bool prev_skip_slow_;
    bool prev_use_dynamic_;
    ExecutionContext* const ctx;

    public:
    AutoUseFastDynamicSolutions(ExecutionContext& ctx_) : ctx(&ctx_)
    {
        prev_skip_slow_ = ctx->skip_solutions_that_take_long_time_to_build_and_have_narrow_coverage;
        prev_use_dynamic_ = ctx->use_dynamic_solutions_only;

        ctx->skip_solutions_that_take_long_time_to_build_and_have_narrow_coverage = true;
        ctx->use_dynamic_solutions_only                                           = true;
    }

    ~AutoUseFastDynamicSolutions()
    {
        ctx->skip_solutions_that_take_long_time_to_build_and_have_narrow_coverage = prev_skip_slow_;
        ctx->use_dynamic_solutions_only = prev_use_dynamic_;
    }
};

bool IsHipKernelsEnabled();

} // namespace miopen

max_stars_repo_name: Slimakanzer/MIOpen

max_issues_repo_name: Slimakanzer/MIOpen

max_forks_repo_name: Slimakanzer/MIOpen


text:
//==================================================================================================
/**
  EVE - Expressive Vector Engine
  Copyright : EVE Contributors & Maintainers
  SPDX-License-Identifier: MIT
**/
//==================================================================================================
#include <eve/function/ellint_2.hpp>
#include <boost/math/special_functions/ellint_2.hpp>
#include <eve/function/next.hpp>
#include <eve/function/prev.hpp>
#include <eve/function/is_denormal.hpp>
#include <eve/constant/nan.hpp>
#include <eve/constant/inf.hpp>
#include <eve/constant/minf.hpp>
#include <eve/constant/minlog.hpp>
#include <eve/platform.hpp>

#include <cmath>

TTS_CASE_TPL("Check eve::ellint_2 return type", EVE_TYPE)
{
  TTS_EXPR_IS(eve::ellint_2(T(0)), T);
}

TTS_CASE_TPL("Check eve::ellint_2 behavior one parameter", EVE_TYPE)
{
  using v_t = eve::element_type_t<T>;

  if constexpr( eve::platform::supports_invalids )
  {
    TTS_IEEE_EQUAL(eve::ellint_2(eve::nan(eve::as<T>())) , eve::nan(eve::as<T>()) );
  }

  TTS_ULP_EQUAL(eve::ellint_2(T(1)) , T(boost::math::ellint_2(v_t(1))), 0.5);
  TTS_ULP_EQUAL(eve::ellint_2(T(-1)), T(boost::math::ellint_2(v_t(-1))), 0.5);
  TTS_ULP_EQUAL( eve::ellint_2(T( 0.)), T(boost::math::ellint_2(v_t(0))), 0.5);
  TTS_ULP_EQUAL( eve::ellint_2(T( 0.5)), T(boost::math::ellint_2(v_t(0.5))), 1.0);
  TTS_ULP_EQUAL( eve::ellint_2(T( 0.9)), T(boost::math::ellint_2(v_t(0.9))), 0.5);

}

TTS_CASE_TPL("Check eve::ellint_2 behavior two parameter", EVE_TYPE)
{
  using v_t = eve::element_type_t<T>;
  using eve::as;
  if constexpr( eve::platform::supports_invalids )
  {
    TTS_IEEE_EQUAL(eve::ellint_2(eve::pio_2(as<T>()), eve::nan(eve::as<T>())) , eve::nan(eve::as<T>()) );
  }

  TTS_ULP_EQUAL( eve::ellint_2(eve::pio_2(as<T>()), T( 1.)),  T(boost::math::ellint_2(v_t(1)  , eve::pio_2(as<v_t>()))), 2.0);
  TTS_ULP_EQUAL( eve::ellint_2(eve::pio_2(as<T>()), T(-1.)),  T(boost::math::ellint_2(v_t(-1) , eve::pio_2(as<v_t>()))), 2.0);
  TTS_ULP_EQUAL( eve::ellint_2(eve::pio_2(as<T>()), T( 0.)),  T(boost::math::ellint_2(v_t(0)  , eve::pio_2(as<v_t>()))), 2.0);
  TTS_ULP_EQUAL( eve::ellint_2(eve::pio_2(as<T>()), T( 0.5)), T(boost::math::ellint_2(v_t(0.5), eve::pio_2(as<v_t>()))), 2.0);
  TTS_ULP_EQUAL( eve::ellint_2(eve::pio_2(as<T>()), T( 0.9)), T(boost::math::ellint_2(v_t(0.9), eve::pio_2(as<v_t>()))), 2.0);
  TTS_ULP_EQUAL( eve::ellint_2(eve::pio_4(as<T>()), T( 0.)),  T(boost::math::ellint_2(v_t(0)  , eve::pio_4(as<v_t>()))), 2.0);
  TTS_ULP_EQUAL( eve::ellint_2(eve::pio_4(as<T>()), T( 0.5)), T(boost::math::ellint_2(v_t(0.5), eve::pio_4(as<v_t>()))), 2.0);
  TTS_ULP_EQUAL( eve::ellint_2(eve::pio_4(as<T>()), T( 0.9)), T(boost::math::ellint_2(v_t(0.9), eve::pio_4(as<v_t>()))), 2.0);
  TTS_ULP_EQUAL( eve::ellint_2(eve::pio_4(as<T>()), T( 1.0)), T(boost::math::ellint_2(v_t(1.0), eve::pio_4(as<v_t>()))), 2.0);
  TTS_ULP_EQUAL( eve::ellint_2(3*eve::pio_4(as<T>()), T( 0.5)), T(boost::math::ellint_2(v_t(0.5), 3*eve::pio_4(as<v_t>()))), 2.0);
  TTS_ULP_EQUAL( eve::ellint_2(3*eve::pio_4(as<T>()), T( 0.9)), T(boost::math::ellint_2(v_t(0.9), 3*eve::pio_4(as<v_t>()))), 2.0);
  TTS_ULP_EQUAL( eve::ellint_2(3*eve::pio_4(as<T>()), T( 0.)),  T(boost::math::ellint_2(v_t(0)  , 3*eve::pio_4(as<v_t>()))), 2.0);
  TTS_ULP_EQUAL( eve::ellint_2(T(100), T( 0.5)), T(boost::math::ellint_2(v_t(0.5), v_t(100))), 2.0);
  TTS_ULP_EQUAL( eve::ellint_2(T(100), T( 0.9)), T(boost::math::ellint_2(v_t(0.9), v_t(100))), 2.0);
  TTS_ULP_EQUAL( eve::ellint_2(T(100), T( 0.)),  T(boost::math::ellint_2(v_t(0)  , v_t(100))), 2.0);

}

max_stars_repo_name: orao/eve

max_issues_repo_name: orao/eve

max_forks_repo_name: orao/eve


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

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
/////////////////////////////////////////////////////////////////////////////
//
// (C) Copyright Ion Gaztanaga  2014-2014
//
// 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)
//
// See http://www.boost.org/libs/intrusive for documentation.
//
/////////////////////////////////////////////////////////////////////////////

#ifndef BOOST_INTRUSIVE_BSTREE_ALGORITHMS_BASE_HPP
#define BOOST_INTRUSIVE_BSTREE_ALGORITHMS_BASE_HPP

#ifndef BOOST_CONFIG_HPP
#  include <boost/config.hpp>
#endif

#if defined(BOOST_HAS_PRAGMA_ONCE)
#  pragma once
#endif

#include <boost/intrusive/detail/uncast.hpp>

namespace boost {
namespace intrusive {

template<class NodeTraits>
class bstree_algorithms_base
{
   public:
   typedef typename NodeTraits::node            node;
   typedef NodeTraits                           node_traits;
   typedef typename NodeTraits::node_ptr        node_ptr;
   typedef typename NodeTraits::const_node_ptr  const_node_ptr;

   //! Requires: 'node' is a node from the tree except the header.
   //!
   //! Effects: Returns the next node of the tree.
   //!
   //! Complexity: Average constant time.
   //!
   //! Throws: Nothing.
   static node_ptr next_node(const node_ptr & node)
   {
      node_ptr const n_right(NodeTraits::get_right(node));
      if(n_right){
         return minimum(n_right);
      }
      else {
         node_ptr n(node);
         node_ptr p(NodeTraits::get_parent(n));
         while(n == NodeTraits::get_right(p)){
            n = p;
            p = NodeTraits::get_parent(p);
         }
         return NodeTraits::get_right(n) != p ? p : n;
      }
   }

   //! Requires: 'node' is a node from the tree except the leftmost node.
   //!
   //! Effects: Returns the previous node of the tree.
   //!
   //! Complexity: Average constant time.
   //!
   //! Throws: Nothing.
   static node_ptr prev_node(const node_ptr & node)
   {
      if(is_header(node)){
         return NodeTraits::get_right(node);
         //return maximum(NodeTraits::get_parent(node));
      }
      else if(NodeTraits::get_left(node)){
         return maximum(NodeTraits::get_left(node));
      }
      else {
         node_ptr p(node);
         node_ptr x = NodeTraits::get_parent(p);
         while(p == NodeTraits::get_left(x)){
            p = x;
            x = NodeTraits::get_parent(x);
         }
         return x;
      }
   }

   //! Requires: 'node' is a node of a tree but not the header.
   //!
   //! Effects: Returns the minimum node of the subtree starting at p.
   //!
   //! Complexity: Logarithmic to the size of the subtree.
   //!
   //! Throws: Nothing.
   static node_ptr minimum(node_ptr node)
   {
      for(node_ptr p_left = NodeTraits::get_left(node)
         ;p_left
         ;p_left = NodeTraits::get_left(node)){
         node = p_left;
      }
      return node;
   }

   //! Requires: 'node' is a node of a tree but not the header.
   //!
   //! Effects: Returns the maximum node of the subtree starting at p.
   //!
   //! Complexity: Logarithmic to the size of the subtree.
   //!
   //! Throws: Nothing.
   static node_ptr maximum(node_ptr node)
   {
      for(node_ptr p_right = NodeTraits::get_right(node)
         ;p_right
         ;p_right = NodeTraits::get_right(node)){
         node = p_right;
      }
      return node;
   }

   //! Requires: p is a node of a tree.
   //!
   //! Effects: Returns true if p is the header of the tree.
   //!
   //! Complexity: Constant.
   //!
   //! Throws: Nothing.
   static bool is_header(const const_node_ptr & p)
   {
      node_ptr p_left (NodeTraits::get_left(p));
      node_ptr p_right(NodeTraits::get_right(p));
      if(!NodeTraits::get_parent(p) || //Header condition when empty tree
         (p_left && p_right &&         //Header always has leftmost and rightmost
            (p_left == p_right ||      //Header condition when only node
               (NodeTraits::get_parent(p_left)  != p ||
                NodeTraits::get_parent(p_right) != p ))
               //When tree size > 1 headers can't be leftmost's
               //and rightmost's parent
          )){
         return true;
      }
      return false;
   }

   //! Requires: 'node' is a node of the tree or a header node.
   //!
   //! Effects: Returns the header of the tree.
   //!
   //! Complexity: Logarithmic.
   //!
   //! Throws: Nothing.
   static node_ptr get_header(const const_node_ptr & node)
   {
      node_ptr n(detail::uncast(node));
      node_ptr p(NodeTraits::get_parent(node));
      //If p is null, then n is the header of an empty tree
      if(p){
         //Non-empty tree, check if n is neither root nor header
         node_ptr pp(NodeTraits::get_parent(p));
         //If granparent is not equal to n, then n is neither root nor header,
         //the try the fast path
         if(n != pp){
            do{
               n = p;
               p = pp;
               pp = NodeTraits::get_parent(pp);
            }while(n != pp);
            n = p;
         }
         //Check if n is root or header when size() > 0
         else if(!bstree_algorithms_base::is_header(n)){
            n = p;
         }
      }
      return n;
   }
};

}  //namespace intrusive
}  //namespace boost

#endif //BOOST_INTRUSIVE_BSTREE_ALGORITHMS_BASE_HPP

max_stars_repo_name: multi-os-engine/cinder-natj-binding

max_issues_repo_name: multi-os-engine/cinder-natj-binding

max_forks_repo_name: multi-os-engine/cinder-natj-binding


text:
#include "image_writer.h"
#include "json_writer.h"
#include "parser.h"

#include <boost/format.hpp>
#include <boost/program_options.hpp>
#include <fstream>

using namespace wotreplay;
namespace po = boost::program_options;

void show_help(int argc, const char *argv[], po::options_description &desc) {
    std::string program_name(argv[0]);
    std::cout
        << boost::format("Usage: %1% --root <working directory> --type <output type> --input <input file> --output <output file>\n\n") % program_name
        << desc << "\n";
}

bool has_required_options(po::variables_map &vm) {
    return vm.count("output") > 0 || vm.count("type") > 0
            || vm.count("root") > 0|| vm.count("input") > 0;
}

int main(int argc, const char * argv[]) {
    po::options_description desc("Allowed options");

    std::string type, output, input, root;

    desc.add_options()
        ("type,t"  , po::value(&type), "select output type")
        ("output,o", po::value(&output), "target file")
        ("input,i" , po::value(&input), "input file")
        ("root,r"  , po::value(&root), "set root directory")
        ("help,h"  , "produce help message")
        ("debug"   , "enable parser debugging");

    po::variables_map vm;

    try {
        po::store(po::parse_command_line(argc, argv, desc), vm);
        po::notify(vm);
    } catch (std::exception &e) {
        show_help(argc, argv, desc);
        std::exit(-1);
    } catch (...) {
        std::cerr << "Unknown error." << std::endl;
        std::exit(-1);
    }

    if (vm.count("help")
            || !has_required_options(vm)) {
        show_help(argc, argv, desc);
        std::exit(0);
    }

    if (chdir(root.c_str()) != 0) {
        std::cerr << boost::format("cannot change working directory to: %1%\n") % root;
        std::exit(0);
    }

    std::ifstream is(input, std::ios::binary);

    if (!is) {
        std::cerr << boost::format("Something went wrong with reading file: %1%\n") % input;
        std::exit(0);
    }

    parser_t parser;
    game_t game;

    bool debug = vm.count("debug") > 0;
    parser.set_debug(debug);
    parser.parse(is, game);
    is.close();

    std::unique_ptr<writer_t> writer;

    if (type == "png") {
        writer = std::unique_ptr<writer_t>(new image_writer_t());
        auto &image_writer = dynamic_cast<image_writer_t&>(*writer);
        image_writer.set_show_self(true);
    } else if (type == "json") {
        writer = std::unique_ptr<writer_t>(new json_writer_t());
    } else {
        std::cout << "Invalid output type, supported types: png" << std::endl;
    }

    writer->init(game.get_map_name(), game.get_game_mode());
    writer->update(game);
    writer->finish();

    std::ofstream file(output);
    writer->write(file);

    return EXIT_SUCCESS;
}

ext: cpp


text:
#include <iostream>
#include <boost/date_time.hpp>
int main()
{
    std::cout << boost::posix_time::ptime( boost::posix_time::min_date_time ) << '\n';
    return 0;
}

max_stars_repo_name: ethansaxenian/RosettaDecode

max_issues_repo_name: ethansaxenian/RosettaDecode

max_forks_repo_name: ethansaxenian/RosettaDecode


text:
#include <epoxy/gl.h>
#include <GLFW/glfw3.h>
#include <boost/filesystem.hpp>
#include <iostream>

#include <shadertoy.hpp>
#include <shadertoy/utils/log.hpp>

#include "test.hpp"

namespace fs = boost::filesystem;
using shadertoy::gl::gl_call;

int main(int argc, char *argv[])
{
	int code = 0;

	if (!glfwInit())
	{
		std::cerr << "Failed to initialize glfw" << std::endl;
		return 2;
	}

	// Initialize window
	int width = 7 * 64, height = 7 * 64;
	GLFWwindow *window = glfwCreateWindow(width, height, "libshadertoy example 11-image", nullptr, nullptr);

	if (!window)
	{
		std::cerr << "Failed to create glfw window" << std::endl;
		code = 1;
	}
	else
	{
		glfwMakeContextCurrent(window);
		glfwSwapInterval(1);

		shadertoy::utils::log::shadertoy()->set_level(spdlog::level::trace);

		try
		{
			example_ctx ctx;
			auto &context(ctx.context);
			auto &chain(ctx.chain);

			// Set the context parameters (render size and some uniforms)
			ctx.render_size = shadertoy::rsize(width, height);

			// Create an auxiliary buffer that renders a gradient
			auto gradientBuffer(std::make_shared<shadertoy::buffers::toy_buffer>("gradient"));
			gradientBuffer->source_file(ST_BASE_DIR "/shaders/shader-gradient.glsl");
			auto buffer_input(std::make_shared<shadertoy::inputs::buffer_input>(chain.emplace_back(gradientBuffer, shadertoy::make_size(shadertoy::rsize(16, 16)), GL_R8)));

			// Create the image buffer
			auto imageBuffer(std::make_shared<shadertoy::buffers::toy_buffer>("image"));
			imageBuffer->source_file(ST_BASE_DIR "/shaders/shader-image.glsl");

			shadertoy::utils::input_loader loader;

			imageBuffer->inputs().emplace_back(loader.create("file:///" ST_BASE_DIR "/images/vase_rect.exr", false)); // implicit iChannel0
			imageBuffer->inputs().emplace_back(loader.create("file:///" ST_BASE_DIR "/images/vase_rect.png", false)); // implicit iChannel1
			imageBuffer->inputs().emplace_back(loader.create("file:///" ST_BASE_DIR "/images/vase_rect.jpg", false)); // implicit iChannel2
			imageBuffer->inputs().emplace_back("noiseChannel", loader.create("noise:?width=64&height=64"));
			imageBuffer->inputs().emplace_back("checkerChannel", loader.create("checker:?width=64&height=64&size=4"));
			imageBuffer->inputs().emplace_back("errorChannel", context.error_input());
			imageBuffer->inputs().emplace_back("bufferChannel", buffer_input);

			for (auto &program_input : imageBuffer->inputs())
			{
				program_input.input()->mag_filter(GL_LINEAR);
				program_input.input()->min_filter(GL_LINEAR_MIPMAP_LINEAR);
				program_input.input()->wrap(GL_REPEAT);
			}

			imageBuffer->inputs().back().input()->sampler().parameter(GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

			// Add the image buffer to the swap chain
			chain.emplace_back(imageBuffer, shadertoy::make_size_ref(ctx.render_size));

			// Create a swap chain member that renders to the screen
			chain.emplace_back<shadertoy::members::screen_member>(shadertoy::make_size_ref(ctx.render_size));

			// Initialize context
			context.init(chain);
			std::cout << "Initialized swap chain" << std::endl;

			// Set uniforms
			chain.set_uniform("iTimeDelta", 1.0f / 60.0f);
			chain.set_uniform("iFrameRate", 60.0f);

			// Now render for 5s
			int frameCount = 0;
			float t = 0.;

			// Set the resize callback
			glfwSetWindowUserPointer(window, &ctx);
			glfwSetFramebufferSizeCallback(window, example_set_framebuffer_size<example_ctx>);

			while (!glfwWindowShouldClose(window))
			{
				// Poll events
				glfwPollEvents();

				// Update uniforms
				chain.set_uniform("iTime", t);
				chain.set_uniform("iFrame", frameCount);

				// Render the swap chain
				context.render(chain);

				// Buffer swapping
				glfwSwapBuffers(window);

				// Update time and framecount
				t = glfwGetTime();
				frameCount++;

				if (libshadertoy_test_exit())
					glfwSetWindowShouldClose(window, true);
			}
		}
		catch (shadertoy::gl::shader_compilation_error &sce)
		{
			std::cerr << "Failed to compile shader: " << sce.log();
			code = 2;
		}
		catch (shadertoy::shadertoy_error &err)
		{
			std::cerr << "Error: " << err.what();
			code = 2;
		}

		glfwDestroyWindow(window);
	}

	glfwTerminate();
	return code;
}

max_stars_repo_name: vtavernier/libshadertoy

max_issues_repo_name: vtavernier/libshadertoy

max_forks_repo_name: vtavernier/libshadertoy


text:
#include <iostream>
#include <memory>
#include <atomic>
#include <vector>

#include <boost/asio.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>

using namespace boost::asio;

struct SocketStr
{
    std::shared_ptr<ip::tcp::socket> pSocket;
    char readBuffer[1024*32];
    char writeBuffer[1024*32];
};
using SocketPtr = std::shared_ptr<SocketStr>;

void startRead(SocketPtr ptr);

void write(SocketPtr ptr,size_t size)
{
    ptr->pSocket->async_write_some( buffer(ptr->writeBuffer, size), [ptr](const boost::system::error_code& error,std::size_t size)
    {
        startRead(ptr);
    });
}

void onRead(SocketPtr ptr,const boost::system::error_code& error,std::size_t size)
{
    if(error)
    {
        return;
    }
    std::copy(ptr->readBuffer, ptr->readBuffer+size, ptr->writeBuffer);
    write(ptr,size);
}

void startRead(SocketPtr ptr)
{
    auto pSocket = ptr->pSocket;
    auto buff = ptr->readBuffer;
    uint64_t size = sizeof(ptr->readBuffer);
    pSocket->async_read_some(buffer(buff,size),std::bind(&onRead,ptr,std::placeholders::_1,std::placeholders::_2));
}

void startClients(io_service& io,std::vector<SocketPtr>& sockets,ip::tcp::endpoint& endpoint, uint64_t cnt)
{
    for(uint64_t i=0;i<cnt;i++)
    {
        SocketPtr ptr = std::make_shared<SocketStr>();
        sockets.push_back(ptr);
        ptr->pSocket = std::make_shared<ip::tcp::socket>(io);
        ptr->pSocket->async_connect(endpoint, [ptr](const boost::system::error_code& error)
        {
            if(error)
            {
                std::cout<<"connect fail"<<std::endl;
                return;
            }
            uint64_t size = 1024*8;
            write(ptr,size);
        });
    }
}

int main(int argc, char* argv[])
{
    io_service io;
    std::vector<SocketPtr> sockets;
    ip::tcp::endpoint endpoint( ip::address::from_string("127.0.0.1"), 10012);
    startClients(io,sockets,endpoint,1);
    io.run();
}

max_stars_repo_name: newspacer/uv-cpp


text:
//  Copyright (c) 2001-2011 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_KARMA_NUMERIC_UTILS_FEB_23_2007_0841PM)
#define BOOST_SPIRIT_KARMA_NUMERIC_UTILS_FEB_23_2007_0841PM

#if defined(_MSC_VER)
#pragma once
#endif

#include <boost/config.hpp>
#include <boost/config/no_tr1/cmath.hpp>
#include <boost/limits.hpp>

#include <boost/type_traits/is_integral.hpp>
#include <boost/spirit/home/support/char_class.hpp>
#include <boost/spirit/home/support/unused.hpp>
#include <boost/spirit/home/support/numeric_traits.hpp>
#include <boost/spirit/home/support/detail/pow10.hpp>
#include <boost/spirit/home/support/detail/sign.hpp>
#include <boost/spirit/home/karma/detail/generate_to.hpp>
#include <boost/spirit/home/karma/detail/string_generate.hpp>

///////////////////////////////////////////////////////////////////////////////
//
//  The value BOOST_KARMA_NUMERICS_LOOP_UNROLL specifies, how to unroll the
//  integer string generation loop (see below).
//
//      Set the value to some integer in between 0 (no unrolling) and the
//      largest expected generated integer string length (complete unrolling).
//      If not specified, this value defaults to 6.
//
///////////////////////////////////////////////////////////////////////////////
#if !defined(BOOST_KARMA_NUMERICS_LOOP_UNROLL)
#define BOOST_KARMA_NUMERICS_LOOP_UNROLL 6
#endif

#if BOOST_KARMA_NUMERICS_LOOP_UNROLL < 0
#error "Please set the BOOST_KARMA_NUMERICS_LOOP_UNROLL to a non-negative value!"
#endif

namespace boost { namespace spirit { namespace traits
{
    ///////////////////////////////////////////////////////////////////////
    //
    //  return the absolute value from a given number, avoiding over- and
    //  underflow
    //
    ///////////////////////////////////////////////////////////////////////
    template <typename T, typename Enable/* = void*/>
    struct absolute_value
    {
        typedef T type;
        static T call (T n)
        {
            // allow for ADL to find the correct overloads for fabs
            using namespace std;
            return fabs(n);
        }
    };

#define BOOST_SPIRIT_ABSOLUTE_VALUE(signedtype, unsignedtype)                 \
        template <>                                                           \
        struct absolute_value<signedtype>                                     \
        {                                                                     \
            typedef unsignedtype type;                                        \
            static type call(signedtype n)                                    \
            {                                                                 \
                return static_cast<unsignedtype>((n >= 0) ? n : -n);          \
            }                                                                 \
        }                                                                     \
    /**/
#define BOOST_SPIRIT_ABSOLUTE_VALUE_UNSIGNED(unsignedtype)                    \
        template <>                                                           \
        struct absolute_value<unsignedtype>                                   \
        {                                                                     \
            typedef unsignedtype type;                                        \
            static type call(unsignedtype n)                                  \
            {                                                                 \
                return n;                                                     \
            }                                                                 \
        }                                                                     \
    /**/

    BOOST_SPIRIT_ABSOLUTE_VALUE(signed char, unsigned char);
    BOOST_SPIRIT_ABSOLUTE_VALUE(char, unsigned char);
    BOOST_SPIRIT_ABSOLUTE_VALUE(short, unsigned short);
    BOOST_SPIRIT_ABSOLUTE_VALUE(int, unsigned int);
    BOOST_SPIRIT_ABSOLUTE_VALUE(long, unsigned long);
    BOOST_SPIRIT_ABSOLUTE_VALUE_UNSIGNED(unsigned char);
    BOOST_SPIRIT_ABSOLUTE_VALUE_UNSIGNED(unsigned short);
    BOOST_SPIRIT_ABSOLUTE_VALUE_UNSIGNED(unsigned int);
    BOOST_SPIRIT_ABSOLUTE_VALUE_UNSIGNED(unsigned long);
#ifdef BOOST_HAS_LONG_LONG
    BOOST_SPIRIT_ABSOLUTE_VALUE(boost::long_long_type, boost::ulong_long_type);
    BOOST_SPIRIT_ABSOLUTE_VALUE_UNSIGNED(boost::ulong_long_type);
#endif

#undef BOOST_SPIRIT_ABSOLUTE_VALUE
#undef BOOST_SPIRIT_ABSOLUTE_VALUE_UNSIGNED

    template <>
    struct absolute_value<float>
    {
        typedef float type;
        static type call(float n)
        {
            return (spirit::detail::signbit)(n) ? -n : n;
        }
    };

    template <>
    struct absolute_value<double>
    {
        typedef double type;
        static type call(double n)
        {
            return (spirit::detail::signbit)(n) ? -n : n;
        }
    };

    template <>
    struct absolute_value<long double>
    {
        typedef long double type;
        static type call(long double n)
        {
            return (spirit::detail::signbit)(n) ? -n : n;
        }
    };

    // specialization for pointers
    template <typename T>
    struct absolute_value<T*>
    {
        typedef std::size_t type;
        static type call (T* p)
        {
            return std::size_t(p);
        }
    };

    template <typename T>
    inline typename absolute_value<T>::type
    get_absolute_value(T n)
    {
        return absolute_value<T>::call(n);
    }

    ///////////////////////////////////////////////////////////////////////
    template <typename T, typename Enable/* = void*/>
    struct is_negative
    {
        static bool call(T n)
        {
            return (n < 0) ? true : false;
        }
    };

    template <>
    struct is_negative<float>
    {
        static bool call(float n)
        {
            return (spirit::detail::signbit)(n) ? true : false;
        }
    };

    template <>
    struct is_negative<double>
    {
        static bool call(double n)
        {
            return (spirit::detail::signbit)(n) ? true : false;
        }
    };

    template <>
    struct is_negative<long double>
    {
        static bool call(long double n)
        {
            return (spirit::detail::signbit)(n) ? true : false;
        }
    };

    template <typename T>
    inline bool test_negative(T n)
    {
        return is_negative<T>::call(n);
    }

    ///////////////////////////////////////////////////////////////////////
    template <typename T, typename Enable/* = void*/>
    struct is_zero
    {
        static bool call(T n)
        {
            return (n == 0) ? true : false;
        }
    };

    template <>
    struct is_zero<float>
    {
        static bool call(float n)
        {
            return (math::fpclassify)(n) == FP_ZERO;
        }
    };

    template <>
    struct is_zero<double>
    {
        static bool call(double n)
        {
            return (math::fpclassify)(n) == FP_ZERO;
        }
    };

    template <>
    struct is_zero<long double>
    {
        static bool call(long double n)
        {
            return (math::fpclassify)(n) == FP_ZERO;
        }
    };

    template <typename T>
    inline bool test_zero(T n)
    {
        return is_zero<T>::call(n);
    }

    ///////////////////////////////////////////////////////////////////////
    template <typename T, typename Enable/* = void*/>
    struct is_nan
    {
        static bool call(T n)
        {
            // NaN numbers are not equal to anything
            return (n != n) ? true : false;
        }
    };

    template <>
    struct is_nan<float>
    {
        static bool call(float n)
        {
            return (math::fpclassify)(n) == FP_NAN;
        }
    };

    template <>
    struct is_nan<double>
    {
        static bool call(double n)
        {
            return (math::fpclassify)(n) == FP_NAN;
        }
    };

    template <>
    struct is_nan<long double>
    {
        static bool call(long double n)
        {
            return (math::fpclassify)(n) == FP_NAN;
        }
    };

    template <typename T>
    inline bool test_nan(T n)
    {
        return is_nan<T>::call(n);
    }

    ///////////////////////////////////////////////////////////////////////
    template <typename T, typename Enable/* = void*/>
    struct is_infinite
    {
        static bool call(T n)
        {
            if (!std::numeric_limits<T>::has_infinity)
                return false;
            return (n == std::numeric_limits<T>::infinity()) ? true : false;
        }
    };

    template <>
    struct is_infinite<float>
    {
        static bool call(float n)
        {
            return (math::fpclassify)(n) == FP_INFINITE;
        }
    };

    template <>
    struct is_infinite<double>
    {
        static bool call(double n)
        {
            return (math::fpclassify)(n) == FP_INFINITE;
        }
    };

    template <>
    struct is_infinite<long double>
    {
        static bool call(long double n)
        {
            return (math::fpclassify)(n) == FP_INFINITE;
        }
    };

    template <typename T>
    inline bool test_infinite(T n)
    {
        return is_infinite<T>::call(n);
    }

    ///////////////////////////////////////////////////////////////////////
    struct cast_to_long
    {
        static long call(float n, mpl::false_)
        {
            return static_cast<long>(std::floor(n));
        }

        static long call(double n, mpl::false_)
        {
            return static_cast<long>(std::floor(n));
        }

        static long call(long double n, mpl::false_)
        {
            return static_cast<long>(std::floor(n));
        }

        template <typename T>
        static long call(T n, mpl::false_)
        {
            // allow for ADL to find the correct overload for floor and
            // lround
            using namespace std;
            return lround(floor(n));
        }

        template <typename T>
        static long call(T n, mpl::true_)
        {
            return static_cast<long>(n);
        }

        template <typename T>
        static long call(T n)
        {
            return call(n, mpl::bool_<is_integral<T>::value>());
        }
    };

    ///////////////////////////////////////////////////////////////////////
    struct truncate_to_long
    {
        static long call(float n, mpl::false_)
        {
            return test_negative(n) ? static_cast<long>(std::ceil(n)) :
                static_cast<long>(std::floor(n));
        }

        static long call(double n, mpl::false_)
        {
            return test_negative(n) ? static_cast<long>(std::ceil(n)) :
                static_cast<long>(std::floor(n));
        }

        static long call(long double n, mpl::false_)
        {
            return test_negative(n) ? static_cast<long>(std::ceil(n)) :
                static_cast<long>(std::floor(n));
        }

        template <typename T>
        static long call(T n, mpl::false_)
        {
            // allow for ADL to find the correct overloads for ltrunc
            using namespace std;
            return ltrunc(n);
        }

        template <typename T>
        static long call(T n, mpl::true_)
        {
            return static_cast<long>(n);
        }

        template <typename T>
        static long call(T n)
        {
            return call(n, mpl::bool_<is_integral<T>::value>());
        }
    };

    ///////////////////////////////////////////////////////////////////////
    //
    //  Traits class for radix specific number conversion
    //
    //      Convert a digit from binary representation to character
    //      representation:
    //
    //          static int call(unsigned n);
    //
    ///////////////////////////////////////////////////////////////////////
    namespace detail
    {
        template <typename CharEncoding, typename Tag, bool radix_less_than_10>
        struct convert_digit
        {
            static int call(unsigned n)
            {
                if (n <= 9)
                    return n + '0';

                using spirit::char_class::convert;
                return convert<CharEncoding>::to(Tag(), n - 10 + 'a');
            }
        };

        template <>
        struct convert_digit<unused_type, unused_type, false>
        {
            static int call(unsigned n)
            {
                if (n <= 9)
                    return n + '0';
                return n - 10 + 'a';
            }
        };

        template <typename CharEncoding, typename Tag>
        struct convert_digit<CharEncoding, Tag, true>
        {
            static int call(unsigned n)
            {
                return n + '0';
            }
        };
    }

    template <unsigned Radix, typename CharEncoding, typename Tag>
    struct convert_digit
      : detail::convert_digit<CharEncoding, Tag, (Radix <= 10) ? true : false>
    {};

    ///////////////////////////////////////////////////////////////////////
    template <unsigned Radix>
    struct divide
    {
        template <typename T>
        static T call(T& n, mpl::true_)
        {
            return n / Radix;
        }

        template <typename T>
        static T call(T& n, mpl::false_)
        {
            // Allow ADL to find the correct overload for floor
            using namespace std;
            return floor(n / Radix);
        }

        template <typename T>
        static T call(T& n, T const&, int)
        {
            return call(n, mpl::bool_<is_integral<T>::value>());
        }

        template <typename T>
        static T call(T& n)
        {
            return call(n, mpl::bool_<is_integral<T>::value>());
        }
    };

    // specialization for division by 10
    template <>
    struct divide<10>
    {
        template <typename T>
        static T call(T& n, T, int, mpl::true_)
        {
            return n / 10;
        }

        template <typename T>
        static T call(T, T& num, int exp, mpl::false_)
        {
            // Allow ADL to find the correct overload for floor
            using namespace std;
            return floor(num / spirit::traits::pow10<T>(exp));
        }

        template <typename T>
        static T call(T& n, T& num, int exp)
        {
            return call(n, num, exp, mpl::bool_<is_integral<T>::value>());
        }

        template <typename T>
        static T call(T& n)
        {
            return call(n, n, 1, mpl::bool_<is_integral<T>::value>());
        }
    };

    ///////////////////////////////////////////////////////////////////////
    template <unsigned Radix>
    struct remainder
    {
        template <typename T>
        static long call(T n, mpl::true_)
        {
            // this cast is safe since we know the result is not larger
            // than Radix
            return static_cast<long>(n % Radix);
        }

        template <typename T>
        static long call(T n, mpl::false_)
        {
            // Allow ADL to find the correct overload for fmod
            using namespace std;
            return cast_to_long::call(fmod(n, T(Radix)));
        }

        template <typename T>
        static long call(T n)
        {
            return call(n, mpl::bool_<is_integral<T>::value>());
        }
    };
}}}

namespace boost { namespace spirit { namespace karma
{
    ///////////////////////////////////////////////////////////////////////////
    //
    //  The int_inserter template takes care of the integer to string
    //  conversion. If specified, the loop is unrolled for better performance.
    //
    //      Set the value BOOST_KARMA_NUMERICS_LOOP_UNROLL to some integer in
    //      between 0 (no unrolling) and the largest expected generated integer
    //      string length (complete unrolling).
    //      If not specified, this value defaults to 6.
    //
    ///////////////////////////////////////////////////////////////////////////
#define BOOST_KARMA_NUMERICS_INNER_LOOP_PREFIX(z, x, data)                    \
        if (!traits::test_zero(n)) {                                          \
            int ch = radix_type::call(remainder_type::call(n));               \
            n = divide_type::call(n, num, ++exp);                             \
    /**/

#define BOOST_KARMA_NUMERICS_INNER_LOOP_SUFFIX(z, x, data)                    \
            *sink = char(ch);                                                 \
            ++sink;                                                           \
        }                                                                     \
    /**/

    template <
        unsigned Radix, typename CharEncoding = unused_type
      , typename Tag = unused_type>
    struct int_inserter
    {
        typedef traits::convert_digit<Radix, CharEncoding, Tag> radix_type;
        typedef traits::divide<Radix> divide_type;
        typedef traits::remainder<Radix> remainder_type;

        template <typename OutputIterator, typename T>
        static bool
        call(OutputIterator& sink, T n, T& num, int exp)
        {
            // remainder_type::call returns n % Radix
            int ch = radix_type::call(remainder_type::call(n));
            n = divide_type::call(n, num, ++exp);

            BOOST_PP_REPEAT(
                BOOST_KARMA_NUMERICS_LOOP_UNROLL,
                BOOST_KARMA_NUMERICS_INNER_LOOP_PREFIX, _);

            if (!traits::test_zero(n))
                call(sink, n, num, exp);

            BOOST_PP_REPEAT(
                BOOST_KARMA_NUMERICS_LOOP_UNROLL,
                BOOST_KARMA_NUMERICS_INNER_LOOP_SUFFIX, _);

            *sink = char(ch);
            ++sink;
            return true;
        }

        //  Common code for integer string representations
        template <typename OutputIterator, typename T>
        static bool
        call(OutputIterator& sink, T n)
        {
            return call(sink, n, n, 0);
        }

    private:
        // helper function returning the biggest number representable either in
        // a boost::long_long_type (if this does exist) or in a plain long
        // otherwise
#if defined(BOOST_HAS_LONG_LONG)
        typedef boost::long_long_type biggest_long_type;
#else
        typedef long biggest_long_type;
#endif

        static biggest_long_type max_long()
        {
            return (std::numeric_limits<biggest_long_type>::max)();
        }

    public:
        // Specialization for doubles and floats, falling back to long integers
        // for representable values. These specializations speed up formatting
        // of floating point numbers considerably as all the required
        // arithmetics will be executed using integral data types.
        template <typename OutputIterator>
        static bool
        call(OutputIterator& sink, long double n)
        {
            if (std::fabs(n) < max_long())
            {
                biggest_long_type l((biggest_long_type)n);
                return call(sink, l, l, 0);
            }
            return call(sink, n, n, 0);
        }
        template <typename OutputIterator>
        static bool
        call(OutputIterator& sink, double n)
        {
            if (std::fabs(n) < max_long())
            {
                biggest_long_type l((biggest_long_type)n);
                return call(sink, l, l, 0);
            }
            return call(sink, n, n, 0);
        }
        template <typename OutputIterator>
        static bool
        call(OutputIterator& sink, float n)
        {
            if (std::fabs(n) < max_long())
            {
                biggest_long_type l((biggest_long_type)n);
                return call(sink, l, l, 0);
            }
            return call(sink, n, n, 0);
        }
    };

#undef BOOST_KARMA_NUMERICS_INNER_LOOP_PREFIX
#undef BOOST_KARMA_NUMERICS_INNER_LOOP_SUFFIX

    ///////////////////////////////////////////////////////////////////////////
    //
    //  The uint_inserter template takes care of the conversion of any integer
    //  to a string, while interpreting the number as an unsigned type.
    //
    ///////////////////////////////////////////////////////////////////////////
    template <
        unsigned Radix, typename CharEncoding = unused_type
      , typename Tag = unused_type>
    struct uint_inserter : int_inserter<Radix, CharEncoding, Tag>
    {
        typedef int_inserter<Radix, CharEncoding, Tag> base_type;

        //  Common code for integer string representations
        template <typename OutputIterator, typename T>
        static bool
        call(OutputIterator& sink, T const& n)
        {
            typedef typename traits::absolute_value<T>::type type;
            type un = type(n);
            return base_type::call(sink, un, un, 0);
        }
    };

    ///////////////////////////////////////////////////////////////////////////
    //
    //  The sign_inserter template generates a sign for a given numeric value.
    //
    //    The parameter forcesign allows to generate a sign even for positive
    //    numbers.
    //
    ///////////////////////////////////////////////////////////////////////////
    struct sign_inserter
    {
        template <typename OutputIterator>
        static bool
        call_noforce(OutputIterator& sink, bool is_zero, bool is_negative,
            bool sign_if_zero)
        {
            // generate a sign for negative numbers only
            if (is_negative || (is_zero && sign_if_zero)) {
                *sink = '-';
                ++sink;
            }
            return true;
        }

        template <typename OutputIterator>
        static bool
        call_force(OutputIterator& sink, bool is_zero, bool is_negative,
            bool sign_if_zero)
        {
            // generate a sign for all numbers except zero
            if (!is_zero || sign_if_zero)
                *sink = is_negative ? '-' : '+';
            else
                *sink = ' ';

            ++sink;
            return true;
        }

        template <typename OutputIterator>
        static bool
        call(OutputIterator& sink, bool is_zero, bool is_negative
          , bool forcesign, bool sign_if_zero = false)
        {
            return forcesign ?
                call_force(sink, is_zero, is_negative, sign_if_zero) :
                call_noforce(sink, is_zero, is_negative, sign_if_zero);
        }
    };

    ///////////////////////////////////////////////////////////////////////////
    //  These are helper functions for the real policies allowing to generate
    //  a single character and a string
    ///////////////////////////////////////////////////////////////////////////
    template <typename CharEncoding = unused_type, typename Tag = unused_type>
    struct char_inserter
    {
        template <typename OutputIterator, typename Char>
        static bool call(OutputIterator& sink, Char c)
        {
            return detail::generate_to(sink, c, CharEncoding(), Tag());
        }
    };

    template <typename CharEncoding = unused_type, typename Tag = unused_type>
    struct string_inserter
    {
        template <typename OutputIterator, typename String>
        static bool call(OutputIterator& sink, String str)
        {
            return detail::string_generate(sink, str, CharEncoding(), Tag());
        }
    };

}}}

#endif


text:
//
// bluetooth/basic_endpoint.hpp
// ~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2019 Huang Qinjin (huangqinjin 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)
//

#ifndef BOOST_ASIO_BLUETOOTH_BASIC_ENDPOINT_HPP
#define BOOST_ASIO_BLUETOOTH_BASIC_ENDPOINT_HPP

#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)

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

#if defined(BOOST_ASIO_HAS_BLUETOOTH_SOCKETS) \
  || defined(GENERATING_DOCUMENTATION)

#include <boost/asio/bluetooth/detail/endpoint.hpp>

#if !defined(BOOST_ASIO_NO_IOSTREAM)
# include <iosfwd>
#endif // !defined(BOOST_ASIO_NO_IOSTREAM)

#include <boost/asio/detail/push_options.hpp>

namespace boost {
namespace asio {
namespace bluetooth {

/// Describes an endpoint for a Bluetooth socket.
/**
 * The boost::asio::bluetooth::basic_endpoint class template describes an endpoint
 * that may be associated with a particular Bluetooth socket.
 *
 * @par Thread Safety
 * @e Distinct @e objects: Safe.@n
 * @e Shared @e objects: Unsafe.
 *
 * @par Concepts:
 * Endpoint.
 */
template <typename Protocol>
class basic_endpoint
{
public:
  /// The protocol type associated with the endpoint.
  typedef Protocol protocol_type;

  /// The type of the endpoint structure. This type is dependent on the
  /// underlying implementation of the socket layer.
#if defined(GENERATING_DOCUMENTATION)
  typedef implementation_defined data_type;
#else
  typedef boost::asio::detail::socket_addr_type data_type;
#endif

  /// Default constructor.
  basic_endpoint() BOOST_ASIO_NOEXCEPT
    : impl_()
  {
  }

  // Construct an endpoint using an address and channel number.
  basic_endpoint(const boost::asio::bluetooth::address& addr,
      unsigned short channel_num) BOOST_ASIO_NOEXCEPT
    : impl_(addr, channel_num)
  {
  }

  /// The protocol associated with the endpoint.
  protocol_type protocol() const BOOST_ASIO_NOEXCEPT
  {
    return protocol_type();
  }

  /// Get the underlying endpoint in the native type.
  data_type* data() BOOST_ASIO_NOEXCEPT
  {
    return impl_.data();
  }

  /// Get the underlying endpoint in the native type.
  const data_type* data() const BOOST_ASIO_NOEXCEPT
  {
    return impl_.data();
  }

  /// Get the underlying size of the endpoint in the native type.
  std::size_t size() const BOOST_ASIO_NOEXCEPT
  {
    return impl_.size();
  }

  /// Set the underlying size of the endpoint in the native type.
  void resize(std::size_t new_size)
  {
    impl_.resize(new_size);
  }

  /// Get the capacity of the endpoint in the native type.
  std::size_t capacity() const BOOST_ASIO_NOEXCEPT
  {
    return impl_.capacity();
  }

  // Get the channel associated with the endpoint.
  unsigned short channel() const BOOST_ASIO_NOEXCEPT
  {
    return impl_.channel();
  }

  // Set the channel associated with the endpoint.
  void channel(unsigned short channel_num) BOOST_ASIO_NOEXCEPT
  {
    return impl_.channel(channel_num);
  }

  // Get the Bluetooth address associated with the endpoint.
  boost::asio::bluetooth::address address() const BOOST_ASIO_NOEXCEPT
  {
    return impl_.address();
  }

  // Set the Bluetooth address associated with the endpoint.
  void address(const boost::asio::bluetooth::address& addr) BOOST_ASIO_NOEXCEPT
  {
    return impl_.address(addr);
  }

  /// Compare two endpoints for equality.
  friend bool operator==(const basic_endpoint<Protocol>& e1,
      const basic_endpoint<Protocol>& e2)
  {
    return e1.impl_ == e2.impl_;
  }

  /// Compare two endpoints for inequality.
  friend bool operator!=(const basic_endpoint<Protocol>& e1,
      const basic_endpoint<Protocol>& e2)
  {
    return !(e1.impl_ == e2.impl_);
  }

  /// Compare endpoints for ordering.
  friend bool operator<(const basic_endpoint<Protocol>& e1,
      const basic_endpoint<Protocol>& e2)
  {
    return e1.impl_ < e2.impl_;
  }

  /// Compare endpoints for ordering.
  friend bool operator>(const basic_endpoint<Protocol>& e1,
      const basic_endpoint<Protocol>& e2)
  {
    return e2.impl_ < e1.impl_;
  }

  /// Compare endpoints for ordering.
  friend bool operator<=(const basic_endpoint<Protocol>& e1,
      const basic_endpoint<Protocol>& e2)
  {
    return !(e2 < e1);
  }

  /// Compare endpoints for ordering.
  friend bool operator>=(const basic_endpoint<Protocol>& e1,
      const basic_endpoint<Protocol>& e2)
  {
    return !(e1 < e2);
  }

private:
  // The underlying Bluetooth endpoint.
  boost::asio::bluetooth::detail::endpoint impl_;
};

/// Output an endpoint as a string.
/**
 * Used to output a human-readable string for a specified endpoint.
 *
 * @param os The output stream to which the string will be written.
 *
 * @param endpoint The endpoint to be written.
 *
 * @return The output stream.
 *
 * @relates boost::asio::bluetooth::basic_endpoint
 */
template <typename Elem, typename Traits, typename Protocol>
std::basic_ostream<Elem, Traits>& operator<<(
    std::basic_ostream<Elem, Traits>& os,
    const basic_endpoint<Protocol>& endpoint)
{
  os << boost::asio::bluetooth::detail::endpoint(endpoint.address(), endpoint.channel()).to_string();
  return os;
}

} // namespace bluetooth
} // namespace asio
} // namespace boost

#include <boost/asio/detail/pop_options.hpp>

#endif // defined(BOOST_ASIO_HAS_BLUETOOTH_SOCKETS)
       //   || defined(GENERATING_DOCUMENTATION)

#endif // BOOST_ASIO_BLUETOOTH_BASIC_ENDPOINT_HPP

max_stars_repo_name: huangqinjin/minapp

max_issues_repo_name: huangqinjin/minapp

max_forks_repo_name: huangqinjin/minapp


text:
#include <gtest/gtest.h>

#include "test/data/merkle_roots.json.h"
#include "test/data/merkle_serialization.json.h"
#include "test/data/merkle_witness_serialization.json.h"
#include "test/data/merkle_path.json.h"
#include "test/data/merkle_commitments.json.h"

#include "test/data/merkle_roots_sapling.json.h"
#include "test/data/merkle_serialization_sapling.json.h"
#include "test/data/merkle_witness_serialization_sapling.json.h"
#include "test/data/merkle_path_sapling.json.h"
#include "test/data/merkle_commitments_sapling.json.h"

#include <iostream>

#include <stdexcept>

#include "utilstrencodings.h"
#include "version.h"
#include "serialize.h"
#include "streams.h"

#include "zelcash/IncrementalMerkleTree.hpp"
#include "zelcash/util.h"

#include <boost/foreach.hpp>

#include "json_test_vectors.h"

using namespace std;

template<>
void expect_deser_same(const SproutTestingWitness& expected)
{
    // Cannot check this; IncrementalWitness cannot be
    // deserialized because it can only be constructed by
    // IncrementalMerkleTree, and it does not yet have a
    // canonical serialized representation.
}

template<typename A, typename B, typename C>
void expect_ser_test_vector(B& b, const C& c, const A& tree) {
    expect_test_vector<B, C>(b, c);
}

template<typename Tree, typename Witness>
void test_tree(
    UniValue commitment_tests,
    UniValue root_tests,
    UniValue ser_tests,
    UniValue witness_ser_tests,
    UniValue path_tests
)
{
    size_t witness_ser_i = 0;
    size_t path_i = 0;

    Tree tree;

    // The root of the tree at this point is expected to be the root of the
    // empty tree.
    ASSERT_TRUE(tree.root() == Tree::empty_root());

    // The tree doesn't have a 'last' element added since it's blank.
    ASSERT_THROW(tree.last(), std::runtime_error);

    // The tree is empty.
    ASSERT_TRUE(tree.size() == 0);

    // We need to witness at every single point in the tree, so
    // that the consistency of the tree and the merkle paths can
    // be checked.
    vector<Witness> witnesses;

    for (size_t i = 0; i < 16; i++) {
        uint256 test_commitment = uint256S(commitment_tests[i].get_str());

        // Witness here
        witnesses.push_back(tree.witness());

        // Now append a commitment to the tree
        tree.append(test_commitment);

        // Size incremented by one.
        ASSERT_TRUE(tree.size() == i+1);

        // Last element added to the tree was `test_commitment`
        ASSERT_TRUE(tree.last() == test_commitment);

        // Check tree root consistency
        expect_test_vector(root_tests[i], tree.root());

        // Check serialization of tree
        expect_ser_test_vector(ser_tests[i], tree, tree);

        bool first = true; // The first witness can never form a path
        BOOST_FOREACH(Witness& wit, witnesses)
        {
            // Append the same commitment to all the witnesses
            wit.append(test_commitment);

            if (first) {
                ASSERT_THROW(wit.path(), std::runtime_error);
                ASSERT_THROW(wit.element(), std::runtime_error);
            } else {
                auto path = wit.path();
                expect_test_vector(path_tests[path_i++], path);
            }

            // Check witness serialization
            expect_ser_test_vector(witness_ser_tests[witness_ser_i++], wit, tree);

            ASSERT_TRUE(wit.root() == tree.root());

            first = false;
        }
    }

    {
        // Tree should be full now
        ASSERT_THROW(tree.append(uint256()), std::runtime_error);

        BOOST_FOREACH(Witness& wit, witnesses)
        {
            ASSERT_THROW(wit.append(uint256()), std::runtime_error);
        }
    }
}

#define MAKE_STRING(x) std::string((x), (x)+sizeof(x))

TEST(merkletree, vectors) {
    UniValue root_tests = read_json(MAKE_STRING(json_tests::merkle_roots));
    UniValue ser_tests = read_json(MAKE_STRING(json_tests::merkle_serialization));
    UniValue witness_ser_tests = read_json(MAKE_STRING(json_tests::merkle_witness_serialization));
    UniValue path_tests = read_json(MAKE_STRING(json_tests::merkle_path));
    UniValue commitment_tests = read_json(MAKE_STRING(json_tests::merkle_commitments));

    test_tree<SproutTestingMerkleTree, SproutTestingWitness>(
        commitment_tests,
        root_tests,
        ser_tests,
        witness_ser_tests,
        path_tests
    );
}

TEST(merkletree, SaplingVectors) {
    UniValue root_tests = read_json(MAKE_STRING(json_tests::merkle_roots_sapling));
    UniValue ser_tests = read_json(MAKE_STRING(json_tests::merkle_serialization_sapling));
    UniValue witness_ser_tests = read_json(MAKE_STRING(json_tests::merkle_witness_serialization_sapling));
    UniValue path_tests = read_json(MAKE_STRING(json_tests::merkle_path_sapling));
    UniValue commitment_tests = read_json(MAKE_STRING(json_tests::merkle_commitments_sapling));

    test_tree<SaplingTestingMerkleTree, SaplingTestingWitness>(
        commitment_tests,
        root_tests,
        ser_tests,
        witness_ser_tests,
        path_tests
    );
}

TEST(merkletree, emptyroots) {
    libzelcash::EmptyMerkleRoots<64, libzelcash::SHA256Compress> emptyroots;
    std::array<libzelcash::SHA256Compress, 65> computed;

    computed.at(0) = libzelcash::SHA256Compress::uncommitted();
    ASSERT_TRUE(emptyroots.empty_root(0) == computed.at(0));
    for (size_t d = 1; d <= 64; d++) {
        computed.at(d) = libzelcash::SHA256Compress::combine(computed.at(d-1), computed.at(d-1), d-1);
        ASSERT_TRUE(emptyroots.empty_root(d) == computed.at(d));
    }

    // Double check that we're testing (at least) all the empty roots we'll use.
    ASSERT_TRUE(INCREMENTAL_MERKLE_TREE_DEPTH <= 64);
}

TEST(merkletree, EmptyrootsSapling) {
    libzelcash::EmptyMerkleRoots<62, libzelcash::PedersenHash> emptyroots;
    std::array<libzelcash::PedersenHash, 63> computed;

    computed.at(0) = libzelcash::PedersenHash::uncommitted();
    ASSERT_TRUE(emptyroots.empty_root(0) == computed.at(0));
    for (size_t d = 1; d <= 62; d++) {
        computed.at(d) = libzelcash::PedersenHash::combine(computed.at(d-1), computed.at(d-1), d-1);
        ASSERT_TRUE(emptyroots.empty_root(d) == computed.at(d));
    }

    // Double check that we're testing (at least) all the empty roots we'll use.
    ASSERT_TRUE(INCREMENTAL_MERKLE_TREE_DEPTH <= 62);
}

TEST(merkletree, emptyroot) {
    // This literal is the depth-20 empty tree root with the bytes reversed to
    // account for the fact that uint256S() loads a big-endian representation of
    // an integer which converted to little-endian internally.
    uint256 expected = uint256S("59d2cde5e65c1414c32ba54f0fe4bdb3d67618125286e6a191317917c812c6d7");

    ASSERT_TRUE(SproutMerkleTree::empty_root() == expected);
}

TEST(merkletree, EmptyrootSapling) {
    // This literal is the depth-20 empty tree root with the bytes reversed to
    // account for the fact that uint256S() loads a big-endian representation of
    // an integer which converted to little-endian internally.
    uint256 expected = uint256S("3e49b5f954aa9d3545bc6c37744661eea48d7c34e3000d82b7f0010c30f4c2fb");

    ASSERT_TRUE(SaplingMerkleTree::empty_root() == expected);
}

TEST(merkletree, deserializeInvalid) {
    // attempt to deserialize a small tree from a serialized large tree
    // (exceeds depth well-formedness check)
    SproutMerkleTree newTree;

    for (size_t i = 0; i < 16; i++) {
        newTree.append(uint256S("54d626e08c1c802b305dad30b7e54a82f102390cc92c7d4db112048935236e9c"));
    }

    newTree.append(uint256S("54d626e08c1c802b305dad30b7e54a82f102390cc92c7d4db112048935236e9c"));

    CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
    ss << newTree;

    SproutTestingMerkleTree newTreeSmall;
    ASSERT_THROW({ss >> newTreeSmall;}, std::ios_base::failure);
}

TEST(merkletree, deserializeInvalid2) {
    // the most ancestral parent is empty
    CDataStream ss(
        ParseHex("0155b852781b9995a44c939b64e441ae2724b96f99c8f4fb9a141cfc9842c4b0e3000100"),
        SER_NETWORK,
        PROTOCOL_VERSION
    );

    SproutMerkleTree tree;
    ASSERT_THROW(ss >> tree, std::ios_base::failure);
}

TEST(merkletree, deserializeInvalid3) {
    // left doesn't exist but right does
    CDataStream ss(
        ParseHex("000155b852781b9995a44c939b64e441ae2724b96f99c8f4fb9a141cfc9842c4b0e300"),
        SER_NETWORK,
        PROTOCOL_VERSION
    );

    SproutMerkleTree tree;
    ASSERT_THROW(ss >> tree, std::ios_base::failure);
}

TEST(merkletree, deserializeInvalid4) {
    // left doesn't exist but a parent does
    CDataStream ss(
        ParseHex("000001018695873d63ec0bceeadb5bf4ccc6723ac803c1826fc7cfb34fc76180305ae27d"),
        SER_NETWORK,
        PROTOCOL_VERSION
    );

    SproutMerkleTree tree;
    ASSERT_THROW(ss >> tree, std::ios_base::failure);
}

TEST(merkletree, testZeroElements) {
    for (int start = 0; start < 20; start++) {
        SproutMerkleTree newTree;

        ASSERT_TRUE(newTree.root() == SproutMerkleTree::empty_root());

        for (int i = start; i > 0; i--) {
            newTree.append(uint256S("54d626e08c1c802b305dad30b7e54a82f102390cc92c7d4db112048935236e9c"));
        }

        uint256 oldroot = newTree.root();

        // At this point, appending tons of null objects to the tree
        // should preserve its root.

        for (int i = 0; i < 100; i++) {
            newTree.append(uint256());
        }

        ASSERT_TRUE(newTree.root() == oldroot);
    }
}

max_stars_repo_name: moooooooo/zelcash


text:
//
// Created by jhwangbo on 30.11.16.
//

#ifndef RAI_TYPEDEF_HPP
#define RAI_TYPEDEF_HPP

#include <Eigen/Core>

namespace rai {

typedef typename Eigen::Matrix<double, 4, 1> Quaternion;
typedef typename Eigen::Matrix<double, 3, 1> EulerVector;
typedef typename Eigen::Matrix<double, 3, 3> RotationMatrix;
typedef typename Eigen::Matrix<double, 4, 4> HomogeneousTransform;
typedef typename Eigen::Matrix<double, 3, 1> Position;
typedef typename Eigen::Matrix<double, 3, 1> AngularVelocity;
typedef typename Eigen::Matrix<double, 3, 1> AngularAcceleration;
typedef typename Eigen::Matrix<double, 3, 1> LinearVelocity;
typedef typename Eigen::Matrix<double, 3, 1> LinearAcceleration;
typedef typename Eigen::Matrix<double, 3, 1> Axis;
typedef typename Eigen::Matrix<double, 3, 1> Torque;
typedef typename Eigen::Matrix<double, 3, 1> Force;
typedef typename Eigen::Matrix<double, 3, 3> Inertia;

typedef typename Eigen::Matrix<float, 4, 1> Quaternionf;
typedef typename Eigen::Matrix<float, 3, 1> EulerVectorf;
typedef typename Eigen::Matrix<float, 3, 3> RotationMatrixf;
typedef typename Eigen::Matrix<float, 3, 1> Positionf;
typedef typename Eigen::Matrix<float, 3, 1> AngularVelocityf;
typedef typename Eigen::Matrix<float, 3, 1> AngularAccelerationf;
typedef typename Eigen::Matrix<float, 3, 1> LinearVelocityf;
typedef typename Eigen::Matrix<float, 3, 1> LinearAccelerationf;
typedef typename Eigen::Matrix<float, 3, 1> Axisf;
typedef typename Eigen::Matrix<float, 3, 1> Torquef;
typedef typename Eigen::Matrix<float, 3, 1> Forcef;
typedef typename Eigen::Matrix<float, 3, 3> Inertiaf;

typedef typename Eigen::MatrixXd MatrixXd;
typedef typename Eigen::VectorXd VectorXd;

}

#endif //RAI_TYPEDEF_HPP

max_stars_repo_name: Wistral/raicommon

max_issues_repo_name: Wistral/raicommon

max_forks_repo_name: Wistral/raicommon


text:
/*
 * OutputProcessor_test.cpp
 *
 * Author: Anthony San Lucas
 * Email:  sanlucas@gmail.com
 */

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

BOOST_AUTO_TEST_SUITE(OutputProcessorTest)

BOOST_AUTO_TEST_CASE(firstTest) {
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: outpaddling/haplohseq

max_issues_repo_name: outpaddling/haplohseq

max_forks_repo_name: outpaddling/haplohseq


text:
// Copyright (c) 2014-2016 The Gcoin Core developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <boost/test/unit_test.hpp>

#include <stdint.h>

#include <map>
#include <string>
#include <iostream>

#include "test_gcoin.h"
#include "policy/licenseinfo.h"

using namespace std;

BOOST_AUTO_TEST_SUITE(handler_normal_test)

struct NormalHandlerFixture : public TestingSetup
{
    NormalHandlerFixture()
    {
        handler = type_transaction_handler::GetHandler(NORMAL);
    }
    ~NormalHandlerFixture()
    {
        handler = NULL;
    }
};

struct NormalHandlerCheckValidFixture : public NormalHandlerFixture
{
    NormalHandlerCheckValidFixture()
    {
        in_hash = ArithToUint256(arith_uint256(1));
        member_hash = ArithToUint256(arith_uint256(3));
        out_hash = ArithToUint256(arith_uint256(4));

        color = 5;
        pinfo = new CLicenseInfo();
        plicense->SetOwner(color, CreateAddress(), pinfo);

        member = CreateAddress();
        receiver = CreateAddress();
        CreateTransaction(in_hash, MINT);
        CreateTransaction(member_hash, NORMAL);
        CreateTransaction(out_hash, NORMAL);
        ConnectTransactions(in_hash, member_hash, COIN, member, color);
        ConnectTransactions(member_hash, out_hash, COIN, receiver, color);
    }

    ~NormalHandlerCheckValidFixture()
    {
        delete pinfo;
    }

    void CheckFalse(int ndos, const std::string &msg)
    {
        CValidationState state;
        bool ret;
        int v;

        ret = handler->CheckValid(
                CTransaction(transactions[member_hash]), state, NULL);
        ret &= handler->CheckFormat(
                CTransaction(transactions[member_hash]), state, NULL);

        BOOST_CHECK_MESSAGE(
                ret == false && state.IsInvalid(v) && v == ndos, msg);
    }

    uint256 in_hash, member_hash, out_hash;
    std::string member, receiver;
    type_Color color;
    CValidationState state;
    CLicenseInfo *pinfo;
};

BOOST_FIXTURE_TEST_CASE(NormalHandlerCheckValidPass, NormalHandlerCheckValidFixture)
{
    BOOST_CHECK(handler->CheckValid(
                CTransaction(transactions[member_hash]), state, NULL) == true);
}

BOOST_FIXTURE_TEST_CASE(NormalHandlerApplyNoMemberOnly, NormalHandlerFixture)
{
    type_Color color = 5;
    uint256 hash1 = ArithToUint256(arith_uint256(1));
    uint256 hash2 = ArithToUint256(arith_uint256(2));
    uint256 hash3 = ArithToUint256(arith_uint256(3));
    std::string issuer = CreateAddress();
    std::string member = CreateAddress();
    CreateTransaction(hash1, MINT);
    CreateTransaction(hash2, NORMAL);
    CreateTransaction(hash3, NORMAL);
    ConnectTransactions(hash1, hash2, COIN, issuer, color);
    ConnectTransactions(hash2, hash3, COIN, member, color);

    CLicenseInfo *pinfo = new CLicenseInfo();
    BOOST_CHECK(plicense->SetOwner(color, issuer, pinfo));
    BOOST_CHECK(handler->Apply(CTransaction(transactions[hash2]), NULL));
    delete pinfo;
}

BOOST_AUTO_TEST_SUITE_END();

max_stars_repo_name: buypolarbear/gcoin-community

max_issues_repo_name: buypolarbear/gcoin-community

max_forks_repo_name: buypolarbear/gcoin-community