text:
#include <Access/IAccessStorage.h>
#include <Access/Authentication.h>
#include <Access/Credentials.h>
#include <Access/User.h>
#include <Common/Exception.h>
#include <Common/quoteString.h>
#include <IO/WriteHelpers.h>
#include <Poco/UUIDGenerator.h>
#include <Poco/Logger.h>
#include <base/FnTraits.h>
#include <boost/algorithm/string/join.hpp>
#include <boost/algorithm/string/replace.hpp>

namespace DB
{
namespace ErrorCodes
{
    extern const int ACCESS_ENTITY_ALREADY_EXISTS;
    extern const int ACCESS_ENTITY_NOT_FOUND;
    extern const int ACCESS_STORAGE_READONLY;
    extern const int WRONG_PASSWORD;
    extern const int IP_ADDRESS_NOT_ALLOWED;
    extern const int LOGICAL_ERROR;
    extern const int NOT_IMPLEMENTED;
    extern const int AUTHENTICATION_FAILED;
}

namespace
{
    String outputID(const UUID & id)
    {
        return "ID(" + toString(id) + ")";
    }
}

std::vector<UUID> IAccessStorage::findAll(AccessEntityType type) const
{
    return findAllImpl(type);
}

std::optional<UUID> IAccessStorage::find(AccessEntityType type, const String & name) const
{
    return findImpl(type, name);
}

std::vector<UUID> IAccessStorage::find(AccessEntityType type, const Strings & names) const
{
    std::vector<UUID> ids;
    ids.reserve(names.size());
    for (const String & name : names)
    {
        auto id = findImpl(type, name);
        if (id)
            ids.push_back(*id);
    }
    return ids;
}

UUID IAccessStorage::getID(AccessEntityType type, const String & name) const
{
    auto id = findImpl(type, name);
    if (id)
        return *id;
    throwNotFound(type, name);
}

std::vector<UUID> IAccessStorage::getIDs(AccessEntityType type, const Strings & names) const
{
    std::vector<UUID> ids;
    ids.reserve(names.size());
    for (const String & name : names)
        ids.push_back(getID(type, name));
    return ids;
}

String IAccessStorage::readName(const UUID & id) const
{
    return *readNameImpl(id, /* throw_if_not_exists = */ true);
}

std::optional<String> IAccessStorage::readName(const UUID & id, bool throw_if_not_exists) const
{
    return readNameImpl(id, throw_if_not_exists);
}

Strings IAccessStorage::readNames(const std::vector<UUID> & ids, bool throw_if_not_exists) const
{
    Strings res;
    res.reserve(ids.size());
    for (const auto & id : ids)
    {
        if (auto name = readNameImpl(id, throw_if_not_exists))
            res.emplace_back(std::move(name).value());
    }
    return res;
}

std::optional<String> IAccessStorage::tryReadName(const UUID & id) const
{
    return readName(id, /* throw_if_not_exists = */ false);
}

Strings IAccessStorage::tryReadNames(const std::vector<UUID> & ids) const
{
    return readNames(ids, /* throw_if_not_exists = */ false);
}

std::optional<String> IAccessStorage::readNameImpl(const UUID & id, bool throw_if_not_exists) const
{
    if (auto entity = read(id, throw_if_not_exists))
        return entity->getName();
    return std::nullopt;
}

UUID IAccessStorage::insert(const AccessEntityPtr & entity)
{
    return *insert(entity, /* replace_if_exists = */ false, /* throw_if_exists = */ true);
}

std::optional<UUID> IAccessStorage::insert(const AccessEntityPtr & entity, bool replace_if_exists, bool throw_if_exists)
{
    return insertImpl(entity, replace_if_exists, throw_if_exists);
}

std::vector<UUID> IAccessStorage::insert(const std::vector<AccessEntityPtr> & multiple_entities, bool replace_if_exists, bool throw_if_exists)
{
    if (multiple_entities.empty())
        return {};

    if (multiple_entities.size() == 1)
    {
        if (auto id = insert(multiple_entities[0], replace_if_exists, throw_if_exists))
            return {*id};
        return {};
    }

    std::vector<AccessEntityPtr> successfully_inserted;
    try
    {
        std::vector<UUID> ids;
        for (const auto & entity : multiple_entities)
        {
            if (auto id = insertImpl(entity, replace_if_exists, throw_if_exists))
            {
                successfully_inserted.push_back(entity);
                ids.push_back(*id);
            }
        }
        return ids;
    }
    catch (Exception & e)
    {
        /// Try to add more information to the error message.
        if (!successfully_inserted.empty())
        {
            String successfully_inserted_str;
            for (const auto & entity : successfully_inserted)
            {
                if (!successfully_inserted_str.empty())
                    successfully_inserted_str += ", ";
                successfully_inserted_str += entity->formatTypeWithName();
            }
            e.addMessage("After successfully inserting {}/{}: {}", successfully_inserted.size(), multiple_entities.size(), successfully_inserted_str);
        }
        e.rethrow();
        __builtin_unreachable();
    }
}

std::optional<UUID> IAccessStorage::tryInsert(const AccessEntityPtr & entity)
{
    return insert(entity, /* replace_if_exists = */ false, /* throw_if_exists = */ false);
}

std::vector<UUID> IAccessStorage::tryInsert(const std::vector<AccessEntityPtr> & multiple_entities)
{
    return insert(multiple_entities, /* replace_if_exists = */ false, /* throw_if_exists = */ false);
}

UUID IAccessStorage::insertOrReplace(const AccessEntityPtr & entity)
{
    return *insert(entity, /* replace_if_exists = */ true, /* throw_if_exists = */ false);
}

std::vector<UUID> IAccessStorage::insertOrReplace(const std::vector<AccessEntityPtr> & multiple_entities)
{
    return insert(multiple_entities, /* replace_if_exists = */ true, /* throw_if_exists = */ false);
}

std::optional<UUID> IAccessStorage::insertImpl(const AccessEntityPtr & entity, bool, bool)
{
    if (isReadOnly())
        throwReadonlyCannotInsert(entity->getType(), entity->getName());
    throw Exception(ErrorCodes::NOT_IMPLEMENTED, "insertImpl() is not implemented in {}", getStorageType());
}

bool IAccessStorage::remove(const UUID & id, bool throw_if_not_exists)
{
    return removeImpl(id, throw_if_not_exists);
}

std::vector<UUID> IAccessStorage::remove(const std::vector<UUID> & ids, bool throw_if_not_exists)
{
    if (ids.empty())
        return {};
    if (ids.size() == 1)
        return remove(ids[0], throw_if_not_exists) ? ids : std::vector<UUID>{};

    Strings removed_names;
    try
    {
        std::vector<UUID> removed_ids;
        std::vector<UUID> readonly_ids;

        /// First we call remove() for non-readonly entities.
        for (const auto & id : ids)
        {
            if (isReadOnly(id))
                readonly_ids.push_back(id);
            else
            {
                auto name = tryReadName(id);
                if (remove(id, throw_if_not_exists))
                {
                    removed_ids.push_back(id);
                    if (name)
                        removed_names.push_back(std::move(name).value());
                }
            }
        }

        /// For readonly entities we're still going to call remove() because
        /// isReadOnly(id) could change and even if it's not then a storage-specific
        /// implementation of removeImpl() will probably generate a better error message.
        for (const auto & id : readonly_ids)
        {
            auto name = tryReadName(id);
            if (remove(id, throw_if_not_exists))
            {
                removed_ids.push_back(id);
                if (name)
                    removed_names.push_back(std::move(name).value());
            }
        }

        return removed_ids;
    }
    catch (Exception & e)
    {
        /// Try to add more information to the error message.
        if (!removed_names.empty())
        {
            String removed_names_str;
            for (const auto & name : removed_names)
            {
                if (!removed_names_str.empty())
                    removed_names_str += ", ";
                removed_names_str += backQuote(name);
            }
            e.addMessage("After successfully removing {}/{}: {}", removed_names.size(), ids.size(), removed_names_str);
        }
        e.rethrow();
        __builtin_unreachable();
    }
}

bool IAccessStorage::tryRemove(const UUID & id)
{
    return remove(id, /* throw_if_not_exists = */ false);
}

std::vector<UUID> IAccessStorage::tryRemove(const std::vector<UUID> & ids)
{
    return remove(ids, /* throw_if_not_exists = */ false);
}

bool IAccessStorage::removeImpl(const UUID & id, bool throw_if_not_exists)
{
    if (isReadOnly(id))
    {
        auto entity = read(id, throw_if_not_exists);
        if (!entity)
            return false;
        throwReadonlyCannotRemove(entity->getType(), entity->getName());
    }
    throw Exception(ErrorCodes::NOT_IMPLEMENTED, "removeImpl() is not implemented in {}", getStorageType());
}

bool IAccessStorage::update(const UUID & id, const UpdateFunc & update_func, bool throw_if_not_exists)
{
    return updateImpl(id, update_func, throw_if_not_exists);
}

std::vector<UUID> IAccessStorage::update(const std::vector<UUID> & ids, const UpdateFunc & update_func, bool throw_if_not_exists)
{
    if (ids.empty())
        return {};
    if (ids.size() == 1)
        return update(ids[0], update_func, throw_if_not_exists) ? ids : std::vector<UUID>{};

    Strings names_of_updated;
    try
    {
        std::vector<UUID> ids_of_updated;
        std::vector<UUID> readonly_ids;

        /// First we call update() for non-readonly entities.
        for (const auto & id : ids)
        {
            if (isReadOnly(id))
                readonly_ids.push_back(id);
            else
            {
                auto name = tryReadName(id);
                if (update(id, update_func, throw_if_not_exists))
                {
                    ids_of_updated.push_back(id);
                    if (name)
                        names_of_updated.push_back(std::move(name).value());
                }
            }
        }

        /// For readonly entities we're still going to call update() because
        /// isReadOnly(id) could change and even if it's not then a storage-specific
        /// implementation of updateImpl() will probably generate a better error message.
        for (const auto & id : readonly_ids)
        {
            auto name = tryReadName(id);
            if (update(id, update_func, throw_if_not_exists))
            {
                ids_of_updated.push_back(id);
                if (name)
                    names_of_updated.push_back(std::move(name).value());
            }
        }

        return ids_of_updated;
    }
    catch (Exception & e)
    {
        /// Try to add more information to the error message.
        if (!names_of_updated.empty())
        {
            String names_of_updated_str;
            for (const auto & name : names_of_updated)
            {
                if (!names_of_updated_str.empty())
                    names_of_updated_str += ", ";
                names_of_updated_str += backQuote(name);
            }
            e.addMessage("After successfully updating {}/{}: {}", names_of_updated.size(), ids.size(), names_of_updated_str);
        }
        e.rethrow();
        __builtin_unreachable();
    }
}

bool IAccessStorage::tryUpdate(const UUID & id, const UpdateFunc & update_func)
{
    return update(id, update_func, /* throw_if_not_exists = */ false);
}

std::vector<UUID> IAccessStorage::tryUpdate(const std::vector<UUID> & ids, const UpdateFunc & update_func)
{
    return update(ids, update_func, /* throw_if_not_exists = */ false);
}

bool IAccessStorage::updateImpl(const UUID & id, const UpdateFunc &, bool throw_if_not_exists)
{
    if (isReadOnly(id))
    {
        auto entity = read(id, throw_if_not_exists);
        if (!entity)
            return false;
        throwReadonlyCannotUpdate(entity->getType(), entity->getName());
    }
    throw Exception(ErrorCodes::NOT_IMPLEMENTED, "updateImpl() is not implemented in {}", getStorageType());
}

scope_guard IAccessStorage::subscribeForChanges(AccessEntityType type, const OnChangedHandler & handler) const
{
    return subscribeForChangesImpl(type, handler);
}

scope_guard IAccessStorage::subscribeForChanges(const UUID & id, const OnChangedHandler & handler) const
{
    return subscribeForChangesImpl(id, handler);
}

scope_guard IAccessStorage::subscribeForChanges(const std::vector<UUID> & ids, const OnChangedHandler & handler) const
{
    scope_guard subscriptions;
    for (const auto & id : ids)
        subscriptions.join(subscribeForChangesImpl(id, handler));
    return subscriptions;
}

void IAccessStorage::notify(const Notifications & notifications)
{
    for (const auto & [fn, id, new_entity] : notifications)
        fn(id, new_entity);
}

UUID IAccessStorage::authenticate(
    const Credentials & credentials,
    const Poco::Net::IPAddress & address,
    const ExternalAuthenticators & external_authenticators, bool allow_no_password, bool allow_plaintext_password) const
{
    return *authenticateImpl(credentials, address, external_authenticators, /* throw_if_user_not_exists = */ true, allow_no_password, allow_plaintext_password);
}

std::optional<UUID> IAccessStorage::authenticate(
    const Credentials & credentials,
    const Poco::Net::IPAddress & address,
    const ExternalAuthenticators & external_authenticators,
    bool throw_if_user_not_exists, bool allow_no_password, bool allow_plaintext_password) const
{
    return authenticateImpl(credentials, address, external_authenticators, throw_if_user_not_exists, allow_no_password, allow_plaintext_password);
}

std::optional<UUID> IAccessStorage::authenticateImpl(
    const Credentials & credentials,
    const Poco::Net::IPAddress & address,
    const ExternalAuthenticators & external_authenticators,
    bool throw_if_user_not_exists, bool allow_no_password, bool allow_plaintext_password) const
{
    if (auto id = find<User>(credentials.getUserName()))
    {
        if (auto user = tryRead<User>(*id))
        {
            if (!isAddressAllowed(*user, address))
                throwAddressNotAllowed(address);
            if (isNoPasswordAllowed(*user, allow_no_password) || isPlaintextPasswordAllowed(*user, allow_plaintext_password))
                throwPasswordTypeNotAllowed();

            if (!areCredentialsValid(*user, credentials, external_authenticators))
                throwInvalidCredentials();

            return id;
        }
    }

    if (throw_if_user_not_exists)
        throwNotFound(AccessEntityType::USER, credentials.getUserName());
    else
        return std::nullopt;
}

bool IAccessStorage::areCredentialsValid(
    const User & user,
    const Credentials & credentials,
    const ExternalAuthenticators & external_authenticators) const
{
    if (!credentials.isReady())
        return false;

    if (credentials.getUserName() != user.getName())
        return false;

    return Authentication::areCredentialsValid(credentials, user.auth_data, external_authenticators);
}

bool IAccessStorage::isAddressAllowed(const User & user, const Poco::Net::IPAddress & address) const
{
    return user.allowed_client_hosts.contains(address);
}

bool IAccessStorage::isPlaintextPasswordAllowed(const User & user, bool allow_plaintext_password)
{
    return !allow_plaintext_password && user.auth_data.getType() == AuthenticationType::PLAINTEXT_PASSWORD;
}

bool IAccessStorage::isNoPasswordAllowed(const User & user, bool allow_no_password)
{
    return !allow_no_password && user.auth_data.getType() == AuthenticationType::NO_PASSWORD;
}

UUID IAccessStorage::generateRandomID()
{
    static Poco::UUIDGenerator generator;
    UUID id;
    generator.createRandom().copyTo(reinterpret_cast<char *>(&id));
    return id;
}

Poco::Logger * IAccessStorage::getLogger() const
{
    Poco::Logger * ptr = log.load();
    if (!ptr)
        log.store(ptr = &Poco::Logger::get("Access(" + storage_name + ")"), std::memory_order_relaxed);
    return ptr;
}

void IAccessStorage::throwNotFound(const UUID & id) const
{
    throw Exception(outputID(id) + " not found in " + getStorageName(), ErrorCodes::ACCESS_ENTITY_NOT_FOUND);
}

void IAccessStorage::throwNotFound(AccessEntityType type, const String & name) const
{
    int error_code = AccessEntityTypeInfo::get(type).not_found_error_code;
    throw Exception("There is no " + formatEntityTypeWithName(type, name) + " in " + getStorageName(), error_code);
}

void IAccessStorage::throwBadCast(const UUID & id, AccessEntityType type, const String & name, AccessEntityType required_type)
{
    throw Exception(
        outputID(id) + ": " + formatEntityTypeWithName(type, name) + " expected to be of type " + toString(required_type),
        ErrorCodes::LOGICAL_ERROR);
}

void IAccessStorage::throwIDCollisionCannotInsert(const UUID & id, AccessEntityType type, const String & name, AccessEntityType existing_type, const String & existing_name) const
{
    throw Exception(
        formatEntityTypeWithName(type, name) + ": cannot insert because the " + outputID(id) + " is already used by "
            + formatEntityTypeWithName(existing_type, existing_name) + " in " + getStorageName(),
        ErrorCodes::ACCESS_ENTITY_ALREADY_EXISTS);
}

void IAccessStorage::throwNameCollisionCannotInsert(AccessEntityType type, const String & name) const
{
    throw Exception(
        formatEntityTypeWithName(type, name) + ": cannot insert because " + formatEntityTypeWithName(type, name) + " already exists in "
            + getStorageName(),
        ErrorCodes::ACCESS_ENTITY_ALREADY_EXISTS);
}

void IAccessStorage::throwNameCollisionCannotRename(AccessEntityType type, const String & old_name, const String & new_name) const
{
    throw Exception(
        formatEntityTypeWithName(type, old_name) + ": cannot rename to " + backQuote(new_name) + " because "
            + formatEntityTypeWithName(type, new_name) + " already exists in " + getStorageName(),
        ErrorCodes::ACCESS_ENTITY_ALREADY_EXISTS);
}

void IAccessStorage::throwReadonlyCannotInsert(AccessEntityType type, const String & name) const
{
    throw Exception(
        "Cannot insert " + formatEntityTypeWithName(type, name) + " to " + getStorageName() + " because this storage is readonly",
        ErrorCodes::ACCESS_STORAGE_READONLY);
}

void IAccessStorage::throwReadonlyCannotUpdate(AccessEntityType type, const String & name) const
{
    throw Exception(
        "Cannot update " + formatEntityTypeWithName(type, name) + " in " + getStorageName() + " because this storage is readonly",
        ErrorCodes::ACCESS_STORAGE_READONLY);
}

void IAccessStorage::throwReadonlyCannotRemove(AccessEntityType type, const String & name) const
{
    throw Exception(
        "Cannot remove " + formatEntityTypeWithName(type, name) + " from " + getStorageName() + " because this storage is readonly",
        ErrorCodes::ACCESS_STORAGE_READONLY);
}

void IAccessStorage::throwAddressNotAllowed(const Poco::Net::IPAddress & address)
{
    throw Exception("Connections from " + address.toString() + " are not allowed", ErrorCodes::IP_ADDRESS_NOT_ALLOWED);
}

void IAccessStorage::throwPasswordTypeNotAllowed()
{
    throw Exception(
        "Authentication denied for users configured with AuthType PLAINTEXT_PASSWORD and NO_PASSWORD. Please check with Clickhouse admin to allow allow  PLAINTEXT_PASSWORD and NO_PASSWORD through server configuration ",
        ErrorCodes::AUTHENTICATION_FAILED);
}
void IAccessStorage::throwInvalidCredentials()
{
    throw Exception("Invalid credentials", ErrorCodes::WRONG_PASSWORD);
}

}


text:
//---------------------------------------------------------------------------//
//!
//! \file   Utility_Measurement.hpp
//! \author Alex Robinson
//! \brief  The measurement class declaration. This object is based of of the
//!         measurement class in the boost::units examples
//!
//---------------------------------------------------------------------------//

#ifndef UTILITY_MEASUREMENT_HPP
#define UTILITY_MEASUREMENT_HPP

// Boost Includes
#include <boost/units/config.hpp>
#include <boost/units/operators.hpp>
#include <boost/typeof/typeof.hpp>

// FRENSIE Includes
#include "Utility_QuantityTraits.hpp"
#include "Utility_OStreamableObject.hpp"
#include "Utility_TypeTraits.hpp"
#include "Utility_DesignByContract.hpp"

namespace Utility{

/*! The measurement class
 *
 * The default template is not defined.
 */
template<typename T, typename Enabled = void>
class Measurement;

/*! The measurement class (for all floating-point types)
 *
 * This class wraps is meant to be used as any typical scalar type
 * (e.g. double). It is designed to keep track of and propagate the
 * uncertainty of a value (like one would with a measured quantity).
 */
template<typename T>
class Measurement<T,typename std::enable_if<std::is_floating_point<T>::value>::type> : public OStreamableObject
{

private:

  // The quantity traits typedef
  typedef QuantityTraits<T> QT;

public:

  //! The typedef for this type
  typedef Measurement<T> ThisType;

  //! The typedef for the value type
  typedef T ValueType;

  //! Constructor
  explicit Measurement( const ValueType& value = QT::zero(),
                        const ValueType& uncertainty = QT::zero() );

  //! Copy constructor
  Measurement( const ThisType& other_measurement );

  //! Destructor
  ~Measurement()
  { /* ... */ }

  //! Method for placing the object in an output stream
  void toStream( std::ostream& os ) const override;

  //! Return the value of the measurement
  const ValueType& getValue() const;

  //! Return the uncertainty of the measurement
  const ValueType& getUncertainty() const;

  //! Return the relative uncertainty of the measurement
  ValueType getRelativeUncertainty() const;

  //! Return the lower bound of the measurement
  ValueType getLowerBound() const;

  //! Return the upper bound of the measurement
  ValueType getUpperBound() const;

  //! In-place addition operator
  ThisType& operator+=( const ValueType& value );

  //! In-place addition operator
  ThisType& operator+=( const ThisType& other_measurement );

  //! In-place subtraction operator
  ThisType& operator-=( const ValueType& value );

  //! In-place subtraction operator
  ThisType& operator-=( const ThisType& other_measurement );

  //! In-place multiplication operator
  ThisType& operator*=( const ValueType& value );

  //! In-place multiplication operator
  ThisType& operator*=( const ThisType& other_measurement );

  //! In-place division operator
  ThisType& operator/=( const ValueType& value );

  //! In-place division operator
  ThisType& operator/=( const ThisType& other_measurement );

private:

  // The measurement value
  ValueType d_value;

  // The measurement uncertainty
  ValueType d_uncertainty;
};

//! Addition operator
template<typename T>
inline Measurement<T> operator+( T lhs, const Measurement<T>& rhs )
{
  // Make sure nested conditions are met
  testNestedConditionsBegin(1);

  return (Measurement<T>( lhs, T(0) ) += rhs);

  testNestedConditionsEnd(1);
}

//! Addition operator
template<typename T>
inline Measurement<T> operator+( const Measurement<T>& lhs, T rhs )
{
  // Make sure nested conditions are met
  testNestedConditionsBegin(1);

  return (Measurement<T>( lhs ) += Measurement<T>( rhs, T(0) ));

  testNestedConditionsEnd(1);
}

//! Addition operator
template<typename T>
inline Measurement<T> operator+( const Measurement<T>& lhs,
				 const Measurement<T>& rhs )
{
  // Make sure nested conditions are met
  testNestedConditionsBegin(1);

  return (Measurement<T>( lhs ) += rhs );

  testNestedConditionsEnd(1);
}

//! Subtraction operator
template<typename T>
inline Measurement<T> operator-( T lhs, const Measurement<T>& rhs )
{
  // Make sure nested conditions are met
  testNestedConditionsBegin(1);

  return (Measurement<T>( lhs, T(0) ) -= rhs);

  testNestedConditionsEnd(1);
}

//! Subtraction operator
template<typename T>
inline Measurement<T> operator-( const Measurement<T>& lhs, T rhs )
{
  // Make sure nested conditions are met
  testNestedConditionsBegin(1);

  return (Measurement<T>( lhs ) -= Measurement<T>( rhs, T(0) ));

  testNestedConditionsEnd(1);
}

//! Subtraction operator
template<typename T>
inline Measurement<T> operator-( const Measurement<T>& lhs,
				 const Measurement<T>& rhs )
{
  // Make sure nested conditions are met
  testNestedConditionsBegin(1);

  return (Measurement<T>( lhs ) -= rhs );

  testNestedConditionsEnd(1);
}

//! Multiplication operator
template<typename T>
inline Measurement<T> operator*( T lhs, const Measurement<T>& rhs )
{
  // Make sure nested conditions are met
  testNestedConditionsBegin(1);

  return (Measurement<T>( lhs, T(0) ) *= rhs);

  testNestedConditionsEnd(1);
}

//! Multiplication operator
template<typename T>
inline Measurement<T> operator*( const Measurement<T>& lhs, T rhs )
{
  // Make sure nested conditions are met
  testNestedConditionsBegin(1);

  return (Measurement<T>( lhs ) *= Measurement<T>( rhs, T(0) ));

  testNestedConditionsEnd(1);
}

//! Multiplication operator
template<typename T>
inline Measurement<T> operator*( const Measurement<T>& lhs,
				 const Measurement<T>& rhs )
{
  // Make sure nested conditions are met
  testNestedConditionsBegin(1);

  return (Measurement<T>( lhs ) *= rhs );

  testNestedConditionsEnd(1);
}

//! Division operator
template<typename T>
inline Measurement<T> operator/( T lhs, const Measurement<T>& rhs )
{
  // Make sure nested conditions are met
  testNestedConditionsBegin(1);

  // Make sure nested conditions are met
  return (Measurement<T>( lhs, T(0) ) /= rhs);

  testNestedConditionsEnd(1);
}

//! Division operator
template<typename T>
inline Measurement<T> operator/( const Measurement<T>& lhs, T rhs )
{
  // Make sure nested conditions are met
  testNestedConditionsBegin(1);

  return (Measurement<T>( lhs ) /= Measurement<T>( rhs, T(0) ));

  testNestedConditionsEnd(1);
}

//! Division operator
template<typename T>
inline Measurement<T> operator/( const Measurement<T>& lhs,
				 const Measurement<T>& rhs )
{
  // Make sure nested conditions are met
  testNestedConditionsBegin(1);

  return (Measurement<T>( lhs ) /= rhs );

  testNestedConditionsEnd(1);
}

/*! Partial specialization of Utility::QuantityTraits for Utility::Measurement
 * \ingroup quantity_traits
 */
template<typename T>
struct QuantityTraits<Measurement<T>,typename std::enable_if<std::is_floating_point<T>::value>::type>;

/*! \brief Partial specialization of Utility::QuantityTraits for
 * boost::units::quantity<Unit,Utility::Measurement> types
 * \ingroup quantity_traits
 */
template<typename Unit, typename T>
struct QuantityTraits<boost::units::quantity<Unit,Measurement<T> >,typename std::enable_if<std::is_floating_point<T>::value>::type>;

} // end Utility namespace

namespace std{

//! Overload of sqrt for a measurement
template<typename T>
Utility::Measurement<T> sqrt( const Utility::Measurement<T>& x );

//! Overload of cbrt for a measurement
template<typename T>
Utility::Measurement<T> cbrt( const Utility::Measurement<T>& x );

//! Overload of pow for a measurement
template<typename T, typename ExponentType>
Utility::Measurement<T> pow( const Utility::Measurement<T>& x,
                             const ExponentType exponent );

} // end std namespace

// Allow the above overloads to be accessed in the global namespace
using std::sqrt;
using std::cbrt;
using std::pow;

//---------------------------------------------------------------------------//
// Template Includes
//---------------------------------------------------------------------------//

#include "Utility_Measurement_def.hpp"

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

#endif // end UTILITY_MEASUREMENT_HPP

//---------------------------------------------------------------------------//
// end Utility_Measurement.hpp
//---------------------------------------------------------------------------//

ext: hpp


text:
/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2015 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

// NOTE: This is an implementation header file and is only meant to be included
//    from implementation files. It therefore doesn't have an include guard.
// mapnik
#include <mapnik/svg/svg_points_grammar.hpp>
#include <mapnik/svg/svg_path_commands.hpp>

#pragma GCC diagnostic push
#include <mapnik/warning_ignore.hpp>
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix_function.hpp>
#include <boost/spirit/include/phoenix_core.hpp>
#include <boost/spirit/include/phoenix_operator.hpp>
#pragma GCC diagnostic pop

namespace mapnik { namespace svg {

using namespace boost::spirit;
using namespace boost::phoenix;

template <typename Iterator, typename PathType, typename SkipType>
svg_points_grammar<Iterator, PathType,SkipType>::svg_points_grammar()
    : svg_points_grammar::base_type(start)
{
    qi::_1_type _1;
    qi::_r1_type _r1;
    qi::lit_type lit;
    qi::double_type double_;
    // commands
    function<move_to> move_to_;
    function<line_to> line_to_;
    function<close> close_;

    start = coord[move_to_(_r1, _1, false)] // move_to
        >> *(-lit(',') >> coord [ line_to_(_r1, _1,false) ] ); // *line_to

    coord = double_ >> -lit(',') >> double_;
}

}}


text:
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2017-2019 The WaykiChain Developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <stdlib.h>
#include <time.h>
#include "main.h"
#include "miner/miner.h"
#include "commons/uint256.h"
#include "commons/util/util.h"
#include <boost/foreach.hpp>
#include <boost/test/unit_test.hpp>

#include "commons/json/json_spirit_writer_template.h"
#include "CBlackHalo_tests.h"
#include "./rpc/core/rpcclient.h"

#include "CycleP2PBet_tests.h"

using namespace std;
using namespace boost;
using namespace json_spirit;

#include "CycleTestManger.h"
#include "CycleSesureTrade_tests.h"
#include "CreateTx_tests.h"

void CycleTestManger::Initialize() {
//	vTest.push_back(std::make_shared<CTestSesureTrade>());
//	vTest.push_back(std::make_shared<CTestSesureTrade>());
//	vTest.push_back(std::make_shared<CTestSesureTrade>());
	for (int i = 0; i < 100; i++)
		vTest.push_back(std::make_shared<CBlackHalo>());
	for (int i = 0; i < 100; i++)
		vTest.push_back(std::make_shared<CTestBetTx>());
//	for (int i = 0; i < 300; i++)
//		vTest.push_back(std::make_shared<CCreateTxTest>());
}

void CycleTestManger::Initialize(vector<std::shared_ptr<CycleTestBase> > &vTestIn) {
	vTest = vTestIn;
}

void CycleTestManger::Run() {
	while (vTest.size() > 0) {
		for (auto it = vTest.begin(); it != vTest.end();) {
			bool flag = false;
			try {
				if (it->get()->Run() == end_state) {
					flag = true;
				};
			} catch (...) {
				flag = true;
			}

			if (flag)
				it = vTest.erase(it);
			else
				++it;

		}
		MilliSleep(1000);
	}
}

BOOST_FIXTURE_TEST_SUITE(CycleTest,CycleTestManger)

BOOST_FIXTURE_TEST_CASE(Cycle,CycleTestManger)
{
	Initialize();
	Run();
}

BOOST_AUTO_TEST_SUITE_END()

ext: cpp

max_stars_repo_name: nondejus/WaykiChain

max_issues_repo_name: linnbenton/WaykiChain

max_forks_repo_name: linnbenton/WaykiChain


text:
#ifndef __SPARSEQUADRATURE__CLASS__
#define __SPARSEQUADRATURE__CLASS__

#include <algorithm>

#include <Eigen/Dense>

#include "CONSTANTS.hpp"

#include "SparseIndexSet.hpp"
#include "TensorProductQuadrature.hpp"
#include "UnivariateQuadrature.hpp"

class SparseQuadrature {
 public:
  SparseQuadrature(void){};
  SparseQuadrature(const SparseIndexSet &spInd, UnivariateQuadrature &Q);
  void computeSparseQuadrature(const SparseIndexSet &spInd,
                               UnivariateQuadrature &Q);
  void purgeSparseQuadrature(void);
  const Eigen::MatrixXd &get_qPoints(void) const;
  const Eigen::VectorXd &get_qWeights(void) const;

 protected:
  Eigen::MatrixXd _qPoints;
  Eigen::VectorXd _qWeights;

  struct lexiCompareInd {
    const double *array;
    int N;
    lexiCompareInd(const Eigen::MatrixXd &A)
        : array(&(A(0, 0))), N((int)A.rows()){};

    bool operator()(const int &i, const int &j) {
      return std::lexicographical_compare(array + i * N, array + i * N + N,
                                          array + j * N, array + j * N + N);
    }
  };

  bool isEqual(const Eigen::VectorXd &vec1, const Eigen::VectorXd &vec2) {
    if (vec1.size() != vec2.size())
      return false;
    else if ((vec1 - vec2).lpNorm<Eigen::Infinity>() < __PRECISION__)
      return true;
    else
      return false;
  }
};

#endif


text:
#ifndef AUDIO_PARAMS_HPP
#define AUDIO_PARAMS_HPP

#include <scluk/aliases.hpp>
#include <scluk/array.hpp>
#include <boost/fiber/buffered_channel.hpp>
#include <bit>
#include "portaudio/stream_wrapper.hpp"
#include "dft/sliding_dft.hpp"

namespace audio {
    using scluk::u64, scluk::f32, scluk::heap_array;
    #ifndef LOWER_PERFORMANCE_MODE
    constexpr u64 ft_win = 1024;
    constexpr u64 rate = ft_win*50;//~40-50k
    constexpr u64 ift_overlap = 4;
    constexpr u64 ft_dist = ft_win / ift_overlap;
    #else
    constexpr u64 rate = 10000;
    constexpr u64 ft_win = 512;
    constexpr u64 ift_overlap = 4;
    constexpr u64 ft_dist = ft_win / ift_overlap;
    #endif
    using sliding_dft = dft::sliding_dft<f32, ft_win>;
    using dft_array = sliding_dft::dft_array;
    using frame_chunk = scluk::heap_array<f32, ft_dist>;
    using ift_chunk = scluk::heap_array<f32, ft_win>;
    using gui_simplex_chan = boost::fibers::buffered_channel<dft_array>;

    static_assert(std::has_single_bit(ft_win), "ft_win must be a power of two to allow us to use cooley-tukey ifft");

    struct duplex_chan {
        boost::fibers::buffered_channel<audio::frame_chunk> cb_to_main, main_to_cb;
        duplex_chan(u64 cb_to_main_sz=2, u64 main_to_cb_sz=2) : cb_to_main(cb_to_main_sz), main_to_cb(main_to_cb_sz) {}
    };

    int cb(const void* v_i_buf, void* v_o_buf, [[maybe_unused]]u64 frames, auto, auto, void* userdata) {
        using namespace std::chrono_literals;
        assert(frames == audio::ft_dist && "You were my brother Anakin");
        auto& chans = *reinterpret_cast<audio::duplex_chan*>(userdata);
        const f32* i_buf = reinterpret_cast<const f32*>(v_i_buf);
        f32* o_buf = reinterpret_cast<f32*>(v_o_buf);
        audio::frame_chunk to_main, to_pa;

        std::copy(i_buf, i_buf + to_main.size(), to_main.begin());
        chans.cb_to_main.push_wait_for(std::move(to_main), 100ms);

        chans.main_to_cb.pop_wait_for(to_pa, 100ms);
        std::copy(to_pa.begin(), to_pa.end(), o_buf);

        return paContinue;
    }
}

#endif

max_stars_repo_name: circled-square/helium

max_issues_repo_name: circled-square/helium

max_forks_repo_name: circled-square/helium